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:

  1. you function names different.

    you're using function lightbulbfunction on onclick event. but, don't have function of name in script. you'll get

referenceerror: lightbulbfunction() not defined.

  1. to change image src attribute value, use image_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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -