0

community!

The idea is to create a list with normal list with text and sometimes clickable links.

Problem:
How to make this list to close only when the button is pressed and not when the user click on any item inside the list or anywhere on screen.

Fiddle: jsfiddle.net/H2Chj/494/

HTML:

<button data-text-swap="Show" id="trigger">Hide</button>    
<div id="drop">   
<a href="#">Menu item 1</a>
    <a href="#">Menu item 2</a>
    <a href="#">Menu item 3</a>
    <a href="#">Menu item 4</a>
</div> 

Javascript

$(document).ready( function(){

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

    event.stopPropagation();

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

});

$(document).click( function(){

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

});

$("button").on("click", function() {

    var el = $(this);

    if (el.text() == el.data("text-swap")) {

        el.text(el.data("text-original"));} 
    else {

        el.data("text-original", el.text());

        el.text(el.data("text-swap"));}
});

});
Bohdan
  • 31
  • 6
  • 3
    then why did you add the `$(document).click` listener which does `$('#drop').hide()`? – wiesion Sep 11 '15 at 22:35
  • Its kinda duplicated of this... I tried and it works fine - http://jsfiddle.net/H2Chj/505/ http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it edit: oh just saw the second part... yeah... joining the question above me... if you don't want it to close on any click, remove the document click event... – Ziv Weissman Sep 11 '15 at 22:52

2 Answers2

0

Please use this javascript code:

$(document).ready( function(){

$("button").on("click", function() {


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

    var el = $(this);

    if (el.text() == el.data("text-swap")) {

        el.text(el.data("text-original"));} 
    else {

        el.data("text-original", el.text());

        el.text(el.data("text-swap"));}
 });

});
Atif Tariq
  • 2,650
  • 27
  • 34
0

The one thing you had missing was stopping the propagation when you click on a link in the dropdown. this stops it from bubbling up to the $(document).click event handler.

$('#drop a').click(function(e){ e.stopPropagation(); });

I assume you had the $(document).click handler there so you could close the dropdown by clicking outside the dropdown menu.

see this fiddle: http://jsfiddle.net/o0m8p4bf/2/

Gregg Duncan
  • 2,635
  • 1
  • 14
  • 20