javascript - Change image in button on click -


i've got button image inside want swap when clicked. got part working, want change original image when clicked again.

the code i'm using:

<button onclick="action();">click me<img src="images/image1.png" width="16px" id="imagebutton1"></button> 

and javascript:

function action() {   swapimage('images/image2.png'); };  var swapimage = function(src) {   document.getelementbyid("imagebutton1").src = src; } 

thanks in advance!

while could use global variable, don't need to. when use setattribute/getattribute, add appears attrib in html. need aware adding global adds variable window or navigator or document object (i don't remember which).

you can add object (i.e variable isn't visible if html viewed, visible if view html element object in debugger , @ it's properties.)

here's 2 alternatives. 1 stores alternative image in way cause visible in html, other doesn't.

<!doctype html> <html> <head> <script> function byid(e){return document.getelementbyid(e);}  window.addeventlistener('load', minit, false);  function minit() {     var tgt = byid('imagebutton1');     tgt.secondsource = 'images/image2.png'; }  function byid(e){return document.getelementbyid(e);}  function action()  {     var tgt = byid('imagebutton1');     var tmp = tgt.src;     tgt.src = tgt.secondsource;     tgt.secondsource = tmp; };  function action2() {     var tgt = byid('imgbtn1');     var tmp = tgt.src;     tgt.src = tgt.getattribute('src2');     tgt.setattribute('src2', tmp); } </script> <style> </style> </head> <body>     <button onclick="action();">click me<img src="images/image1.png" width="16px" id="imagebutton1"></button>     <br>     <button onclick="action2();">click me<img id='imgbtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>     </body> </html> 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -