How to trigger an event, when component becomes visible. Must be self-contained
I was wondering if anyone knows of a way to trigger an event when a component becomes visible.
In my situation I have a bunch of client side tabs and some components under them that need to know when they become visible. So, they are hidden or shown by some parent container. I have no control over these tabs, so I can't fire the event when the tabs are switched (I'm writing a stand alone JSF component, so I cannot always predict what the exact action that makes the component visible will be).
So, this solution must be self contained within my component. Is there a way for my component to determine that it became visible due 开发者_StackOverflow社区to some change in the parent container(s)?
After doing some more research and looking at the code for http://plugins.jquery.com/project/watch plugin, I came to the conclusion that there is no good event based way to do what I needed in all browsers.
So, I had to resort to a polling approach instead. My solution involves checking component visibility with:
jQuery(this.id).is(":visible")
If the component is visible, I run my heavy lifting javascript code for the component. If it is not visible I run a routine every 200ms to check if the component is visible. This way I'll know when a component becomes first visible, so I can process it.
Since the amount of code executed every 200ms is quite small (just the visibility check, which I think is based on testing component width == 0), this seems to perform pretty well.
So, not as cool of a solution as I was hoping for, but it seems to get the job done.
I solve this by firing the resize
event from the tabstrip whenever it switches tab:
window.dispatchEvent(new Event('resize'));
You could also consider firing scroll
and/or visibilitychange
.
精彩评论