0

I'm trying to work out a way to delegate an event to future, dynamically loaded elements using .on

I have a button (#button) which is present when the DOM is loaded.

The new elements (let's give them a class of .newElement) are then loaded into the page dynamically.

I want to click on '#button' and scroll to '.newElement.'

Is this possible?

The following is where my head is at:

jQuery(document).on("click", '#button', function (e) {
            jQuery(window).scrollTop(jQuery('.newElement').offset().top);
        });

This doesn't work as #button can't find .newElement in the DOM.

Thanks

shifty_uk
  • 13
  • 1
  • 4
  • 1
    I was going to dupe close this in favor of https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements, however it doesn't seem like it's a fit. You don't need to use event binding on #button, which is what you're doing. Please post a [mcve], specifally related to how `.newElement` is being added. – j08691 Jul 01 '17 at 22:40
  • You can't scroll to something that isn't there? When the element is inserted, getting the offset and scrolling to it should work the way you're doing it ? – adeneo Jul 01 '17 at 23:04
  • Have the elements that have class `.newElement` been added prior to clicking the button? You should show a full working example so we can determine what is going on. – RJM Jul 01 '17 at 23:21

1 Answers1

-1

Try with this one.

jQuery("body").on("click", '#button', function (e) {
            jQuery(window).scrollTop(jQuery('.newElement').offset().top);
        });
Wasif Iqbal
  • 474
  • 1
  • 4
  • 17
  • This just changes which element has the click handler, changing that does not affect wither or not jQuery will find an element with `newElement` class – Patrick Evans Jul 01 '17 at 23:25
  • Let me know if this helps. Create a fiddle for you for better understanding. https://jsfiddle.net/o11ouj2e/4/ – Wasif Iqbal Jul 05 '17 at 20:53