0

i have this HTML code on a page when my page loaded:

<div class="divmain">Add
  <span class="spn">123</span>
</div>

when you click on that span it will create another span and show hi alert to you, when the page loaded for the first time it works fine and write another span on that dive as the same the old span but after that if you click on the new span it works not.

i did some test and found if i add this code :

   $('.spn').on("click", function (e) {
        showalert(this);
   });

on the "spanwriter" function it will works , i mean if that function be like this:

  function spanwriter(master) {
  var rows = '<span class=\'spn\'>123</span>';
  $('.divmain').html(rows);

 <------- this event must be add here until it --------------->
    $('.spn').on("click", function (e) {   works
     showalert(this);
  });
}

why i should add click event at the end of wrote content until span can get that event and works?

i used jquery-1.10.2.js on my sample

my all codes are:

$(function () {

$('.divmain').on("click", function (e) {
    spanwriter(this);
});

$('.spn').on("click", function (e) {
    showalert(this);
});

});

function spanwriter(master) {
   var rows = '<span class=\'spn\'>123</span>';
   $('.divmain').html(rows);
}

function showalert(master) {
  alert("hi");
}
1
  • You want to use delegated-events: api.jquery.com/on start reading at "Event handlers are bound only to the currecntly ..." Commented Dec 10, 2014 at 14:26

2 Answers 2

4

you have to do the same but with document.on("click")

$(document).on("click", ".buttonClass", function() { console.log("inside"); });

$('.divmain').on("click" make a kind of binding when document is loaded, so when you add dynamix elements to the dom it is noit catched. Whith the use od document.on, it works even if you add dynamic content to the document.

Sign up to request clarification or add additional context in comments.

Comments

1

The simplest and best solution to your problem is to attach the event listener to a parent element in the dom and pass the second parameter of the on() method as described in the jQuery documentation (http://api.jquery.com/on/)

In other words you should have something along the lines of:

$('body').on("click", ".spn", function (e) {
    showalert(this);
    spanwriter(this);
});

and then have the spanwriter() add the new span to the parent of the element it's been called upon.

I hope this is what you were looking for and answers your question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.