Rache Riveto Rache Riveto - 3 months ago 9
CSS Question

How to make button which executes a Javascript code have its own URL

I have already posted this but I am going to explain it better with a jsFiddle. Hence, the repost.

I apologize if this has already been asked but I have been looking everywhere and I can't find any help at all.

I have made 'tabs' using anchors with

href='#'
. However, what I want is when I click button1 it changes the url to www.myurl.com/btn1 and when I click button 2 - www.myurl.com/btn2.

When I visit www.myurl.com/btn1 I want button1 to be highlighted as it is when clicked on the jsFiddle.I've searched everywhere but found no way of doing this.

Answer

The simplest way to do this is by using the fragment of the URL to store the id of the tab, ie. myurl.com#tab1. You can then check on load if the URL has a fragment (using location.hash) and set the default tab and you can use the exact same mechanism in the href attribute of the a elements you use to change tabs. Try this:

$('.tab-trigger').click(function() {
  showTab($(this).attr('href'));
})

if (window.location.hash)
  showTab(window.location.hash);
    
function showTab(tab) {
  $('.tab-content').hide();
  $(tab).fadeIn();
}
.tab-content {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#div1" class="tab-trigger">Button 1</a>
<a href="#div2" class="tab-trigger">Button 2</a>
<a href="#div3" class="tab-trigger">Button 3</a>

<div id="div1" class="tab-content">div 1</div>
<div id="div2" class="tab-content">div 2</div>
<div id="div3" class="tab-content">div 3</div>

Comments