0

I edited a string in the following way, wrapping it using 2 numers with a span with a class. After that, i would like to do some actions after the click on an element that has that class. The following code doesn't work. Why?

var str="Hello, how are you?";
var start=2;
var end=5;
str=wrap(str,start,end);

$("#somewhere").html(str);

$(".blue").on("click",function(){
    alert("done");
});

function wrap(str,start,end) {
    var sx=str.substring(0,start);
    var wr=str.substring(start,end);
    var dx=str.substring(end,str.length);
    var ret=sx+"<span class='blue'>"+wr+"</span>"+dx;
    return(ret);
}
SctALE
  • 509
  • 2
  • 10
  • 30
  • The code you've shown is just a string. It's not inserted into the DOM where it would be clickable. And, you have to run the `$(".blue").on(...)` after it's inserted into the DOM or switch to using [delegated event handling](http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409). – jfriend00 Dec 05 '15 at 15:58
  • I forgot to insert a string in the code: see now please. – SctALE Dec 05 '15 at 16:04
  • After it's inserted in to the DOM the given answer will work – Andy Dec 05 '15 at 16:06
  • It seems to work fine here: http://jsfiddle.net/jfriend00/tyx8t9L6/ – jfriend00 Dec 05 '15 at 16:35

1 Answers1

6

you can use

$('body').on('click', 'span.blue' , function(){})

take a look at Event binding on dynamically created elements?

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28