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
3 Answers 3
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
});
1 Comment
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');
}
);
Comments
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);
}
);
org_srcis only scoped to the first function, but not the second.$(this).data("rolloverImage");