user3881000 user3881000 - 5 months ago 8
Javascript Question

How to turn a CSS class on and off by clicking a button

I have some code I got from a youtube tutorial (https://www.youtube.com/watch?v=nQK0kz65wpo) and i cannot find why it is not working. It is a responsive navigation bar. I want to change ul (class="showing") to (ul class=" ") when i click Menu. I cannot see why it is not working and I've been at it for quite a while. Any help would be great thanks! sorry i'm new at this.

<nav>
<ul class="showing">
<a href="#"></a><li>1</li></a>
<a href="#"></a><li>1</li></a>
<a href="#"></a><li>1</li></a>
<a href="#"></a><li>1</li></a>
<a href="#"></a><li>1</li></a>
<a href="#"></a><li>1</li></a>
</ul>
<div class="handle">Menu</div>
</nav>


in the head

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>


in the body

<script>
$('.handle').on('click', function(){
$('nav ul').toggleClass('showing');
});
</script>

Answer

It seems to be working just fine. Maybe you don't have any styles attached to the showing class so you don't realize it's actually working?

$('.handle').on('click', function(){
            $('nav ul').toggleClass('showing');               
      });
ul.showing {
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
   <ul class="showing">
       <a href="#"></a><li>1</li></a>
       <a href="#"></a><li>1</li></a>
       <a href="#"></a><li>1</li></a>
       <a href="#"></a><li>1</li></a>
       <a href="#"></a><li>1</li></a>
       <a href="#"></a><li>1</li></a>
   </ul>
   <div class="handle">Menu</div>
</nav>

Comments