Skip to content Skip to sidebar Skip to footer

Jquery Click Event Target Padding

I am trying to register clicks using jQuery and there seems to be an issue with the padding. Here's a jsFiddle to help with seeing it. I'm trying to get clicks on an open menu to d

Solution 1:

Your problem is with this line:

$parents = $target.parents(".menu");

Change it to this:

$parents = $target.closest(".menu");

The div doesn't have a parent with the class .menu, so if you click that, it doesn't find anything. closest includes the selected element in the search.

http://jsfiddle.net/ecnGr/

Solution 2:

Use closest to solve your issue

$parents = $target.closest(".menu");

If you still want to use parents then add an extra check to see if the clicked element is the div.

if ($parents.length > 0 || $target.is('.menu')) {

Check Fiddle

The problem with your code was that parents method does not include the element in question. So you have to do that check explicitly, or use closest which includes the element in question as well.

Solution 3:

You can just consume all clicks on the menu, which will do the trick.

$(document).ready(function () {
    //Attach a handler to the document for clicks.
    $(document).on("click", function (e) {
        $('.menu').hide();
    });

    $('.menuLink').on("click", function (e) {
        $('.menu').hide();
        e.stopPropagation();
        e.preventDefault();
        var targetMenu = $(e.target).attr("href");
        $(targetMenu).show();
    });

    //Handle showing the menu.
    $('.menu').on("click", function (e) {
         e.stopPropagation();
    });
});

http://jsfiddle.net/MightyPork/UCwAt/8/

Post a Comment for "Jquery Click Event Target Padding"