Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript of dynamically change image src

I'm writing some very simple code to dynamically change image src on mouseover/mouseout:

   function e(id) {
     return document.getElementById(id);
   }

   function changeimg_bw(ele) {
      e(ele).src='rating_bw.png';
   }

   function changeimg_color(ele) 
      e(ele).src='rating_color.png';
   }

   for(var i=1;i<=5;i++) {
     var img ='rating'+i;
     e(img).addEventListener('mouseover', function(event) {
          changeimg_color(img);
     });
     e(img).addEventListener('mouseout', function(event) {
          changeimg_bw(img);
     });
   }

The idea is fairly simple: use an array of images to simulate the rating bar. And when some image is covered by mouse pointer, it should change color (well ideally including all previous images should change color but I got stuck before getting there). My question is when I hover on any image, only the last image changes color ('rating5'). Looks when i == 5 its eventlistener overwrote all other eventlistener (i=1,2,3,4)?

like image 485
Yandong Liu Avatar asked Jul 09 '13 07:07

Yandong Liu


People also ask

How to set image SRC dynamically in JavaScript?

Use id into img tag and getElementById method then assign imager source to set image src in JavaScript. document.getElementById ('image').src = 'http://yourImagePathHere'; Also, one way to solve this is to use document.createElement and create your html img and set its. Example of JavaScript set image src dynamically

How to set image image source in JavaScript?

Use id into img tag and getElementById method then assign imager source to set image src in JavaScript. Also, one way to solve this is to use document.createElement and create your html img and set it.

What happens when you change the SRC property in jQuery?

Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load () method will execute. However, this load block will not execute if the image in question doesn’t exist.

How to assign image in script code in HTML?

Also, one way to solve this is to use document.createElement and create your html img and set it. Let’s see HTML example code, Give your img tag an id and use getElementById to assign an image in script code. Note: Use script code after img tag, otherwise, an error occurs.


Video Answer


4 Answers

Since javascript don't have block scope but function scope, the img within the anonymous listener functions will refer to the last value.
You could solve this by simply encloses the listeners to a private closure like

for (var i = 1; i <= 5; i++) {
    var img = 'rating' + i;
    (function (img) {
        e(img).addEventListener('mouseover', function (event) {
            changeimg_color(img);
        });
        e(img).addEventListener('mouseout', function (event) {
            changeimg_bw(img);
        });
    })(img);
}

DEMO

For better understanding about closures read this

like image 53
code-jaff Avatar answered Oct 12 '22 19:10

code-jaff


Easiest way to delegate event... In such way you don't need to add listeners per element

Live Demo

var parent = document.getElementById("rating1").parentNode;

parent.addEventListener("mouseover", changeimg_color, false);
parent.addEventListener("mouseout", changeimg_bw, false);

function changeimg_bw(e) {
    if (e.target.nodeName.toLowerCase() === "img") {
        e.target.src='rating_bw.png';
    }
    e.stopPropagation();
    e.preventDefault();
}

function changeimg_color(e) {
    if (e.target.nodeName.toLowerCase() === "img") {
        e.target.src='rating_color.png';
    }
    e.stopPropagation();
    e.preventDefault();
}
like image 2
Givi Avatar answered Oct 12 '22 19:10

Givi


In JS you can add properties to any object at run time. Using this behavior you can do something like this...

for(var i=1;i<=5;i++) {
    var img ='rating'+i;
    e(img).index = i;
    e(img).addEventListener('mouseover', function(event) {
        changeimg_color("rating" + event.target.index);
    });
    e(img).addEventListener('mouseout', function(event) {
        changeimg_bw("rating" + event.target.index);
    });
}
like image 1
mohkhan Avatar answered Oct 12 '22 20:10

mohkhan


You could simply add your listeners in a custom function:

function addImgListeners(img) {
    e(img).addEventListener('mouseover', function(event) {
        changeimg_color(img);
    });
    e(img).addEventListener('mouseout', function(event) {
        changeimg_bw(img);
    });
}

Then:

for(var i=1; i<=5; i++) {
    var img = "rating" + i;
    addImgListeners(img);
    // or even addImgListeners("rating" + i);
}

Demo

like image 1
sp00m Avatar answered Oct 12 '22 20:10

sp00m