简体   繁体   中英

Hide a div if an element has been clicked twice in a row, else Show

I have several items in my navigation bar, and a div next to it, ie:

<nav>
  <a id="a"></a>
  <a id="b"></a>
  <a id="c"></a>
</nav>
<div id="menu-col"></div>

If the same link is clicked twice in a row, I want to hide #menu-col . If not, I want #menu-col to remain visible.

I'm not a javascript guy so I tried this:

var lastClicked;
$('nav a').on('click', function(e) {
    alert(e.target.id + " - " + this.lastClicked);
    if (e.target.id == this.lastClicked) {
        $('#menu-col').hide();
        this.lastClicked = '';
    }
    else {
        $('#menu-col').show();
        this.lastClicked = e.target.id;
    }
});

Then I remembered that javascript assigns references, and not values. So when I did this.lastClicked = e.target.id; I'm assigning a reference to my element's id, then on the next click I make that e.target.id == '' .

In javascript, what would be the proper way of closing a box if the same link is clicked twice, and if not making sure the box is visible.

You can achieve this using toggleClass() to set a state class on the clicked a and also using toggle() on the .menu-col to show or hide it based on that state class. Try this:

 $('nav a').click(function(e) { e.preventDefault(); var $a = $(this); $a.toggleClass('active').siblings().removeClass('active'); $('.menu-col').toggle($a.hasClass('active')); }); 
 .menu-col { display: none; } .active { color: #C00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <a id="a" href="#">a</a> <a id="b" href="#">b</a> <a id="c" href="#">c</a> </nav> <div class="menu-col">menu-col</div> 

As long as you keep those ids unique across you app (which you should be doing anyway) the approach you've chosen isn't wrong. Any primitive in javascript is actually stored by value. Those primitives are string, number, boolean, and symbol. For more info see here https://developer.mozilla.org/en-US/docs/Glossary/Primitive

I would suggest something like this, you should have some kind of condition in which the div shows after it has been hidden.

$('nav a').dblclick(function(event) {
    event.preventDefualt();
    alert($(this).attr('id'));
    $('#menu-col').toggle();
});

Something like that should be exactly what you are looking for, like I said though, there should be a condition in which it shows itself again, I made it a toggle so any double click on any 'nav a' element will cause it to show/hide the div.

Just for the sake of an option. Here is another way for double clicks(clicked twice in a row).

Using ondblclick event.

 <a href="#" ondblclick="console.log('Double clicked!');">Double-click me.</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM