Tuesday, 10 January 2012

click event does not work / trigger/fire, click event triggers/fires in double click

when working on click event in javascript or jquery, click won't fire the event 
in a single click. it requires double click. in that case 
your code may look like the following
 
<ul id="drop-menu" style="display:none;">
<li><a href="..">xxxx xxxx</a> </li>
<li><a href="..">** *** *** **</a> </li>
<li><a href="..">... ... .. </a> </li>
<li><a href="LogOff">Log Off</a> </li>
</ul>
 
 $("a#my-link").click(function(e) {
$("#drop-menu").slideToggle('medium');
});
$("body").click(function(e) {
$("#drop-menu").hide();
}); 
 
in reality, click event fires / triggers the click event, however along with the 
click event body click event also fires thus hiding your drop-menu.
here we cannot stop body click event, removing which our drop-menu doesnot get 
closed. to stop closing or hiding of our drop-menu on body click, 
we have to check the target of the event
 
like the one in the following code
$("a#my-link").click(function(e) {
$("#drop-menu").slideToggle('medium');
});
$("body").click(function(e) {
if (!$(e.target).is('#my-link')) {
$("#drop-menu").hide();
}
});
 
here in body click i am hiding the drop menu, only when the target of the click
event is my-link.
 

No comments:

Post a Comment