event listner isn't working on dynamically created object

I have a bit of code where I am looping though all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouseon/off.

This happens on page ready and works just fine.

The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.


As of jQuery 1.7 you should use jQuery.fn.on:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Prior to this, the recommended approach was to use live():

$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

$(selector).live( eventName, function(){} );

... can be replaced with the following on() signature:

$(document).on( eventName, selector, function(){} );

For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists, often document.

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout
    // occurs on elements that match '.dosomething'

Any parent that exists at the time the event is bound is fine. For example

$('.buttons').on('click', 'button', function(){
    // do something

would apply to

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->

There is a good explenation on this documentation.

In short:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). Thus in the following example, #dataTable tbody tr must exist before the code is generated.

$("#dataTable tbody tr").on("click", function(event){

If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:

$("#dataTable tbody").on("click", "tr", function(event){

In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, the first code example attaches a handler to 1,000 elements. A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody).

Note: Delegated events do not work for SVG.

This is a pure javascript solution without any libraries or plugins:

document.addEventListener( 'click', function ( e ) {
    if ( hasClass( e.target, 'bu' ) ) {
        // .bu clicked
        // do your thing
    } else if ( hasClass( e.target, 'test' ) ) {
        // .test clicked
        // do your other thing
}, false );

where hasClass is

function hasClass( elem, className ) {
    return elem.className.split( ' ' ).indexOf( className ) > -1;

Live demo

Credit goes to Dave and Sime Vidas

Try to use .live() instead of .bind(); the .live() will bind .hover to your checkbox after the Ajax request executes.

you can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

var mouseOverHandler = function() {
    // do stuff
var mouseOutHandler = function () {
    // do stuff

$(function() {
    // on the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);

// this next part would be in the callback from your AJAX call
    .append(/* your <option>s */)
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo(/* wherever you need the select box */)

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

function addCallbacks(eles){


// ... add elements ...

(for some reason, SO seems to be turning my dollar signs into double dollars, but you get the idea).

u can use the live() method to bind elements(even newly created ones) to events and handlers, like the onclick event. Here is a sample code I have written, where u can see how live() method binds chosen elements, even newly created ones, to events:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js">      </script>

<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
        $('.FOO').live("click", function (){alert("It Works!")});
        var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                         autoOpen: false,
                                                                                    tite: 'Basic Dialog'
                                //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                                var button = document.createElement("input");
                             alert("It Works!");

Other solution is add the listener when create the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:

var myElement = $('<button/>', {
    text: 'Go to Google!'

myElement.bind( 'click', goToGoogle);

function goToGoogle(event){

I prefer using on selector and I apply it on document. This binds itself on the document and will be applicable to the elements that will be rendered after page load For ex

$(document).on("click",$(selector), function(){
  //Your code here

Hope this helps. Happy Learning

Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists

  //Particular Parent chield click

  //Dynamic event bind on button class
    alert("Dymamic Clicked");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <input type="button" value="1">
  <input type="text">
  <input type="button" value="5">

Event binding on dynamically created elements?

Since this is the popular post i will add these answer.

Single element:

$(document.body).on('click','.element', function(e) {  });

Child Element :

 $(document.body).on('click','.element *', function(e) {  });

Notice the * added. Event will be triggered for all child of that element.

I have noticed that :

$(document.body).on('click','.#element_id > element', function(e) {  });

Is not working anymore but was working before. Been using Jquery from Google CDN but I dont know if they changed it.

var myElement = $('<button/>', {
    text: 'Go to Google!'

myElement.bind( 'click', goToGoogle);

function goToGoogle(event){

I was having the same issue but you can do it simply. Add an attribute to the element on which you want to add an event, for example if you want to send an ajax request when the user clicks on a button then you have to write this code:

<button onclick="ajaxRequest()" >
    Click me

And create a function in JavaScript like this:

function ajaxRequest() {
   // your javascript code goes here

This also works with dynamically created elements.

Category: javascript Time: 2008-10-14 Views: 4

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.201 (s). 12 q(s)