I have two colored divs on which I want to put events on. I have selected them using getElementById and that worked fine - when I console.log the variable I get the right div.
However, the click event doesn't seem to fire at all. I basically just wanted to check if it works with console.log so that is what the function returns.
Here is the HTML code:
<html>
<head>
<style>
#red{
background: red;
width: 50px;
height: 50px;
}
#blue {
background-color: blue;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
</div>
<div class="color picker">
<h2>Pick a color!</h2>
<div id="red"></div>
<div id="blue"></div>
<div id="green"></div>
</div>
</div>
</body>
<html>
And here the JavaScript
var redColor = document.getElementById('red');
var blueColor = document.getElementById('blue');
function loadEventListeners(){
redColor.addEventListener('click', pickRed);
};
function pickRed(){
console.log("You have selected red");
}
Thank you for your help!
It seems like you haven't called loadEventListeners
. Doing that should solve the problem.
Your loadEventListeners function is never being called. You can call it directly after or use an IIFE
function pickRed(){ console.log("You have selected red"); } function loadEventListeners(){ document.getElementById('red').addEventListener('click', pickRed); }; loadEventListeners();
#red{ background: red; width: 50px; height: 50px; } #blue { background-color: blue; width: 50px; height: 50px; }
<html> <head> </head> <body> </div> <div class="color picker"> <h2>Pick a color!</h2> <div id="red"></div> <div id="blue"></div> <div id="green"></div> </div> </div> </body> <html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.