Search code examples
jquerycssparentchildren

'this' parent selector not working


http://jsfiddle.net/raduv118/

I've got two jQuery functions, respectively either showing or hiding a div, nested inside a div, nested inside a list.

First function applies CSS display: block, and the second one applies display: none. But the second function is not working.

Check out the fiddle.

  1. Click the green li element to load the first function.
  2. Click the orange div header to load the second function. (NOT WORKING)

What I wan't to achieve, in plain English, is two functions. First one to open the child, second one to close the parent.

NOTE: NO other selector than parent and child must be used, thereby no specific ID's. The code is meant to be applied onto a whole lot of the same structures.

$(document).ready(function () {
    $('.listcontainer').click(function () {
        $(this).children().css('display', 'block');
    })
});
$(document).ready(function () {
    $(".popup_header").click(function () {
        $(this).parent('div').css("display", "none");
    })
});

Solution

  • The issue is because the click event bubbles up the DOM, so clicking on the inner div makes it appear, but then the parent click event fires which immediately hides it again. You need to use stopPropagation() on the click event of the inner div:

    $(".popup_header").click(function (e) {
        e.stopPropagation();
        $(this).parent('div').css("display", "none");
    });
    

    Example fiddle

    Also note that you can put all your code inside a sing DOMReady handler.