0

It been a long day, I suspect that is contributing to this seemingly simple issue.

I have a burger menu that, I need to toggle the #url on, it needs to toggle between:

Open = #open
Close = #close

My jquery code looks like this:

        $('.menu').click(function () {
            $(this).attr("href","#close");
        });

and my html looks like this:

 <a href="#open" class="menu">
   <b></b>
   <b></b>
   <b></b>
   <span>Menu</span>
</a>

I can open the menu fine, I can close it too, however, once I have closed the menu I can't then open it again since the href is still showing as #close. So, I wondered how I can toggle it so whatever the url, the href is the opposite?

I Appreciate any help.

CompanyDroneFromSector7G
  • 4,291
  • 13
  • 54
  • 97
  • 1
    `window.location.hash = "open"` – Rory McCrossan May 23 '19 at 13:09
  • Possible duplicate of [Using location.hash to activate jquery toggle/slideToggle](https://stackoverflow.com/questions/6700276/using-location-hash-to-activate-jquery-toggle-slidetoggle) – Feras Al Sous May 23 '19 at 13:15
  • @RoryMcCrossan could you expand on window.location.has and where it fits into my script, I haven't used it before. – leewilson78 May 23 '19 at 13:24
  • That line would go in your `click` handler. There's also `pushState()` which allows you more control. Details are on MDN: https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries – Rory McCrossan May 23 '19 at 13:26
  • @RoryMcCrossan I tried that but it didn't seem to work, could you perhaps post a revised code to make sure I haven't messed up somewhere? – leewilson78 May 23 '19 at 13:32
  • Use css pseudo classes to control this kind o thing. – Marco May 23 '19 at 13:45

3 Answers3

0

I usually use <a href="#open"> but alternatively window.location.hash. A nice way to handle it is to use the following to do your actions:

$(window).on('hashchange', function() {
});

I make my hash string exactly like an HTTP GET string, parse the pairs manually, then shoot that off to an AJAX call. It's a nice way to get AJAX to play with direct links and browser history.

MaKR
  • 1,882
  • 2
  • 17
  • 29
0

Just check what is the href attribute value every time the menu is clicked and change it's value?

This should work:

$('.menu').click(function() {
    if($(this).attr("href") == "#open") {
        $(this).attr("href", "#close");
    } else {
        $(this).attr("href", "#open");
    }
});
0

The below solution works in your case.

    $('.menu').click(function(e) {
      var hash = (e.currentTarget.hash === "#close") ? '#open' : '#close'
      $(this).attr("href", hash);
    });
kpr379
  • 13
  • 3