0

i am trying to create a drop down menu using jQuery.

HTML is:

<div id="cats">
    <div id="cat_ram">
        <span>RAM</span>
        <div class="cat_arrow"></div>
        <div class="cat_options">
            <ul class="cat_list">
                <li>1GB</li>
                <li>2GB</li>
                <li>3GB</li>
                <li>4GB</li>
           </ul>
        </div>
    </div>
</div>

my jQuery code is:

$(document).ready(function(e) {

    $('.cat_options').hide();

    $('.cat_arrow').click(function(){
            $('.cat_options').toggle();
        });


        $(document).click(function(){
        if($('.cat_options').is(':visible')){
            $('.cat_options').hide();
            }
        })
});

Here is what i am trying to accomplish:

1)when .cat_arrow is clicked the drop down menu i.e .cat_options should be shown.And when it is clicked again it should hide.

2)While .cat_options is visible if a click event occurs any where else on the page (not on .cat_arrow) .cat_options should hide.

Now the problem is that:

1)For above code the .cat_options never shows. And if i add another if condition like this

if($('.cat_options').is(':hidden')){
        $('.cat_options').show();

Then clicking anywhere in the document would make the .cat_options visible i.e the .cat_arrow would become useless.

1 Answer 1

2

Stop propagation on .cat_arrow click:

$('.cat_arrow').click(function(e){
    e.stopPropagation();
    $('.cat_options').toggle();
});
Sign up to request clarification or add additional context in comments.

6 Comments

Can you explain a little how it worked?? Why did it worked by putting it with toggle(). I think i should have been with the second part i.e $(document).click......?Sorry but i haven't quite understood the concepts involved here:(
See: api.jquery.com/event.stoppropagation Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Otherwise, your click event bound to document level would be fired and so hide the element. An other way would be to filter in document click handler the event target to see if it is descendant of .cat_arrow or .cat_arrow itself. And finally, a completly different way: stackoverflow.com/a/17966127/1414562
OK! isn't it the document element it self the element due to which the clcik event was triggered?? so why would an element lower in DOM tree get notified?? i mean here the second part of code would get executed.
can you suggest some reading on the topics concerned with my problem.
You have to understand event propagation, bubbling and capturing (not relevant here) event phase: stackoverflow.com/questions/4616694/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.