Materialize tabs persist active tab on page refresh - javascript

I am building a single page application using vue.js with materialize and I have a navbar with tabs to navigate to different pages on my website. Materialize's tabs has an active property that displays which tab is currently selected. Every thing this far works perfectly.
This is materialize's tabs reference
The Issue
If you refresh the web page the tabs active property 'resets' to its default position. So I am trying to figure out how to persist the state of the navbar's active property and then reassign it to router-link.
My Code
<ul id="tabs" class="tabs tabs-transparent" :class="{ 'navbar--color': !changeNavColor }">
<li class="tab" id="home">
<router-link
id="home"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="/"
>Home</router-link>
</li>
<li class="tab" id="services">
<router-link
id="services"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Services"
>Service</router-link>
</li>
<li class="tab" id="Preapproved">
<router-link
id="Preapproved"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="PreApproved"
>Get Pre-Approved</router-link>
</li>
<li class="tab">
<router-link
id="cars"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Cars"
>inventory</router-link>
</li>
<li class="tab">
<router-link
id="testimonials"
class="link"
:class="{ 'navbar--color': !changeNavColor }"
to="Testimonials"
>Testimonals</router-link>
</li>
</ul>
if (localStorage.currentTab) {
this.currentTab = localStorage.currentTab;
var activeTab = document.getElementById(this.currentTab);
activeTab.classList.add("active");
console.log("saved");
}
$(document).ready(function() {
$("a").click(function(event) {
this.currentTab = event.target.id;
console.log(this.currentTab);
});
});
$(document).ready(function() {
$(".tabs").tabs();
});
window.addEventListener("scroll", this.onScroll);
},
beforeDestroy() {
window.removeEventListener("scroll", this.onScroll);
},
watch: {
currentTab(newTab) {
console.log("watch");
localStorage.currentTab = this.currentTab;
}
}
any help is appreciated

So I think you can use hash mechanism by using window.location.hash. You can put the data-toggle attribute in every tag anchor. And just check for location.hash !== ''
But the more Vue way would be through client side storage. Check the link its from vue docs. Although it is for the input field but you will get the idea of how to persist info by keeping a reference in client storage and on reload getting your desired state from there onward. Hope it helps.

Remove the indicator that is nested inside the first li, and the navigation works fine.
<ul id="tabs" class="tabs tabs-transparent">
<li id="tab" class="tab">
Home
<li class="indicator"></li> <!-- THIS RANDOM NESTED INDICATOR IS THE ISSUE -->
</li>
<li id="tab" class="tab">
Service
</li>
<li id="tab" class="tab">
Get Pre-Approved
</li>
<li id="tab" class="tab">
inventory
</li>
<li class="indicator" style="right: 488px; left: 0px;"></li> <!-- CORRECT INDICATOR, AUTOMATICALLY GENERATED BY MATERIALIZE -->
</ul>

This is how I ended up implementing this. First all of your router-links or <a> have to have unique id's
mounted() {
if (localStorage.currentTab) {
this.currentTab = localStorage.currentTab;
var element = document.querySelector(this.currentTab);
element.classList.add("active");
}
$(document).ready(function() {
$(".tabs").tabs();
$("a").click(function(event) {
this.currentTab = "#" + event.target.id;
localStorage.currentTab = this.currentTab;
});
});
},
watch: {
currentTab(newTab) {
localStorage.currentTab = this.currentTab;
}
}

Related

Is it possible to add links to bootstrap 4 nav-pills tab-panel from a different page?

