Skip to content
Advertisement

Image swapping when a variable changes

I have an html page that has one image object.

I am trying to write some JavaScript but something isn’t working in the script. I have a piece of script that reads a variable and if the variable ‘e’ is equal to 1, then one image appears. If ‘e’ is anything other number then image 2 appears. For now, ‘e’ is static, but it will be dynamic.

How do you change an image dynamically based off a variable?

Any help is most appreciated.

    <!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Title of the 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);
         // something  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>

Advertisement

Answer

You can use jQuery to change image source. Your function have e inside, pass it as parameter and you can change the image where you want just by calling the function with the corresponding value.

var e = 1;
changei(e);
// something  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: You can attach an event to an input, keyup and every time you press a key in that input the image will change based on what you entered.

changei(1); // when entering in page set src

$('#eInput').keyup(function(){ // when something was 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">
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement