jQuery: How to bind an event for the div when it becomes visible?

foreline picture foreline · Oct 4, 2010 · Viewed 12.8k times · Source

I've got a div element: <div id="tab1"> Tab data </div>.

How to bind a custom event when this div becomes visible (gets display: block;)?

And also I'd like to bind an event when this div becomes invisible (gets display: none;).

I'd like to do this in jQuery.

Edit: I'm making simple tabs with ajax content. I want the content on this tabs to be ajax-updated only when the tab is visible.

Answer

Mike Trpcic picture Mike Trpcic · Oct 4, 2010

Have the event always bound to the div, but inside the event, do something like the following:

if($(self).is(":visible")){
    // Implement your code
}

Now your event will only be triggered if the element is visible to the user.