0

i have created <ul> containing two <li> , but none of them firing click event .

code

    var d = document.createElement('div');
    d.className = "dataTables_paginate paging_bootstrap pagination";
    var UL = document.createElement('ul');
    var L1 = document.createElement('li');
    L1.className = 'prev';
    var A1 = document.createElement('a');
    A1.appendChild(document.createTextNode('← Previous'));
    A1.id = 'B1';
    L1.appendChild(A1);
    UL.appendChild(L1);
    var L3 = document.createElement('li');
    L3.className = 'active';
    var A3 = document.createElement('a');
    A3.appendChild(document.createTextNode('1'));
    L3.appendChild(A3);
    UL.appendChild(L3);
    d.appendChild(UL);
    var L2 = document.createElement('li');
    L2.className = 'next';
    var A2 = document.createElement('a');
    A2.appendChild(document.createTextNode('Next →'));
    L2.appendChild(A2);
    A2.id = 'B2';
    UL.appendChild(L2);
   var root = document.getElementById('rose');
   root.appendChild(d);

script

$('#B1').click(function () {

        alert('back');
    });

    $('#B2').click(function () {

        alert('next');
    });
  • 1
    check this out > http://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-trigger-and-on – Cracker0dks Jan 15 '14 at 13:19
  • check this it worked for me http://stackoverflow.com/questions/21073425/create-element-with-eventlistener-dynamically-in-javascript – sam Jan 15 '14 at 13:21

2 Answers2

0

Try this for event delegation

$('#myContainer').on("click", element , function(){
   alert('back');
});
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • 1
    @BaqerNaqvi Ordinary event handlers are only added to elements that exist at the time. Using `.on('click',selector)` will check if the clicked element matches the selector, even if it was added later. – Scimonster Jan 15 '14 at 13:31
  • @BaqerNaqvi SO question: [Direct vs delegated](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on) – LeGEC Jan 15 '14 at 13:37
  • @BaqerNaqvi Just do it in the body of the function, where it currently has `alert('back');` – Scimonster Jan 15 '14 at 15:03
  • i have tried this : $(this).attr("disabled", true); but no difference ... @Scimonster –  Jan 15 '14 at 15:07
  • Try `$(this).attr("disabled", "disabled");`? – Scimonster Jan 15 '14 at 16:33
0
use jQuery 'on' method to fire click function on dynamically added ul.

example :-    $('#parent').on("click", "#child", function() {});

Answer

$('#parentDiv').on('click','#B1', function () {

    alert('back');
});

$('#parentDiv').on('click','#B2', function ()  {

    alert('next');
});
Venu immadi
  • 1,585
  • 11
  • 20