0

My Code:

$("img.rollover-neu").hover (
 function() { 
 var org_src = $(this).attr('src');
 this.src = $(this).attr("data-rolloverImage"); }, 
 function() { alert("h"+org_src); /*this.src = $(this).attr('src', org_src);*/ } 
 );

On Mouse-enter i save the src of an image inside a var "org_src". On Mouse-Out it should change the src back. Unfortunately the var "org_src" is empty at the mouse-out function. Any help why?

Thanks

asked Dec 6, 2016 at 11:17
2
  • 2
    org_src is only scoped to the first function, but not the second. Commented Dec 6, 2016 at 11:19
  • Why not assign it to a data attribute so you can use it on mouse out too. Or just make the org_src global. Also for data attributes, you can use $(this).data("rolloverImage"); Commented Dec 6, 2016 at 11:22

3 Answers 3

1

Why not pull the org_src variable out of your event handlers?

var org_src
$("img.rollover-neu").hover(function() { 
 org_src = this.src
 this.src = this.getAttribute("data-rolloverImage")
}, function() {
 this.src = org_src
});
answered Dec 6, 2016 at 11:22
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! You save my day!
0

If you delcare a variable within a function, it is scoped to that function - have a look at this post for a good explanation of scoping

In your case I would use a data attribute to store your original source so you can just reuse it on the mouseout:

$("img.rollover-neu").hover(
 function() {
 var image = $(this);
 image.data('org-src', this.src);
 this.src = image.data("rolloverImage");
 },
 function() {
 this.src = $(this).data('org-src');
 }
);
answered Dec 6, 2016 at 11:30

Comments

0

using var you org_src is local to that function, you can create a global variable or use a attribute to store your data

$("img.rollover-neu").hover (
 function() { 
 var org_src = $(this).attr('src');
 $(this).attr('org-src',org_src);
 this.src = $(this).attr("data-rolloverImage"); 
 }, 
 function() { 
 var org_src = $(this).attr('org-src');
 this.src = $(this).attr('src', org_src);
 } 
 );
answered Dec 6, 2016 at 11:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.