New here. I'm trying to use onclick to switch out some images that i have assigned to variables in my script but i can't get it to work. Any ideas?
let doorImage1 = document.getElementById("door1");
let botDoorPath ='https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/robot.svg';
doorImage1.onclick= () =>{
doorImage1.src = botDoorPath;
}
This did not work for me until I set the src in the element to something first. Seems to be working, so perhaps your element was not found. Look at console to see if it was undefined.
let doorImage1 = document.getElementById("door1");
let botDoorPath = 'https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/robot.svg';
doorImage1.onclick = () => {
console.log('click')
doorImage1.src = botDoorPath;
}
<html>
<img src='./missing.png' id='door1'></img>
</html>
Related
I'm trying to add the attributes dynamically to an img tag but only onmouseenter is not been included else everything is been added perfectly
let img_elem = document.createElement('img')
img_elem.src = movies[i].large_cover_image
img_elem.alt = 'poster'
img_elem.id = i
img_elem.className ='poster'
img_elem.onmouseover = 'give_me_id(this)'
This is my HTML after adding attributes dynamically
<img src="https://yts.mx/assets/images/movies/woodstock_99_peace_love_and_rage_2021/large-cover.jpg" alt="poster" id="0" class="poster">
Just an issue with onmouseover else everything working perfectly.
I have already found other ways to add onmouseover attribute but the above method seems to be easier than I have used, so let me know the issue here. Thank you in advance
It's not working because we are trying to add the attribute but what we really want is add event listener. Below is the code please try it out
let img_elem = document.createElement('img');
img_elem.src = 'https://upload.wikimedia.org/wikipedia/commons/1/12/User_icon_2.svg'
img_elem.alt = 'poster';
img_elem.id = 'img1'; //i;
img_elem.className ='poster';
img_elem.addEventListener("mouseover",function(event){console.log('mouseover');});
document.getElementById('imgParent').appendChild(img_elem);
<div id='imgParent'>
</div>
I'm guessing that you're following the W3Schools example, but the example is adding a method through the attribute. You can't really do that in javascript code. Instead, you send in a function and then use event.target to get which image that the user is hovering. I'm taking one more step, and using shorthand properties (I think that's the name) to get target directly by using {target}.
Another way is to add an eventlistener instead, like in Bharat's answer.
const imageIds = [100, 200, 400];
for (const id of imageIds) {
let img_elem = document.createElement('img');
img_elem.src = `https://picsum.photos/id/${id}/200/200`;
img_elem.alt = 'poster';
img_elem.id = id;
img_elem.className = 'poster';
img_elem.onmouseover = giveMeId;
document.body.appendChild(img_elem);
}
function giveMeId({target}) {
console.log('id:', target.id);
}
I'm trying to do javascript navbar but for some reason can't get it to work. I inspected those elements on the browser, but when I click the open button elements don't get those classes. Could somebody check out what is my problem?
Here's my Javascript:
const body = document.querySelector("body");
const navbar = document.querySelector(".main-menu");
const openButton = document.querySelector(".open-button");
const closeButton = document.querySelector(".close-button");
openButton.onClick = () => {
navbar.classList.add("show");
openButton.classList.add("hide");
body.classList.add("disabled");
};
closeButton.onClick = () => {
body.classList.remove("disabled");
navbar.classList.remove("show");
openButton.classList.remove("hide");
};
You can use Jquery instead for that simply DOM Manipulations, which is a framework of Javascript. Using Jquery makes your code more readable and shorter than vanilla javascript.
$(document).ready(()=>{
$("#openButton").click(()=>{
$("body").toggleClass("disabled");
$("#closeButton").toggleClass("hide");
$(".main-menu").toggleClass("show");
});
});
So I am trying to add classes to javascript and I put showMenu.classList.toggle('.open') with the period after open and the click events work. Meanwhile I put the period after class on my other functions and one works when I put in on the other and the then the other one shuts down. Can anyone explain to me what is happening? Here's my code:
const menuBtn = document.querySelector('.toggler');
const showMenu = document.querySelector('.showmenu');
const links = document.querySelector('.showlink');
const showLinks = document.querySelectorAll('.showlinks > li');
menuBtn.addEventListener('click', function(){
showMenu.classList.toggle('.open');
console.log(showMenu.classList.toggle('open'))
links.classList.toggle('.open');
showLinks.forEach(item => item.classList.toggle('open'));
console.log(showLinks);
});
You should be passing the class without the dot, so just showMenu.classList.toggle('open'), so your code should look something like this:
const menuBtn = document.querySelector('.toggler');
const showMenu = document.querySelector('.showmenu');
const links = document.querySelector('.showlink');
const showLinks = document.querySelectorAll('.showlinks > li');
menuBtn.addEventListener('click', function(){
showMenu.classList.toggle('open');
links.classList.toggle('open');
console.log(showMenu.classList);
console.log(links.classList);
showLinks.forEach(item => {
item.classList.toggle('open');
console.log(item.classList);
});
});
This a basic question (Posting this again, as it was not re-opened after I updated the question). But I couldn't find any duplicates on SO.
This is a script I intend to use in my project on different pages. The purpose is to override the default ID shown in a span element to the order number from the URL parameter session_order. This doesn't affect anything and only enhances the UX for my project.
scripts.js (loaded in the header):
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
And in my HTML template, I call the function this way,
<div onload="this.innerHTML = get_url_parameter(window.location.href, 'session_order');">24</div>
Also tried this,
<div><script type="text/javascript">document.write(get_url_parameter(window.location.href, 'session_order'));</script></div>
When the page is rendered, nothing changes. No errors or warnings in the console either for the first case.
For the second case, console logged an error Uncaught ReferenceError: get_url_parameter is not defined, although script.js loads before the div element (without any errors).
Normally, I'd do this on the server-side with Flask, but I am trying out JavaScript (I am new to JavaScript) as it's merely a UX enhancement.
What am I missing?
Try this:
// This is commented because it can't be tested inside the stackoverflow editor
//const url = window.location.href;
const url = 'https://example.com?session_order=13';
function get_url_parameter(url, parameter) {
const u = new URL(url);
return u.searchParams.get(parameter);
}
window.onload = function() {
const el = document.getElementById('sessionOrder');
const val = get_url_parameter(url, 'session_order');
if (val) {
el.innerHTML = val;
}
}
<span id="sessionOrder">24</span>
Define the function you need for getting the URL param and then on the window load event, get the URL parameter and update the element.
Here you go. Try to stay away from inline scripts using document.write.
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
window.addEventListener('load', function() {
const url = 'https://yourpagesdomain.name/?session_order=hello'; //window.location.href;
const sessionOrder = get_url_parameter(url, 'session_order');
document.getElementById('sessionOrder').innerText = sessionOrder;
});
<div id="sessionOrder"></div>
The order of your markup and script matters...
<div></div>
<script>
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
</script>
<script>
document.querySelector('div').innerHTML = get_url_parameter('https://example.com?session_order=2', 'session_order');
</script>
So, I am trying to make an element and then assign an onclick to it through JS.
Here is my code so far:
HTML
<div id = "Programs" onclick = "Cpb()">Programs</div>
JS
function Cpb() {
document.getElementById("AllBody").innerHTML = "";
var rh = document.createElement("h2");
var rht = document.createTextNode("Recent Programs");
rh.id = "Recentt";
var rh1 = document.createElement("h4");
var rh1t = document.createTextNode("test");
rh1t.onclick = window.open('website');
rh1.appendChild(rh1t);
rh.appendChild(rht);
}
So does anybody know how I can do this?
This javascript worked for me:
let h4Node = document.createElement("H4");
h4Node.innerHTML = "4th Header";
h4Node.onclick = function (){
alert('Oi!');
};
document.getElementById("demo").appendChild(h4Node);
Html:
<div class="demo"></div>
It will put an h4 element with an onclick event listener inside the demo div.
I think you want addEventListener.
Example:
rh1t.addEventListener('click', myHandlerFunction);
function myHandlerFunction () {
// ...
}
You can continue using onclick as you have in your code. But you'll need to do as I've done above and assign a function reference to it. Like this:
rh1t.onclick = myHandlerFunction;
function myHandlerFunction () {
window.open('website');
}