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

Stiller Eugen
  • 681
  • 2
  • 10
  • 28
  • 2
    `org_src` is only scoped to the first function, but not the second. – Sebastian Simon Dec 06 '16 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");` –  Dec 06 '16 at 11:22

3 Answers3

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
});
gyre
  • 16,369
  • 3
  • 37
  • 47
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);
       } 
    );
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
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');
  }
);
Community
  • 1
  • 1