Select a listener class that will be created later.

I am trying to figure out if it is possible to create a clicklistener class. When I create a listener div, I can first add the listener and then I can create a div.

So, I want to create a listener first and then add a class. Is it possible?

HTML:

<div>
    <div id="1">
        <div id="2">
            <!-- will be created.. -->
        </div>
    </div>
</div>

      

js:

$(".welcome").click(function() {
    alert("Hi there");
});

// Later the class album will be loaded
// When you put it above it will work..
welcome = document.getElementById("2");
welcome.innerHTML = '<div id="3" class="welcome"> Hello</div>';

      

I checked the jsfiddle for testing.

+3


source to share


4 answers


yes ... use on event delegate ...

Event handlers are bound only to the currently selected items; they must exist on the page when your code calls .on (). To ensure that the elements are present and selectable, bind events inside the document handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML has been placed on the page. Or, use delegated events to attach an event handler, as described below.

try it

 $(document).on('click','.welcome',function() {
    alert("Hi there");
 });

      



even better if u bound the event to the closest element ... in your case it's the div with id # 2 <div id=2

>

$('#2').on('click', '.welcome', function() {
   alert("Hi there");
});

      

violin here

+2


source


You can achieve this. In jQuery, this pattern is known as a delegated event. You can attach a click handler to an element #2

, which will be available after adding an element .welcome

to it. Try the following:

$('#2').on('click', '.welcome', function() {
    alert("Hi there");
});

      



Updated script

Note that in your fiddle, I have also corrected plain javaScript to use jQuery methods. If you received them, you can also use them.

+3


source


Yes, it is possible using event delegation :

$(document).on('click', '.welcome', function(e) {
    alert("Hi there");
});

      

I used document

to attach a delegated event handler because it will get all elements that match the selector .welcome

no matter where they are on the page. Ideally, you would use the closest static element that will contain all the elements you want to match.

+2


source


You need to delegate to the closest existing parent that is available in the dom when the page was ready:

$('div[id="2"]').on('click', '.welcome', function(e) {
    alert("Hi there");
});

      

0


source







All Articles