RedGiant
RedGiant

Reputation: 4748

trouble using this script to make the button close by clicking outside

I'm trying to use the following script to make the button close its menu by clicking outside of it.

$(document).ready( function(){

$('#trigger').click( function(event){

    event.stopPropagation();

    $('#drop').toggle();

});

$(document).click( function(){

    $('#drop').hide();

});});

You can see the demo ([Ideal Fiddle])(http://jsfiddle.net/craigmdennis/H2Chj/2/)

But my button ([Problematic Fiddle]) (http://jsfiddle.net/xJ9ug/) isn't working that well. It takes a few clicks to open the menu. Would you please tell me what's wrong with the css or the script? Any help is much appreciated.

Upvotes: 1

Views: 82

Answers (3)

Sanjeevi Rajagopalan
Sanjeevi Rajagopalan

Reputation: 232

Check out this fiddle. All you need is a simple condition check to make this work.

if ($('#dropdown').has(e.target).length === 0)

Upvotes: 3

Deep Sharma
Deep Sharma

Reputation: 3483

actually your code is correct .. the reason why it is not working is it have <input type="checkbox" /> inside a span and click event is being added for span. I don't know the exact reason why checkbox is not let the event propogate but removing the checkbox works like a charm..

and yea one more thing you haven't closed first span tag properly.

working demo without checkbox HERE

use addClass() and removeClass() to acheive the effect you demo had.

thanks

Upvotes: 2

Sasidharan
Sasidharan

Reputation: 3750

Add .dropdown_content li a,its working now..

$(document).ready( function(){

    $('.dropdown').click( function(event){       
        event.stopPropagation();        
        $('.dropdown_content li a').toggle();      
    });   
});

Upvotes: -1

Related Questions