-1

I have click functions in jQuery to show/hide different content:

$(“#button1”).click(function() {
  $(“#project1”)[0].style.display = "block";
  $(“#project2”)[0].style.display = “none”;
});

$(“#button2”).click(function() {
  $(“#project1”)[0].style.display = “none”;
  $(“#project2”)[0].style.display = “block”;
});

I want to have an identical URL in each situation. For example when #project1 is shown I want the URL in the webpage different than the URL when #project2 is shown.

Now it is always https://…./..../projects/index.html

How can I do it?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kexin Hao
  • 13
  • 1

1 Answers1

1

You can use window.location.hash to add a fragment to the URL.

In addition, if you're using jQuery to select elements and add event handlers, you may as well use it to show/hide content too. Also note that the quotes you're using are not valid JS. Only " and ' is allowed. Try this:

$("#button1").click(function() {
  $("#project1").show()
  $("#project2").hide();
  window.location.hash = 'project1';
});

$("#button2").click(function() {
  $("#project1").hide();
  $("#project2").show();
  window.location.hash = 'project2';
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • It works, thank you! But then I wonder: if I refresh the URL "https://…./..../projects/index.html#project1", how it can show #project1 without clicking the button..? – Kexin Hao Mar 27 '20 at 11:53
  • You need to write the code for that to happen. You can use [this](https://stackoverflow.com/a/6682514/519413) to detect the fragment. Then you just need to show/hide the relevant elements – Rory McCrossan Mar 27 '20 at 11:54