Mohamed Fathy Mohamed Fathy - 6 months ago 25
Javascript Question

Toggle element with jQuery from a click function

I want to toggle an element from a click function to hide and show my navigation bar. I can show it using the below jQuery code but to toggle it, it does not work for me.

I tried to make two functions, one to show and another to hide, but it didn't work either.



$(function() {
$(".navig-icon").click(
function() {
$(".second-nav").css("display", "block");
},
function() {
$(".second-nav").css("display", "none");
}
);
});

<!-- The below line is added for the Stack Overflow snippet to work, it's not in the real code -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Real code: -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/jquery-1.12.0.min.js"></script>
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/jquery-1.10.2.min.js"></script>
<link rel="shortcut icon" href="img/favicon.jpg" type="image/x-icon" />
<link rel="stylesheet" href="responsiveslides.css">
<link rel="stylesheet" href="demo.css">
</head>

<body>

<div class="navig-icon">
<img src="img/navig-icon.png">
</div>
<nav class="second-nav">
<ul class="second-nav-list">
<li><a href="index.html" class="active">Home</a>
</li>
<li><a href="aboutus.html">About us</a>
</li>
<li><a href="products.html">Products</a>
<ul class="second-dropdwn">
<li class="second-sub1"><a href="#"> Product 1</a>

<ul class="second-sub-list1">
<li><a href="#">sub p1</a>
</li>
</ul>

</li>
<li class="second-sub2"><a href="#"> product 2</a>

<ul class="second-sub-list2">
<li><a href="#">sub p1</a>
</li>
</ul>

</li>
<li class="second-sub3"><a href="#">product 3</a>

<ul class="second-sub-list3">
<li><a href="#">sub p1</a>
</li>
<li><a href="#">sub p1</a>
</li>
<li><a href="#">sub p1</a>
</li>
</ul>

</li>
</ul>
</li>
<li><a href="career.html">Career</a>
</li>
<li><a href="contactus.html">Contact us</a>
</li>
</ul>
</nav>
<script src="js/jq.js"></script>

</body>

</html>




Answer

Instead of this:

$(".navig-icon").click(
    function() {
        $(".second-nav").css("display","block");
    },
    function() {
        $(".second-nav").css("display","none");
    }
);

Can you try using this?:

$(".navig-icon").click(
    function() {
        $(".second-nav").toggle();
    }
);