0

Is there a way to trigger an event in jQuery when the client has an element in their viewport?

So for example lets say I select this element in jQuery:

$('#star')

Then immediately when that element is visible in the viewport I'd like to run an animation.

Any idea if there is a way to do this as I have checked the documentary at jQuery and I can't find an event that does this.

Thanks

Nicholas Maddren
  • 135
  • 4
  • 11
  • Give a try to this answer: http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433 – K K Jan 09 '16 at 12:48

2 Answers2

2

Try this code

$(function() {
   if ($("#star").length > 0) {
      //do something 
   }
});

.length() can be used to find whether an element exist.

siva
  • 495
  • 2
  • 14
0

If this selector $('#star') return anything then its already in the browser/viewport. In that case you could use:

if (document.getElementById('star')) {
    // do something
}

or

var star = $('#star');
if (star.length) {
    start.trigger('click');
    // or something else you need
}

If you want to fire something when the page loads you are better off with:

$(function(){
    // do something because the DOM is ready
});
Sergio
  • 27,160
  • 10
  • 79
  • 126