Michael Young
Michael Young

Reputation: 25

Img attr src will not change

Heres the situation i am able to show on hover the src as being chenged but the image on the screen itself doesnt actualy change. any help would be a great help.

$('.hoverImgs').hover(
function(){mouseOn = 1; formSelector('hover');},
function(){mouseOn = 0; formSelector('out');
});

function formSelector(method){
if(mouseOn === 1 && method === 'hover'){       
    $(this).attr("src", "images/radio_hover.png");
    alert($(this).attr("src"));
}
else {}
}
});

Upvotes: 2

Views: 1244

Answers (2)

sachleen
sachleen

Reputation: 31131

First, you have an extra }); at the end.

Your real problem: this is not what you think it is. In that context, this refers to the window object, not the image. One way to fix that is pass in the image element into the functions.

$('.hoverImgs').hover(
  function(){mouseOn = 1; formSelector($(this), 'hover');},
  function(){mouseOn = 0; formSelector($(this), 'out');}
);

function formSelector(elem, method){
  if(mouseOn === 1 && method === 'hover'){
    console.log(elem.attr('src'));
    elem.attr("src", "https://www.google.com/images/srpr/logo3w.png");
  }
}

Demo

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

The context is lost when you call the function formSelector and this would window object inside the function. You should either pass this object as an argument or invoke the function using .call/.apply.

Try like below,

$(function () {
   var mouseOn;
   $('.hoverImgs').hover(
      function(){ mouseOn = 1; formSelector('hover', this); },
      function(){mouseOn = 0; formSelector('out', this); }
   );

  function formSelector(method, thisObj){
     if(mouseOn === 1 && method === 'hover'){       
       thisObj.src = "images/radio_hover.png";
       alert(thisObj.src);
     }
     else {}
   }

});

Upvotes: 2

Related Questions