- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Using a clicked element to trigger a script. The element is loaded dynamically!
Hello all,
Here’s the page I’m working on: http://iavi.com/glored/json.html
In the upper left hand corner you’ll see the word “test”. The div that holds this text has a class of .trigger-quote-modal. If you click on it, it will open a modal that contains an iframe.
My issue is that I would like to trigger this modal on links within the rest of the page. Unfortunately, I have content that is being AJAX’d in from a .json file. When clicking on the .trigger-quote-modal elements in this content nothing happens. (Ideally, each button that says “Get a Quote” would be clickable and open up the modal window.)
I only sort of understand why this doesn’t work. Can anyone help me out with a solution to get this working?
You need to use jQuery’s “on” method for live event delegation. http://api.jquery.com/on/
Change:
$('.trigger-quote-modal').click(function(e){ ... })
to
$('.trigger-quote-modal').on('click', (function(e){ ... })
Cheers
Thanks for the reply!
I changed my code around and it still doesn’t seem to be working. The “test” text at the top of my page still works when clicked. But none of the AJAX’d content is working.
My old code: http://iavi.com/glored/json.html
The new code you provided: http://iavi.com/glored/json-2.html
Scratch that. I figured it out.
It looks like I needed to add the class after the .on(‘click’, instead of at the beginning. Here’s the code I used and the final page: http://iavi.com/glored/json-3.html
$('.product-line-container').on('click', '.trigger-quote-modal', function (e) {
Thanks for pointing me in the right direction.