Hans Liu
Hans Liu

Reputation: 37

toggleClass does't work, but addClass does

I have imported jQuery and Bootstrap in my HTML page already.

Anyhoo, I wanted to toggle a dropdown menu once I click on the little menu image.

Here's how I hide my menu dropdown:

.menu {
  height:150px;
  width:155px;
  background-color:black;
  border-radius:5px;
  position:absolute;
  top:-10px;
  left:100%;
  padding-left:0;
}
.menu-active {
  position:absolute;
  top:35px;
  left:60%;
}

To make it responsive, I first tried addClass (menuBtn is the button image and I got):

$('.menuBtn').click(function(){
  $('.menu').addClass('menu-active');
})

Which works pretty smooth, though it's always ignored if I added time like addClass('menu-active', 1000), but this is a minor problem! I want to make it toggle, so I tried to change it to toggleClass:

$('.menuBtn').click(function(){
  $('.menu').toggleClass('menu-active');
})

Even when I intended to bypass toggle and just use if like:

function menuDropdown(){
$('.menuBtn').on('click', function(){
 if($('.menu').hasClass('menu-active')){
  $('.menu').removeClass('menu-active');
  }else{
    $('.menu').addClass('menu-active');
 });
}

Both of these don't work, the website just ignored them thoroughly. I know bootstrap does have a simpler way to do this, I just wanna see what can I write on my own.

Upvotes: 2

Views: 3214

Answers (1)

Bryan Miller
Bryan Miller

Reputation: 3323

Here is one way to solve the problem. Create an ID and use that to refer to your menu instead of trying to use the menu class:

HTML:

<div id="toggler" class="menu">Menu Example</div>
<button type="button" class="menuBtn">Click me</button>

JQuery:

$('.menuBtn').click(function () {
        $('#toggler').toggleClass('.menu-active menu');
 });

Notice how the above toggles both the .menu-active and the .menu class based off of the #toggler ID.

A working example: http://jsfiddle.net/gratiafide/vubsv2pt/12/

Upvotes: 1

Related Questions