0

At the begging I have one ul:

<div id="ul1DivId">
    <ul id="ul1Id">
        <li>li1</li>
    </ul>
</div>

Than I have a javascript that will hide this div/ul and add another div with another ul:

$(document).ready(function () {
$("#ul1Id > li").click(function() {
                    //to prevent scroll firing this handler:
        event.preventDefault();

        $("#ul1DivId").hide();
        var someValue = "someValue";
        var outputUl2Html = "<div id=\"ul2DivId\">" +
        "<ul id=\"ul2Id\">" +
        "<li id=\"liXId\">> " + someValue + "</li>" +
        "<li id=\"clearLiId\">-clear-</li>" +
        "</ul>" +
        "</div>";
        //show ul 2
        $(outputUl2Html).insertAfter('#ul1DivId');

});
});

Than I get style="display: none; " in the div with id="ul1DivId". This is expected. And I get the new inserted div after the hidden div element. This is expected too.

I have another javascript that never gets fired when clicking clearLiId:

$(document).ready(function () {
    $("#clearLiId").click(function() {
        //I never reach here!!!!
    });
});

I tried also #ul2Id > li and #ul2Id > #clearLiId as selectors. Nothing gets the handler fired when I click on the #clearLiId li! Why? How do I get it to catch the click event? I want to show the first div (ul1DivId) again and remove the current div (ul2DivId).

Manse
  • 37,765
  • 10
  • 83
  • 108
despot
  • 7,167
  • 9
  • 44
  • 63

2 Answers2

2

You have to use live() function because the selector does not exist yet.

Attach an event handler for all elements which match the current selector, now and in the future.

$(document).ready(function () {
    $("#clearLiId").live(function() {
        //I never reach here!!!!
    });
});
Kristian
  • 1,058
  • 1
  • 11
  • 16
2

You're missing event arguments and you need delegate event like following:

$(document).on('click', '#clearLiId', function() {
     //I never reach here!!!!
});


$("#ul1Id > li").click(function(event) {...
                                 ^ ----- missing event  

Note

I seems though $("#ul1Id > li"). is working for your first ul but it will not working for future coming uls. So it would be better if you assign class to each ul(already in DOM and will come in future) and change your selector. For example:

HTML

<div id="ul1DivId">
    <ul id="ul1Id" class="someClassToUl">
        <li>li1</li>
    </ul>
</div>

jQuery

$(".someClassToUl > li")...
Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • I don't get what u mean by "future coming ul s", but $("#ul1Id > li").click(function() { works well even without the event part. thanks for the on solution though! – despot Jun 19 '12 at 15:20
  • @despot that means `ul` coming to DOM after page load. But feeling happy to know that works. – thecodeparadox Jun 19 '12 at 15:22
  • Actually the function(event) part is required for ff. I was looking only in chrome. Thanks again! – despot Jun 21 '12 at 09:50