Pregunta

I have a problem changing pic src attribute on mouseover using jquery, all works fine when I do this:

    $(this).attr('src',currURL+"_0"+currPicID+'i.jpg');

but when the loop starts src attribute changes too, but picture (I means visually) does not (looking firebug cosnole) but I see the change doing a simple alert with src attribute like this:

    this.iid = setInterval(function() {
currPicID++;
if (currPicID>16){currPicID=1;}
$(this).attr('src',currURL+"_0"+currPicID+'i.jpg');
alert($(this).attr('src')); <=== this changes perfectly and shows correct paths
}, 525);

also on mouseover it works fine:

    bind('mouseleave', function(){
this.iid && clearInterval(this.iid);
$(this).attr('src', oriPIC)

any suggestion about what m I doing wrong?

Thanks!

¿Fue útil?

Solución

You issue is most possible this which inside the interval callback would be global context (window or undefined) and in your case you are just setting the src attribute of the window and not the image. Instead cache the current image object in a variable before the callback and use it.

var $img = $(this);
 this.iid = setInterval(function () {
     currPicID++;
     if (currPicID > 16) {
         currPicID = 1;
     }
     $img.attr('src', currURL + "_0" + currPicID + 'i.jpg');
     alert($img.attr('src')); //<= == this changes perfectly and shows correct paths
 }, 525);

Or use $.proxy or function.bind to bind the context for the callback function.

this.iid = setInterval($.proxy(function () {
     currPicID++;
     if (currPicID > 16) {
         currPicID = 1;
     }
     $(this).attr('src', currURL + "_0" + currPicID + 'i.jpg');
     alert($(this).attr('src')); <= == this changes perfectly and shows correct paths
 },this), 525);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top