DominicM
DominicM

Reputation: 6898

Passing "this" to .on function doesnt seem to work

I have a function:

function test(e){
            $('.movie').find('.moreInfo').removeClass('moreInfoShow');
            e.parent().find('.moreInfo').addClass('moreInfoShow');
            $("#movieBox").isotope('reLayout');

            e.parent().find('.moreInfo').css("opacity", "0");
            e.parent().find('.moreInfo').animate({opacity: 1}, 500);
        }

which is called by:

$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});

The issue is that I want the function to be called when the page loads. I need to pass "this" to the function but I have had no luck in getting it to work.

This is what I expected to work:

test($(".moviePoster").first());

(ALL code is in "$(document).ready" function)

Upvotes: 1

Views: 83

Answers (2)

Robin Drexler
Robin Drexler

Reputation: 4457

W/O fiddle:

Change this:

$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});

to

$("#movieBox").on('mouseover', '.moviePoster', test);

Then $(this) inside test function should point to the jQuery object which triggered the event.

Invoking test function in the callback with "test($(this))" will instantly execute the function and not when the event is fired.

Update:

After you did this, you'll need to trigger the mouseover event on page load of course. See Jashwant's comment on how to do that.

Update I was wrong.

function(event){test($(this));}

will of course not trigger the callback function instantly. This only would happen if it would be like this:

$("#movieBox").on('mouseover', '.moviePoster', test($(this)));

Sorry!

Upvotes: 1

Jashwant
Jashwant

Reputation: 29005

As stated in comments, trigger the mouseover event on page load.

$("#movieBox").find('.moviePoster').trigger('mouseover');

Reference

Upvotes: 0

Related Questions