javascript - Image swapping when a variable changes -
i have html page has 1 image object.
i trying write javascript isn't working in script. have piece of script reads variable , if variable 'e' equal 1, 1 image appears. if 'e' other number image 2 appears. now, 'e' static, dynamic.
how change image dynamically based off variable?
any appreciated.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>title of document</title> <body onload="changei()"> <img id="im1" src="images/lion1.jpg" width="100" height="180" style="display:show"> <p> hello</p> <script> function changei() { var e = 0; changei(e); // changed e in e = 0; change(e); function changei(e) { var loc = ''; if (image.src.match("lion1")) { image.src = "images/lion1.jpg"; } else { image.src = "images/lion2.jpg"; } $('#im1').attr("src",loc); // change image source } </script> </body> </html>
you can use jquery
change image source. function have e
inside, pass as parameter , can change image want calling function corresponding value.
var e = 1; changei(e); // changed e in e = 0; changei(e); function changei(e) { var loc = ''; if (e==1) { loc = "images/lion1.jpg"; } else { loc = "images/lion2.jpg"; } $('#im1').attr("src",loc); // change image source }
example: can attach event input, keyup
, every time press key in input
image change based on entered.
changei(1); // when entering in page set src $('#einput').keyup(function(){ // when inserted on input var e = $(this).val(); changei(e); }); function changei(e) { var loc = ''; if (e==1) { loc = "http://images.math.cnrs.fr/local/cache-vignettes/l256xh256/section1-original-0f409.png"; } else { loc = "http://www.data-compression.com/baboon_24bpp.gif"; } $('#im1').attr("src",loc); // change image source }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="einput" /> <img id="im1" src="images/lion1.jpg" style="display:show">