javascript - jQuery click event target padding -
i trying register clicks using jquery , there seems issue padding.
here's jsfiddle seeing it.
i'm trying clicks on open menu nothing while clicks anywhere else close menus. works well, biggest problem if click above <li>
still within <div>
fails. seems padding isn't counted part of div or something.
the code here well:
html
<a href="#mainmenu" class="menulink">main</a> <div id="mainmenu" class="menu"> <ul> <li class="menuitem"><a href="#">item 1</a> </li> <li class="menuitem"><a href="#">item 2</a> </li> <li class="menuitem"><a href="#">item 3</a> </li> <li class="menuitem"><a href="#">item 4</a> </li> <li class="menuitem"><a href="#">item 5</a> </li> </ul> </div> <a href="#menutwo" class="menulink">menu 2</a> <div id="menutwo" class="menu"> <ul> <li class="menuitem"><a href="#">item 1</a> </li> <li class="menuitem"><a href="#">item 2</a> </li> <li class="menuitem"><a href="#">item 3</a> </li> <li class="menuitem"><a href="#">item 4</a> </li> <li class="menuitem"><a href="#">item 5</a> </li> </ul> </div>
js
$(document).ready(function () { //attach handler document clicks. $(document).on("click", function (e) { //get click's target , convert $ object. $target = $(e.target); //find out if click occurred on menu. $parents = $target.parents(".menu"); if ($parents.length > 0) { console.log(["menu click", e]); return; } else { //if wasn't on menu close open menu. console.log(["non-menu click", e]); $('.menu').hide(); } }); //handle showing menu. $('.menulink').on("click", function (e) { //close other menus. $('.menu').hide(); console.log("started"); e.stoppropagation(); e.preventdefault(); var targetmenu = $(e.target).attr("href"); $(targetmenu).show(); });
});
css
#mainmenu { background-color: lightblue; } #menutwo { background-color: lightgreen; } .menu { display: none; border: 1px solid black; }
your problem line:
$parents = $target.parents(".menu");
change this:
$parents = $target.closest(".menu");
the div doesn't have parent class .menu
, if click that, doesn't find anything. closest
includes selected element in search.
Comments
Post a Comment