Faris MX Faris MX - 3 years ago 69
jQuery Question

Change image src as toggle button works

when i'm using this code ,when i click nav-btn one time it become changed but when i click second time content will hide and nav-btn (src) unchanged
i want to get the default src(drop down-icon) when i click second time(but my button still close-icon)



$(document).ready(function(){
$("img.nav-btn").click(function(){
$("nav>ul").toggle('slow');
$(".nav-btn").attr('src', 'http://www.salmanulfaris.com/GEM/images/button_1.png')(500);
});
});

.nav-ul {
background-color:#252525;
width:100%;
display:none;
padding: 40px 0px 10px 0px;
margin:0px 0px 0px 0px;
position:absolute;
height:375px;
right:0;
}
.nav-ul > li {
display:block;
width:50%;
border-bottom:solid 1.5px #57d846;
margin:0 auto;
margin-bottom:25px;
font-weight:700;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<nav>
<img src="http://www.salmanulfaris.com/GEM/images/button.png" class="nav-btn">
<ul class="nav-ul" id="">
<li><a href="#" >HOME</a></li>
<li ><a href="#" >TUTORIALS</a></li>
<li><a href="#">ARTICLES</a></li>
<li><a href="#">ABOUT US</a></li>
</ul>
</nav>




Answer Source

The issue is because you only set the src of the img once. Instead you need to check that the current src is then toggle it on each click, something like this:

$("img.nav-btn").click(function() {
  $("nav > ul").toggle('slow');
  $(".nav-btn").attr('src', function(i, src) {
      return src == 'http://www.salmanulfaris.com/GEM/images/button.png' ? 'http://www.salmanulfaris.com/GEM/images/button_1.png' : 'http://www.salmanulfaris.com/GEM/images/button.png';
  });
});
.nav-ul {
  background-color: #252525;
  width: 100%;
  display: none;
  padding: 40px 0px 10px 0px;
  margin: 0px 0px 0px 0px;
  position: absolute;
  height: 375px;
  right: 0;
}

.nav-ul>li {
  display: block;
  width: 50%;
  border-bottom: solid 1.5px #57d846;
  margin: 0 auto;
  margin-bottom: 25px;
  font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<nav>
  <img src="http://www.salmanulfaris.com/GEM/images/button.png" class="nav-btn">
  <ul class="nav-ul" id="">
    <li><a href="#">HOME</a></li>
    <li><a href="#">TUTORIALS</a></li>
    <li><a href="#">ARTICLES</a></li>
    <li><a href="#">ABOUT US</a></li>
  </ul>
</nav>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download