Trevan Hetzel
Trevan Hetzel

Reputation: 1369

jQuery blur()....How exactly does it work?

I've created a mobile dropdown menu for a responsive website, that essentially shows a hidden unordered list when you click on a certain element. It works great, except for the fact that I can't get the blur() function to work, so that when a user clicks anywhere on the page other than inside the menu, it hides the menu. Here's a codepen: http://codepen.io/trevanhetzel/pen/wIrkH

My javascript looks like so:

$(function() {
    var pull = $('#pull');
    menu = $('header ul');

    $(pull).on('click', function(e) {
        e.preventDefault();
        $('.close-menu').toggle();
        $('.mobi-nav span').toggle();
        menu.slideToggle(250);
    });

    $(menu).blur(function() {
        $(this).slideToggle();
    });
});

I've struggled with blur() in the past, so would really like to figure out once and for all how exactly it works, and whether or not I'm using it in the right context here. Thanks!

Upvotes: 1

Views: 206

Answers (1)

Brandon
Brandon

Reputation: 39192

You have to watch for clicks yourself. And use $.contains to see if the clicked thing is within your menu:

$(document).click(function (ev) {
    if (ev.target !== menu.get(0) && !$.contains(menu.get(0), ev.target)) {
       menu.slideUp();
    }
});

Just be sure to call ev.stopPropagation() in your toggle click handler to prevent the handler above from immediately closing the menu when the event bubbles up.

Upvotes: 1

Related Questions