0

My basic setup is this:

function overLink ( e ){
    alert( e );
}
$(document).ready(function() {
    $( "#id" ).mouseover( overLink( this ) );
});

However 'overLink' is being called on page load, not when '#id' is hovered. I read that this is because of () in my function declaration, but I can't remove this as I want to pass a selector to the function. Any ideas?

Thanks!

  • Possible duplicate of [jQuery pass more parameters into callback](http://stackoverflow.com/questions/939032/jquery-pass-more-parameters-into-callback) – JJJ May 21 '16 at 11:28

5 Answers5

3

What you're doing, when you "pass" this to the function like you are doing is to actually call the function. Try this instead

$(document).ready(function() {
    $("#id").mouseover(function() {
      overLink(this);
    });
});
Arjun
  • 1,261
  • 1
  • 11
  • 26
fredrik
  • 6,483
  • 3
  • 35
  • 45
2

its because you are calling the function and returning the result of it ti the mouseover listener .... you should instead pass the function reference ... not its result

   $( "#id" ).mouseover(overLink);
reda igbaria
  • 1,444
  • 12
  • 15
0

This is right way of calling function :-

function overLink (e){
    alert(e);
}
$(document).ready(function() {
    $( "#id" ).mouseover(function() {
     overLink( this );
    });
});
BenG
  • 14,826
  • 5
  • 45
  • 60
Jagdish Thakre
  • 158
  • 2
  • 11
0

When a function name is followed by parentheses (()), it is immediately invoked (executed) by JavaScript. To pass it as reference, omit the parens. This will work :-

$(document).ready(function(){
  $("#id").mouseover(overLink);
});

But since you are passing an argument to overLink, you should use an anonymous function :-

$(document).ready(function(){
  $("#id").mouseover(function(){
    overLink(this);
  });
});
Arjun
  • 1,261
  • 1
  • 11
  • 26
0

There is no need to pass this as an argument as this within overLink will be the element anyway.

function overLink(){
    alert(this);
}
$(document).ready(function() {
    $("#id").mouseover(overLink);
});
BenG
  • 14,826
  • 5
  • 45
  • 60