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.
The solution I found was to fire up
focus
event when the tab is selected.And then I catch these
focus
andblur
events:Start and stop the AJAX update based on the visibility. You can use
.is()
to return a TRUE or FALSE for:visible
:Here is a simple example of a timer that stops when it is invisible. Note that the numbers don't keep increasing when they're not visible:
jsFiddle example
Of course, in the above case, and maybe your case, it's more straight forward to simple alternately turn the update on and off:
jsFiddle example
Have the event always bound to the div, but inside the event, do something like the following:
Now your event will only be triggered if the element is visible to the user.