Dancer
Dancer

Reputation: 17671

Toggle link HREF

I have a menu panel that is displayed via pure css - using #nav - its controlled by a simple button

<a id="nav-burger" href="#nav">
     <span></span>
     <span></span>
     <span></span>
     <span></span>
</a>

I'd like to toggle the href on click to display #home - can anyone advise how to do this?

I am using this format but my syntax is a bit messed up and there must be an easier way!

$(document).ready(function(){
  $('#nav-burger').click(function(){
    $(this).toggleClass('open');
     $(this).attr('href',$(this).attr('href') == '#nav' ? '#nav' : '#home');
  });
});

Thanks

UPDATE As a demo - In the code snippet below - whenever the link gos red the href should have the value of #home and visa versa fro blue (#nav)

$(document).ready(function(){
  $('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});
});
a{color:blue}
a.open{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="nav-burger" href="#nav">
     
          hello
    
      </a>

Upvotes: 0

Views: 1655

Answers (1)

charlietfl
charlietfl

Reputation: 171690

You can use attr(attributeName, function) and chain the methods

$('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});

Upvotes: 2

Related Questions