h2O
h2O

Reputation: 544

jQuery simple dropdown

I am trying to make a simple dropdown using jQuery which opens on mouse click and closes on mouse click or a click over the document. I have the following JS code to make that work. Refer to my code at http://jsfiddle.net/4mCsy/1/ .But the code is not working :-

var x=0;
if(x==0){
    $(".notification").click(function(){
        $(".drpdwn").css("display","block");
    });
    x=1;

}
if(x==1){
    $(".notification").click(function(){
        $(".drpdwn").css("display","none");
    });
    x=0;

}

But, when I change the code to the following(removing the lower portion of the code) (http://jsfiddle.net/4mCsy/2/), the code partly works in just openiing the dropdown. But does not closes (OBVIOUSLY):-

var x=0;
if(x==0){
    $(".notification").click(function(){
        $(".drpdwn").css("display","block");
    });
    x=1;

}

Please tell me where am I going wrong. Any help will be appreciated.

Upvotes: 0

Views: 2559

Answers (3)

Shivam Chopra
Shivam Chopra

Reputation: 639

You are going write as of now you are only specifying that you need to open the dropdown when you click but not close. So, you can use toggle() to open and close the dropdown.

<div class="notification">Notification</div>
<div class="drpdwn"></div>
$(".notification").on('click',function(){
     $(".drpdwn").toggle('blind', 'options', 500 );
});

Here's the link for it : http://jsfiddle.net/coolshivster/4mCsy/25/

Upvotes: 0

MackieeE
MackieeE

Reputation: 11862

They've made it a little to do this in recent jQuery versions:

jQuery toggle()

$(document).on('click', '.notification', function() {
    $('.drpdwn').toggle(); 
});

If you wish to exclude the dropdown itself, which is toggling because .drpdwn is child member of .notification, you'd have to exclude it from a given condition - I'd prefer doing that from the event.target.

$(document).on('click', '.notification', function( event ) {
   if ( event.target.className != 'drpdwn' )
       $('.drpdwn').toggle();
});

Demo

Otherwise you'd have to separate the two <div>'s because as explained previously, they're a member of each other. Thus, the jQuery selector will listen to both <div>s when you click .notification. To prevent this, restructure your HTML as below:

<!-- Notification Click -->
<div class="notification">
    Notification
</div>

<!-- Dropdown Div -->
<div class="drpdwn">
</div>

Upvotes: 2

Satinder singh
Satinder singh

Reputation: 10198

$(".notification").on('click',function(){
  $(".drpdwn").toggle();
});

Demo

Updated:

<div class="notification">Notification</div>
<div class="drpdwn"></div>
$(".notification").on('click', function () {
    $(".drpdwn").toggle('slow');
});

Demo 2

Upvotes: 1

Related Questions