I have a service page that using bootstrap 4's pills .nav-pills navigation (this is not the main navigation navbar), which is working very well. My challenge is that i want to be able to click on a link on the home page that should open the targeted tab-panel on the service page. Haven't been able to find a way for almost a week now. How can i achieve this?
Service.html
<div class="nav flex-column nav-pills col-md-3" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<ul class="list-group list-unstyled">
<li class="nav-item">
<a class="nav-link list-group-item" id="v-pills-manpower-tab" data-toggle="pill" href="#v-pills-manpower" role="tab" aria-controls="v-pills-manpower" aria-selected="false">Manpower Supply</a>
</li>
</ul>
</div>
<div class="tab-content col-md-8" id="v-pills-tabContent">
<div class="tab-pane fade" id="v-pills-manpower" role="tabpanel" aria-labelledby="v-pills-manpower-tab">
<h5>Man Power Supply</h5>
</div>
Home.html
<a href="services.html#v-pills-manpower" data-toggle="tab" >
My code in home.html doesn't work but that's one of my many attempts.
On the home page, configure data attributes to help. I've added data-tab-name to the anchor and it defines the desired, selected tab for the service page.
When the page loads, it re-configures the onclick of the link so that the tab name can be stored in localStorage before redirecting the user to the service page.
Home.html
<a href="services.html" data-tab-name="v-pills-manpower" data-toggle="tab" >
<script type="text/javascript">
window.onload = function() {
document.querySelectorAll('[data-toggle="tab"]').forEach(function(item, index){
item.addEventListener('click', function(e){
e.preventDefault();
localStorage.selectedTabName = item.getAttribute('data-tab-name');
window.location.href = item.href;
});
});
};
</script>
When the service page loads, the javascript looks for the saved tab name in localStorage, identifies that tab and then makes it the active tab by applying the "active" class to the appropriate element.
Service.html
<script type="text/javascript">
window.onload = function() {
document.querySelectorAll('.nav-link').forEach(function(item, index){
var isActive = (item.className.indexOf('active')>-1);
if (item.id==localStorage.selectedTabName) {
if (!isActive) {
item.className += ' active';
}
item.setAttribute('aria-selected', 'true');
} else {
item.setAttribute('aria-selected', 'false');
if (isActive) {
item.className = item.className.replace('active', '');
}
}
});
};
</script>

jQuery Tabs, multiple tabs with just ONE panel

