Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle click event for appended elements in jQuery

I have generated few elements in my page using following method. For example,

$("#button"+caption).click(function(){         var firstDisplay = '<div id="firstDisp'+caption+'"><ul>';         for(var i=0;i<parents.length;i++){             firstDisplay=firstDisplay+'<li class="fClick">'+parents[i]+'</li>';         }         firstDisplay=firstDisplay+'</ul></div>';         $(firstDisplay).dialog(); }); 

and when i create an onclick event for 'fClass' like so :

$(".fClick").click(function(){     alert("hey!"); });  

It does not works ! However, if i put the onclick function inside the other function, right after .dialog(), it works ! I have a lot of elements created this way, so I cannot put all onclick events in a single method. Is there any way around this? I am having the same problem with .append method as well.

like image 542
Eddard Stark Avatar asked Aug 21 '12 13:08

Eddard Stark


People also ask

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

How to appendchild in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

What is the difference between .on click function ()) and .click function?

on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.


1 Answers

Change it to .on or .delegate based on the version of jQuery you are using..

As of jQuery 1.7+

$(document).on('click', '.fClick', function(){      alert("hey!"); });  

For older jQuery versions use delegate

$(document).delegate('.fClick', 'click', function(){     alert("hey!"); });  
like image 195
Selvakumar Arumugam Avatar answered Sep 23 '22 05:09

Selvakumar Arumugam