Double click function in jQuery is not working

manishjangir picture manishjangir · Mar 13, 2012 · Viewed 14.5k times · Source

I have two span elements in a page. when I call a jquery double click function on both then the function is called only on first element. I am using the following code:

<span id="shiftTime_1">1</span>
<span id="shiftTime_2">1</span>

and jquery function is:

 $("[id^='shiftTime_']").dblclick(function() {
 alert("hello");
 });

when I double click on the element Id of shiftTime_1. then the function works fine. But when I double click on element Id of shiftTime_2 then this function does not respond.

Please help. Thanks

Answer

Igor L. picture Igor L. · Jul 24, 2015

Use .on if you plan to add elements dynamically (e.g. by using $( "body" ).append( "<span id='shiftTime_2'>1</span>" ); )

$( "body" ).on( "dblclick", "span", function() {
    alert( "This works also with dynamically added elements" );
} );