I'm working on a custom solution, so I thought I would ask the community if anyone has use jQuery Tabs for this purpose before.
The idea is this: I have one main panel, a form with inputs. There are multiple tabs which basically identify different records. All the records will use this form, thats why I just want to load it once, instead of for each tab.
I put a basic example of the direction I want to go. As you can see there are 3 tabs but only one panel. I want to dynamically load content into the_input depending on which tab I click. SO i don't even want to switch the panel, just the selected tab on each click.
I was thinking I need to catch the beforeActivate (http://api.jqueryui.com/tabs/#event-beforeActivate) event, identify which tab was selected, and dynamically alter the 1 visual panel accordingly.
The code isn't really working
jQuery(function($){
$("#tabs").tabs({
beforeActivate(event, ui) {
$('#msg').append('<p>'+ui.newPanel+'</p>');
//I figure what I want to do here is catch the ID of the selected tab, and use that to dynamically load content to the tab.
}
});
function fill_input(selector){
if ( selector == 1 ) {
$('#the_input').val(1);
}else if ( selector == 2 ) {
$('#the_input').val(2);
}else{
$('#the_input').val();
}
}
})
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<div id="tabs">
<ul>
<li>New</li>
<li>record 1</li>
<li>record 2</li>
</ul>
<div id="bol_new">
<form>
<input id="the_input">
</form>
</div>
</div>
<div id="msg">
</div>
You could set the href for each hyperlink to bol_new as under
<ul>
<li>New</li>
<li>record 1</li>
<li>record 2</li>
</ul>
This will set the panel for each tab to the same div with id="bol_new"
Test: https://plnkr.co/edit/EGtCnmNr0c28AaT647SP?p=preview
I would advise just mocking up the tabs with CSS. You can then manipulate the form as needed.
Working example: https://jsfiddle.net/Twisty/j63uvk4q/
HTML
<div id="tabs" class="ui-tabs ui-corner-all ui-widget ui-widget-content">
<ul class="ui-tabs-nav ui-corner-all ui-helper-reset ui-helper-clearfix ui-widget-header">
<li class="ui-tabs-tab ui-corner-top ui-state-default ui-tab ui-tabs-active ui-state-active">
New
</li>
<li class="ui-tabs-tab ui-corner-top ui-state-default ui-tab">
Record 1
</li>
<li class="ui-tabs-tab ui-corner-top ui-state-default ui-tab">
Record 2
</li>
</ul>
<div id="bol_new" class="ui-tabs-panel ui-corner-bottom ui-widget-content">
<form>
Record:
<input id="the_input">
</form>
</div>
</div>
<div id="msg">
</div>
JavaScript
var myData = {
records: {
bol_1: "Homer Simpson",
bol_2: "Marge Simpson"
}
}
$(function() {
$("#tabs .ui-tabs-nav li").click(function(e) {
e.preventDefault();
$("#tabs li.ui-state-active").toggleClass("ui-tabs-active ui-state-active");
$(e.target).parent().addClass("ui-tabs-active ui-state-active");
var id = $(e.target).attr("href").substring(1);
$("#the_input").val(myData.records[id]);
});
$("#tabs .ui-tabs-nav .ui-tabs-tab").hover(function(e) {
$(this).toggleClass("ui-state-hover");
}, function(e) {
$(this).toggleClass("ui-state-hover");
});
});

Need an element's parent index using jquery or javascript

I have three <ul>s that expand when their buttons are clicked. Not all three <ul>s will show up - only when there is a notification to show. I hard-coded the values for now, but I can instantiate them on an as-needed basis.
Right now, they cover each other when they expand. I would like the others to move when a list is expanded so they don't cover each other. I was thinking of getting the index of the one whose button is clicked and then resetting the bottom style of the others. I need to get the index of the <ul> parent of the button that was clicked, probably using jQuery but straight JavaScript is fine as well. Can anyone help?
Here is my code:
<div id="NotificationDiv">
<ul id="noticeLead" class="notification_base notification_Lead"><button id="notification_button">Lead Notice</button>
<div>
<li id="urlLead" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Lead #1</a>
</li>
<li id="urlLead" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Lead #2</a>
</li>
</div>
</ul>
<ul id="noticeTask" class="notification_base notification_Task"><button id="notification_button">Task Notice</button>
<div>
<li id="urlTask" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Task #5</a>
</li>
<li id="urlTask" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Task #6</a>
</li>
<div>
</ul>
<ul id="noticePolicy" class="notification_base notification_Policy"><button id="notification_button">Policy Notice</button>
<div>
<li id="urlPolicy" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Policy #3</a>
</li>
<li id="urlPolicy" class="notification_urlNotice notification_notice">
<a target="_blank" >Check Policy #4</a>
</li>
</div>
</ul>
</div>
And in the $(document).ready, I have:
$('.notification_base').on('click', 'button', function(){
$(this).closest('.notification_base').find('.notification_urlNotice').slideToggle();
});
Try this:
var myParentId; //Here you'll store the id of the clicked element
$('.notification_base').on('click', 'button', function(){
$(this).closest('.notification_base').find('.notification_urlNotice').slideToggle();
myParentId = $(this).attr("id");
});
Thank you everyone for your input. I changed my structure to a table assigning .parent class to the header row and .child class to the data row and put this code in the jQuery ready function and it works great.
function getChildren($row) {
var children = [];
while($row.next().hasClass('child')) {
children.push($row.next());
$row = $row.next();
}
return children;
}
$('.parent').on('click', function() {
var children = getChildren($(this));
$.each(children, function() {
$(this).toggle();
})
});

update sidebar main-menu and sub-menu class based on url

I've asked this question here but another problem came up so I decided to keep the old one for reference purposes. Old question here.
The old question was just about updating the class of a main-menu based on the url but now things have changed. I will provide the new sidebar below.
Sidebar without any active class yet
<div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul class="sidebar-menu">
<li class="sub-menu">
<a class="" href="panel-admin.php">
<i class="icon-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-calendar"></i>
<span>Scheduling</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
<li><a class="" href="admin-esl.php">ESL Local</a></li>
<li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
It would look like this:
Dashboard
Scheduling
--> Foreign Languages
--> ESL Local
--> Summer Workshops
As you can see Scheduling has a sub-menu.
Then how it would look like if I am on the dashboard. The sidebar would look like this
<div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul class="sidebar-menu">
<li class="sub-menu [active]"> //without the []
<a class="" href="panel-admin.php">
<i class="icon-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-calendar"></i>
<span>Scheduling</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
<li><a class="" href="admin-esl.php">ESL Local</a></li>
<li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
So the Dashboard would be highlighted in this scenario
And how it would look like if Im on any of the sub-menu under Scheduling
<div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul class="sidebar-menu">
<li class="sub-menu">
<a class="" href="panel-admin.php">
<i class="icon-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu [active]">
<a href="javascript:;" class="">
<i class="icon-calendar"></i>
<span>Scheduling</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li [class="active"]><a class="" href="admin-foreign.php">Foreign Languages</a></li>
<li><a class="" href="admin-esl.php">ESL Local</a></li>
<li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
Since I am in the Foreign Languages section. The main header Scheduling and this Foreign Langauges would be active but different class. The active class of Scheduling is sub-menu active while Foreign Languages would just have active only.
And javascript that I've tried no longer applies here since it only handles menus without any dropdown. And it didn't work anyway
Old javascript
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
//alert($('ul a').length);
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
}
//alert(this.href);
});
});
</script>
The goal here is to put a "active" class to the section of the sidebar based on the url the user is in. I've just include('sidebar.php') this sidebar so I would only change this file rather than put a sidebar in each php page file. But then the main heading and the dropdown menu has different active classes.
Found the solution with the help of gecco. The javascript is below:
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$(this).parent().closest("li").addClass('active'); //added this line to include the parent
$(this).parent().parent().closest("li").addClass('active');
}
});
});
</script>
I was already halfway with using php to do this HAHAHAHA. if current_url = db_page_url then put echo class=active. HAHAHA.
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$(this).parent().parent().closest("li").addClass('active2');
}
});
});
</script>
The only change I have done here is adding another line to your JS
$(this).parent().parent().closest("li").addClass('active2');
And here is my style sheet
.active2 > a{
color:red; //what ever the styles you want
}
OR
You can do it without a style
jQuery(function($) {
var path = window.location.href;
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$( this ).parent().parent().closest("li").addClass('active2');
$('.active2 a:first').addClass('active'); //add the active class to the parent node
}
});
});

