Rexhep Rexhepi Rexhep Rexhepi - 28 days ago 12
Javascript Question

How to change link url when clicking each tab with jquery

I'm trying to change URL link (in browser and in ) when I click each tab with jquery, but I cant. URL should take ID of .vertical-tab-content-container

My HTML code is:

<div class="vertical-tabs">
<a href="" class="js-vertical-tab vertical-tab is-active" rel="tab1">Applications</a>
<a href="" class="js-vertical-tab vertical-tab" rel="tab2">Web Applications</a>
<a href="" class="js-vertical-tab vertical-tab" rel="tab3">Portals</a>
<a href="" class="js-vertical-tab vertical-tab" rel="tab4">Applications</a>
</div>
<div class="vertical-tab-content-container">
<div id="tab1" class="js-vertical-tab-content vertical-tab-content">
<p>Content 1</p>
</div>
<div id="tab2" class="js-vertical-tab-content vertical-tab-content">
<p>Content 2</p>
</div>
<div id="tab3" class="js-vertical-tab-content vertical-tab-content">
<p>Content 3</p>
</div>
</div>


jQuery:

$('.vertical-tab-content').each(function() {
var id = $(".vertical-tab-content").attr('id');
});

$(".vertical-tabs .vertical-tab").each(function(){
$(this).click(function(){
window.location.hash = $(this)[0].id;
});
});

Answer Source

Well there's no need for the first loop in your actual code, in the second loop you can profit from the index in the callback function.

This is how should be your code:

$(".vertical-tabs .vertical-tab").each(function(i){ 
  $(this).click(function(e){
    $(this).attr("href", $('.vertical-tab-content')[i].id);
    window.location.hash  = $('.vertical-tab-content')[i].id;
  });
});

Demo:

$(".vertical-tabs .vertical-tab").each(function(i){ 
  $(this).click(function(e){
  e.preventDefault();
  console.log(i);
    $(this).attr("href", $('.vertical-tab-content')[i].id)
    //window.location.hash  = $('.vertical-tab-content')[i].id;
    console.log($('.vertical-tab-content')[i].id);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vertical-tabs">
   <a href="" class="js-vertical-tab vertical-tab is-active" rel="tab1">Applications</a>
   <a href="" class="js-vertical-tab vertical-tab" rel="tab2">Web Applications</a>
   <a href="" class="js-vertical-tab vertical-tab" rel="tab3">Portals</a>
</div>  
<div class="vertical-tab-content-container">
   <div id="tab1" class="js-vertical-tab-content vertical-tab-content">
      <p>Content 1</p>
   </div>
   <div id="tab2" class="js-vertical-tab-content vertical-tab-content">
      <p>Content 2</p>
   </div>
   <div id="tab3" class="js-vertical-tab-content vertical-tab-content">
      <p>Content 3</p>
   </div>
</div>