I want to check if url contains hashtag with javascript. If yes do nothing if not refresh with default hash. So I did…
HTML:
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist" id="utabs">
<li role="presentation"><a href="#tab1" onClick="window.location.hash='tab1';" data-toggle="tab"data-url="tab1.php?cal=<?=$cal?>">Tab1</a></li>
<li role="presentation"><a href="#tab2" onClick="window.location.hash='tab2';" data-toggle="tab" data-url="tab2.php?cal=<?=$cal?>">Tab2</a></li>
<li role="presentation"><a href="#tab3" onClick="window.location.hash='tab3';" data-toggle="tab" data-url="tab3.php?cal=<?=$cal?>">Tab3</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane" id="tab1"><?include "SL/tab1.php"?></div>
<div role="tabpanel" class="tab-pane" id="tab2"></div>
<div role="tabpanel" class="tab-pane" id="tab3"></div>
</div><!-- tab-content -->
Javascript:
var url = window.location.href;
if (url.indexOf("#") > 0){
var activeTab = url.substring(url.indexOf("#") + 1);
$('.nav[role="tablist"] a[href="#'+activeTab+'"]').tab('show');
}
//tabs
//ajax tab
$('#utabs a').click(function (e) {
e.preventDefault();
var url = $(this).attr("data-url");
var href = this.hash;
var pane = $(this);
// ajax load from data-url
$(href).load(url,function(result){
pane.tab('show');
});
});
var hash = window.location.hash;
// load first tab content
if (hash) {//if hash detected then reload the content
console.log(hash+` detected`);
$(hash).load($('.active a').attr("data-url"),function(result){
$('.active a').tab('show');//Current tab not load here!
});
} else {//if no hash then load with default tab
console.log(`no hash!!`)
window.location.href +='#tab1';
location.reload();
}
But there’re 2 problems:
- Page keep reloading because it detects the hash in url
- The content is not load into the tab according to the hash.
1