Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery preventDefault() even after .ajax()

Tags:

jquery

When PHP script is pulled into my page using

$.ajax({
    url: "/assets/inc/user-stream-list.php",
    success: function (data) {
        $(".user-stream-list").html(data);
    }
});

It produces <a> and I currently use

$('.col-l .feed a').click(function(e){
    e.preventDefault();
});

To stop the links being able to be clicked but after I run the .ajax() script the links become clickable.

Is there a way to prevent the links being clickable after the ajax has run?

like image 214
ngplayground Avatar asked Dec 10 '25 08:12

ngplayground


1 Answers

Delegate the click event to an element higher up the DOM that exists before the AJAX call is made.

For example:

$(document).on('click', '.col-l .feed a', function(e){
    e.preventDefault();
});

Note how the .on() method with three arguments delegates the event to the document element, instead of binding it directly to the yet non-existing a elements. Naturally, document is as high as you can go up the DOM tree. But closer parents can be used as long as you know they exist beforehand.

like image 183
Boaz Avatar answered Dec 12 '25 21:12

Boaz