Adam Grant
Adam Grant

Reputation: 13105

Send a variable to javascript function from jquery

I have a jquery mouseover event which succesfully calls a javascript function

$(document).ready(function() {
$('.nw').mouseover(run_nw);
});

function run_nw() {
...
}

However, when I try to pass parameters, the js fails.

$(document).ready(function() {
$('.nw').mouseover(run_nw(1));
});

var a;
function run_nw(a) {
...
}

Tried looking through SO and through jQ documentation but I'm still stumped. I'm assuming this is a simple formatting issue.

Thanks

(Here is the full code if it helps)

    <script>
    var $ = jQuery.noConflict();
    var incr = 650;

        function run_nw() {
            //move x and y
            var topAdjust = -incr;
            var leftAdjust = -incr;

            var top = parseInt($(this).css('top'))+topAdjust;
            var left = parseInt($(this).parent().css('left'))+leftAdjust;

            //rotate
            var randomnumber = Math.floor(Math.random()*11);
            var rotate = -randomnumber*10;

            $(this).animate({
                top:top,
                left:left,
                'rotate':rotate
            }, 700, 'swing');
        }

        $(document).ready(function() {
            $('.nw').mouseover(run_nw);
        });
    </script>

Upvotes: 0

Views: 104

Answers (1)

James Allardice
James Allardice

Reputation: 166001

Wrap the function call in an anonymous function:

$('.nw').mouseover(function() {
    run_nw(1);
});

The way you have it currently will execute the function and pass the result of that as the callback to mouseover.

Update

The problem with your current code is that in the event handler function, this does not refer to what you're expecting (it refers to the Window, because you are calling the function from an anonymous callback to mouseover - this inside the anonymous callback is what you want it to be).

So, you need to pass this into the function and change any references to this to whatever you choose to name that argument:

$('.nw').mouseover(function() {
    run_nw(1, this);
});
function run_nw(a, elem) {
    //Now `elem` is what you expected `this` to be
}

Here's an updated fiddle.

Upvotes: 4

Related Questions