Question

Hi friends i want the drop down menu just like facebook. when i click on the menu it want to be open and if i again clicked it want to be close. And when it is open if i click on any other area then also it want to be close.... please help me.

I used the jquery as below:

$(document).ready(function ()
 {
    $('.profile').on('click', function ()
    {
        $('.profile-mgnt').fadeToggle("slow").toggleClass('act_drop');
    });
    $('body').on('click', function (e)
    {
        if ($('.profile-mgnt').hasClass('act_drop'))
        {
            if (!$(e.target).parent().hasClass('profile-mgnt'))
            {
                $('.profile-mgnt').removeClass('act_drop');
            }
        }
    });
});
Was it helpful?

Solution

You don't know what was clicked. It could have been the drop down itself. It could have been a link inside the drop down. It could have been the textnode inside the link inside the drop down. So using parent will only get you up ONE level from the target. And actually, in this case target will be body since it propagated up to body so that won't help either. See this article about target vs currentTarget.

So, what you really want is to say "If what I clicked doesn't have an ancestor with class profile-mgnt, then I want to close (remove the class)".

Something like this: if(!$(e.currentTarget).closest('.profile-mgnt').length). Closest goes up up the ancestor chain matching on the filter criteria, in this case an ancestor with class .profile-mgnt. If it can't be found, then you didn't click anywhere inside the profile-mgnt scope, so removeClass.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top