Reputation: 81
Suppose, in my webpage, I have a sidebar menu containing three tabs like: notice, news and events. If I click on any of the tab, corresponding items become visible at a specific place in the page which were kept hidden using display:none property. Coding format is as follows:
<div class="sidenav">
<div class="panel-header-silver">
<h2>Upcoming</h2>
</div>
<div class="sidenav-item sidenav-active" data-tab="notices" >
General Notices
</div>
<div class="sidenav-item " data-tab="News" >
News
</div>
<div class="sidenav-item" data-tab="Events">
Events
</div>
</div>
Now, I want to link to any tab from another page. That means, if I click a link it will activate the news tab (say). Is there any way to achieve this functionality?
Upvotes: 3
Views: 1732
Reputation: 1643
Try using the below code. You need to pass the "data-tab" value of the Element you want to make Active, on button click.
// Page 1.html Script
function activeButton(value) {
window.location.href = '2.html#active=' + value;
}
// Page 2.html Script
$(document).ready(function() {
var activeTab = getUrlParameter('active');
console.log(activeTab);
$(".sidenav").find(`[data-tab='${activeTab}']`).addClass("active");
});
var getUrlParameter = function getUrlParameter(sParam) {
var results = new RegExp('[\?&#]' + sParam + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="sidenav">
<div class="panel-header-silver">
<h2>Upcoming</h2>
</div>
<div class="sidenav-item sidenav-active" data-tab="notices">
General Notices
</div>
<div class="sidenav-item " data-tab="News">
News
</div>
<div class="sidenav-item" data-tab="Events">
Events
</div>
</div>
<div class="container">
<a class="btn btn-primary" href="javascript:activeButton('News')"> Active </a>
</div>
Edit : I have modified the above function to get parameter name in URL using "#" too.
Upvotes: 2