llanato
llanato

Reputation: 2491

Click Issue: Dynamically Generated Links Not Triggering Click Function

Below are the two snippets of code, for some reason nothing is happening, yet other jQuery functions from the same JS file are executing fine on the page with the UL, is it something that's staring me in the face!?

<ul id="activityPaganation" class="paganation">
    <li>1</li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
    <li><a href="#">4</a></li>
    <li><a href="#">5</a></li>
    <li><a href="#">6</a></li>
</ul>



$(document).ready(function() { 
    $('#activityPaganation li a').on("click", function(e) {
            e.preventDefault();     
            var pid = $(this).text();

            alert(pid);
    });
});

Upvotes: 2

Views: 6461

Answers (2)

PSL
PSL

Reputation: 123739

You can use event delegation, since this is dynamically added to DOM.

 $(document).on("click", "#activityPaganation li a", function(e) {
            e.preventDefault();     
            var pid = $(this).text();

            alert(pid);
    });

instead of document use some container that exists in DOM at any point in time.

if the li's are added and your ul #activityPaganation exists at any time then:

  $('#activityPaganation').on("click", "li a", function(e) {
                e.preventDefault();     
                var pid = $(this).text();

                alert(pid);
        });

otherwise move your event binding to the load's complete call back.

i.e

$('something').load('someurl', function(){
 $('#activityPaganation li a').on("click", function(e) {
            e.preventDefault();     
            var pid = $(this).text();

            alert(pid);
    });
});

Reason is that with direct event binding on the element it needs to exist in DOM, instead workaround is to delegate the event to a container that exists in DOM at any point or document head so that the when element is added in future it gets the event delegated from its parent. Effectively it uses event bubbling for this effect.

See

Upvotes: 8

Sushanth --
Sushanth --

Reputation: 55740

Try event delegation instead

Replace

$('#activityPaganation li a').on("click", function(e) {

with

$(document).on("click", '#activityPaganation li a', function(e) {

Because the elements are being added dynamically to the page, the events are not bound to the elements that are added.

The event signature that you are trying , will only bind the events to the elements taht are present in the DOM at that point of time. So delegating the event to the closest static ancestor will solve your problem as the event bubbles up and is handled by it.

Upvotes: 3

Related Questions