1

How can I toggle when I add #ID at the end of the URL? For example when I access a URL like domain.com/xxxxxx#01 then my div will show.

$(document).ready(function() {
  $(".toogle_button_<?php echo $link_shs['no_e'] ?>").click(function() {
    $("#<?php echo $link_shs['no_e'] ?>").slideToggle();
  });
  if (location.hash) {
    var id = location.hash.slice(1);
    var elementToShow = $("#" + id);
    if (elementToShow.length) {
      elementToShow.slideToggle();
    }
  }
});

#01 is the id from $link_shs['no_e'].

1 Answer 1

1

You can use location.hash to read the fragment from the URL, then use it to select the element. Try this:

if (window.location.hash) {
  $(window.location.hash).slideToggle();
}

You'd obviously need to make this more secure and check that the hash is a valid value that you want to allow, but that's the general pattern to use.

Sign up to request clarification or add additional context in comments.

2 Comments

i edit my code, please take a look, it show and hide 3 times and hide it at the end.
You don't need the slice() call at all. You remove the leading # just to put it back again. Also, nothing about the code you've shown will execute three times. That is incredibly odd behaviour, as it should only run on load which can happen once per page. Can you set up a demo of the issue in a jsfiddle.net?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.