Meteor: Change the class of link on click

Template:
<template name="header">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item {{active}}" href="{{pathFor 'homePage'}}">Home</a>
{{#if currentUser}}
<a class="blog-nav-item {{active}}" href="#">{{Meteor.userId}}</a>
{{else}}
<a class="blog-nav-item {{active}}" href="{{pathFor 'loginPage'}}">Login</a>
<a class="blog-nav-item {{active}}" href="{{pathFor 'signUpPage'}}">Sign Up</a>
{{/if}}
<a class="blog-nav-item {{active}}" href="#">About</a>
</nav>
</div>
</div>
</template>
header.js
Template.header.events({
'click a': function(e) {
e.preventDefault();
this.active?"active":"";
}
});
I just want to make set click link's class as active. Clicked link class should look like class="blog-nav-item active".
The example below relies on iron-router and presents a reactive approach for adding the active class
First should modify the template to be:
<a class="blog-nav-item {{active 'homePage'}}" href="{{pathFor 'homePage'}}">Home</a>
And then the appropriate helper for it should be:
Template.name.helpers({
active: function(routeName) {
var curRoute = Router.current().route;
return curRoute.name === routeName ? 'active' : '';
}
});
Edit v1.0+
As of iron-router 1.0, A route's name is now accessible at
route.getName() (previously it was route.name).
In particular, you'll need to write return
curRoute.getName() === routeName ? 'active' : '';
Thank you #jrbedard for the notification
I guess this would be the "Meteor way" you wanted:
<template name="menu">
<ul>
<li class="{{#if isCurrentPage 'pageA'}}active{{/if}}">
Page A
</li>
<li class="{{#if isCurrentPage 'pageB'}}active{{/if}}">
Page B
</li>
<li class="{{#if isCurrentPage 'pageC'}}active{{/if}}">
Page C
</li>
</ul>
</template>
Router.onBeforeAction(function(){
Session.set('currentRouteName', Router.current().route.name)
})
Template.menu.helpers({
isCurrentPage: function(pageName){
return Session.equals('currentRouteName', pageName)
}
})
Router.current().route.name do evaluate to the current page name in the latest version of iron router, but I don't know if that's part of the public API one should use.
EDIT
Router.current() is apparently reactive, so all JavaScript code you need is the following:
Template.menu.helpers({
isCurrentPage: function(pageName){
return Router.current().route.name == pageName
}
})
You can solve it with JavaScript only:
Template.header.events({
'click .blog-nav-item': function(event, template){
// Remove the class 'active' from potentially current active link.
var activeLink = template.find('.blog-nav-item')
if(activeLink){
activeLink.classList.remove('active')
}
// Add the class 'active' to the clicked link.
event.currentTarget.classList.add('active')
}
})

Categories