0

My content changes with ajax and I want that after 200px of scrolling to trigger a click to an element.

$(window).scroll(function() {
  if($(window).scrollTop() > 200){
    $(".element")[0].click();
  }
}

But this does not work with changing content. On first load it works. But as soon as ajax does it's stuff the event isn't firing anymore. Any ideas? I know about the on event but cannot figure it out how to use it here.

Update

The linked question does not help me:

$(staticAncestors).on(eventName, dynamicChild, function() {});

this works for clicks or other events. But I don't want to attach a click event, I want to trigger a click event. How could I do it? The change is in an ajax call beyond my control so I cannot add a callback.

Thanks

8
  • So does it work when the element isn't dynamically loaded? Perhaps an example would be helpful.. Commented Dec 9, 2015 at 14:46
  • When you say it doesn't work, what specifically doesn't work about it - ie it doesn't click, the correct element isn't clicked, the event of the clicked element isn't fired... etc Commented Dec 9, 2015 at 14:50
  • how do your change your content and where is the content loaded? body? some examples help. Commented Dec 9, 2015 at 14:55
  • @JoshCrozier yes, it is working when the element isn't dynamically loaded. yes, nothing is clicked when the element is reloaded. the change is in an ajax call beyond my control so I cannot add a callback. Commented Dec 9, 2015 at 14:59
  • 1
    @isherwood can you please post an answer how to use on() and trigger a click, not attach a click event like that question wants. I'm unsure how to do it. Commented Dec 9, 2015 at 15:04

2 Answers 2

0

Per this answer, you use the find() method to look at a static ancestor element's descendant elements:

$('#someStaticAncestorElement').find('.element')[0].click();
Sign up to request clarification or add additional context in comments.

Comments

0

When you're trying to play with item/object's that aren't there on the very first load JavaScript gets a bit confusing.

jQuery/JS language in simple terms only really can apply to the objects on page load.

The easiest way around this is to delegte functions to a HTML element that is always there on pageload. Most people usually use the <body>.

Eg:

$(window).scroll(function() {
  if($(window).scrollTop() > 200){
    $( "body" ).delegate( $(".element")[0], "click", function() {
      // Your Code Here
    });
  }
}

1 Comment

The OP isn't trying to add a click event listener, they are trying to trigger a click event.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.