0

I make an AJAX call and import the data to my html. Now I want to make an alert when I click a certain div.

In the past I always used .on() on elements after an AJAX call. This time its not working but AjaxComplete is working.

Any explination for this ?

NOT WORKING :

$( ".morec" ).on("click",function() {
alert('test');
});

WORKING :

$(document).ajaxComplete(function(){
$( ".morec" ).click(function() {
alert('test');
});
});
RDBWSF
  • 63
  • 1
  • 1
  • 4
  • Well, they are the same, but one is inside an event handler that fires when the ajax call is completed. If you want to delegate the event, you'll have to use `on()` [**differently**](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on) – adeneo Dec 18 '15 at 00:09
  • are u using jquery < 1.7 ??? – Abhishek Singh Dec 18 '15 at 00:11
  • Possible duplicate of [jquery click doesnt work on ajax generated content](http://stackoverflow.com/questions/9344306/jquery-click-doesnt-work-on-ajax-generated-content), [jquery onclick, vs click, vs delegated click](http://stackoverflow.com/questions/11296530/jquery-onclick-vs-click-and-delegateclick), [direct vs delegated jquery on](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on) – War10ck Dec 18 '15 at 00:18

1 Answers1

0

Try

$(document).on("click", ".morec", function(){
    alert ("test");
});

Edit

At the time of page load, the element with the class .morec, may not be present in the DOM. So if you attach the event handler to that object using your method, it will not work when the element gets generated dynamically. Rather you should be delegating the event on a parent element or on the document so that it will fire whenever the element gets added to the DOM.

You can have a detaild read in Understanding Event Delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

rahul
  • 174,563
  • 47
  • 223
  • 254
  • Yes but normally the classic $( ".morec" ).on("click",function() { works. Why not now I wonder ? – RDBWSF Dec 18 '15 at 00:13
  • 1
    @RDBWSF The content doesn't exist in the DOM structure when the event handler is initialized. In other words at the time of initialization, `$('.morec').length === 0`... – War10ck Dec 18 '15 at 00:20
  • 1
    Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. – Nathan Tuggy Dec 18 '15 at 02:44