3

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?

Boaz
  • 19,892
  • 8
  • 62
  • 70
ngplayground
  • 20,365
  • 36
  • 94
  • 173

3 Answers3

3

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.

Boaz
  • 19,892
  • 8
  • 62
  • 70
2

Since the HTML is loaded in via AJAX, if you want to bind events to it, you need to bind them to the parent, using on, and set a filter on it.

$(".user-stream-list").on('click', '.col-l .feed a', function() {
 ...
});

EDIT: live is deprecated. use on instead.

Ayush
  • 41,754
  • 51
  • 164
  • 239
-1

Use an overlay div with loading icon, to prevent clicks events from any element...

there is an example here: jQuery: How can i create a simple overlay?

check another example: How can I create a "Please Wait, Loading..." animation using jQuery?

Community
  • 1
  • 1
luchopintado
  • 899
  • 11
  • 15
  • OP does not mean the links are active *during* the AJAX request, but rather *after*. – Boaz Sep 09 '13 at 23:59