Misha Kolosov
Misha Kolosov

Reputation: 13

jQuery onclick add class and remove

My code does not work correctly. I need to when user click on an class="menubutton" to tag header add classes "hidden". When pressed again, the class was removed.

here is my Code.

HTML:

<header>
  <div class="headgeneral">
    <div id="headerlogo_dot">
      <div class="menubutton">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>
    </div>
  </div>

jQuery:

jQuery('.menubutton').click( function() {
    jQuery("header").toggleClass("hidden"); 
});

Upvotes: 1

Views: 386

Answers (2)

Abi
Abi

Reputation: 734

$('document').ready(function() {
  jQuery('.menubutton').click(function() {
    jQuery("header").toggleClass("hidden");
  });
});
.headgeneral{
  border: 2px solid black;
  padding: 30px;

}

.menubutton{
  border: 1px solid green;
  padding: 10px;
}

.hidden{
  background: #ffd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<header>
  <div class="headgeneral">
    <div id="headerlogo_dot">
      <div class="menubutton">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>
    </div>
  </div>
</header>

When using JQuery must written code within ready method and you didn't mention any style for your tag so that it is not visible in the page.

Upvotes: 2

franmartosr
franmartosr

Reputation: 388

You need to load jQuery listener after the document is loaded. You can do it like that:

$('document').ready(function() {
  $('.menubutton').click(function() {
    $("header").toggleClass("hidden");
  });
});

PS: The snippet doesn't load anything, try to fix it. Without that we can't give you more info.

Upvotes: 1

Related Questions