html - javascript onclick function not working? -
i trying onclick event when light bulb image clicked goes light bulb off light bulb on image , vice versa. using external javascript file. when click on image nothing happens.
i cant figure out whats wrong,
my html portion:
<head> <link rel="stylesheet" href="css/program-01.css" /> <script type="text/javascript" src="javascript/program-01.js"></script> <title> <h1>program-01</h1> </title> </head> <body> <div id="lightoff"> <img src="images/light_off.png" id="light_off" alt="" onclick="lightbulbfunction()" /> </div> </body>
my js file function:
function lightbulb() { var image_change = document.getelementbyid("light_off"); if (image_change.src == "images/light_off.png") { image_change = "images/light_on.png"; } else { image_change = "images/light_off.png"; } }
suggestions/problems:
you function names different.
you're using function
lightbulbfunction
ononclick
event. but, don't have function of name in script. you'll get
referenceerror: lightbulbfunction() not defined.
- to change image
src
attribute value, useimage_change.src
inside event handler.
to solve problem change name of onclick
attribute value lightbulb
.
function lightbulb() { var image_change = document.getelementbyid("light_off"); if (image_change.src == "images/light_off.png") { image_change.src = "images/light_on.png"; // ^^^^ } else { image_change.src = "images/light_off.png"; // ^^^^ } }
<div id="lightoff"> <img src="images/light_off.png" id="light_off" alt="" onclick="lightbulb()" /> <!-- ^^^^^^^^^^^ --> </div>
better approach use addeventlistener
bind events on elements.
document.getelementbyid('light_off').addeventlistener('click', function() { var image_change = document.getelementbyid("light_off"); if (image_change.src == "images/light_off.png") { image_change.src = "images/light_on.png"; } else { image_change.src = "images/light_off.png"; } }, false);
<div id="lightoff"> <img src="images/light_off.png" id="light_off" alt="" onclick="lightbulb()" /> <!-- ^^^^^^^^^^^ --> </div>
Comments
Post a Comment