Jquery Tab should remain unchanged after refresh - javascript

I am new to Jquery. I am facing a problem with tab implementation. When I refresh the page I am getting redirected to the intial set tab.
$(function() {
var indicator = $('#indicator'),
indicatorHalfWidth = indicator.width()/2,
lis = $('#tabs').children('li');
$("#tabs").tabs("#content section", {
effect: 'fade',
fadeOutSpeed: 0,
fadeInSpeed: 400,
onBeforeClick: function(event, index) {
var li = lis.eq(index),
newPos = li.position().left + (li.width()/2) - indicatorHalfWidth;
indicator.stop(true).animate({ left: newPos }, 600, 'easeInOutExpo');
}
});
});
This is HTML VIEW :
<nav>
<ul id="tabs">
<li><a class "current" t" href="#">Change Password</a></li>
<li>Update Your Profile</li>
</ul>
<span id="indicator"></span>
</nav>
<div id="content">
<section>
<!--content1 -->
</section>
<section>
<!--content2-->
</section>
</div>

You can do this in several ways. Here are two ways to do:
You can use hash tags that are well explained in below post
Can I keep on same jQuery tab on page refresh or when I have navigated away from the page?
Initialize a tabs with the cookie option specified.
$( "#tabs" ).tabs({ cookie: { expires: 30 } });

Related

How to load a NavBar in the collapsed state when it goes vertical on a small screen

I am new to bootstrap and jquery and javascript and I am working on a website and I am down to one issue . . . I need the navbar at the top to load in a collapsed state on an Extra Small screen. Right now, the bar goes vertical on an XS screen, but I want it to load in the collapsed state so that the user has to click the "three bar icon" on the right to load the page. No matter what I do, I cannot get the navbar to load correctly. If I load it collapsed on the small screen, it becomes invisible on a large screen. I have been working on this for 2 days now. I know it is something simple, but I just cannot figure it out. Can someone else please help.
Here is the relevant code …
<body id="page-top" data-spy="scroll" data-target="#nav-target">
<header id="header">
<!-- Navigation
================================================== -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<ul class="nav navbar-nav">
<li>Watch It Outside</li>
<li id="drop"></li>
<li id="drop1">Home</li>
<li id="drop2">City Of Boston News</li>
<li id="drop3">Boston Public Gardens</li>
<li id="drop4">Film Information</li>
<li id="drop5">Registration</li>
</ul>
</nav>
</header>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Javascript and Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
// Scrollspy fluide
$(function () {
$('li>a').on('click', function (e) {
var hash = this.hash;
$('html, body').animate({
scrollTop: $(this.hash).offset().top
}, 1000, function () {
window.location.hash = hash;
});
});
});
</script>
<script>
$(function() {
$('#drop').click(function() {
$('#drop1').collapse('toggle');
$('#drop2').collapse('toggle');
$('#drop3').collapse('toggle');
$('#drop4').collapse('toggle');
$('#drop5').collapse('toggle');
});
$('#drop1').click(function() {
$('#drop1').collapse('toggle');
$('#drop2').collapse('toggle');
$('#drop3').collapse('toggle');
$('#drop4').collapse('toggle');
$('#drop5').collapse('toggle');
});
$('#drop4').click(function() {
$('#drop1').collapse('toggle');
$('#drop2').collapse('toggle');
$('#drop3').collapse('toggle');
$('#drop4').collapse('toggle');
$('#drop5').collapse('toggle');
});
$('#drop5').click(function() {
$('#drop1').collapse('toggle');
$('#drop2').collapse('toggle');
$('#drop3').collapse('toggle');
$('#drop4').collapse('toggle');
$('#drop5').collapse('toggle');
});
});
</script>
I am also getting a weird error that has recently popped up in the site where I now have to click a link twice to get it to close the first time. From there, every click toggles it collapsed and expanded, but the first one takes 2 clicks to collapse the navbar. (I don't know what I changed to cause this as it didn't start out that way)
Try something like
if (device.width < 800) {
$("nav").addClass("collapsed");
}

Dynamic One Page site that hides all sections except first child of each parent

So I have a one page site that when a user clicks the navigation it shows that div associated with the ID in the anchor and hides all the other divs. Got that working ok.
However, I have sub sections within those divs.They are working ok except the first sub section child is not showing up for each page(parent div).
For example if I'm on the 'Resume' and click 'Work timeline', and then hit 'Projects' it hides the sub section of the 'Project' page due to it being clicked on the 'Resume'.
Is there something I can do to override when the users go to another page(div) it overrides what happen on the other page(div)
Any help would be really appreciated.
DEMO:https://www.kevinhenriquez.com/projects/full/
HTML Code:
<nav>
<ul>
<li>Home</li>
<li>Projects</li>
<li>Resume</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<section id="cover" class="page-section">
........
</section>
<section id="projects" class="page-section">
<section id="portfolio-sites" class="sub-section">
..................
</section>
<section id="client-sites" class="sub-section">
................................
</section>
<div class="page-section-nav">
<ul>
<li>Portfolio</li>
<li>Client</li>
<li>School</li>
</ul>
</div>
</section>
<section id="resume" class="page-section">
<section id="work-timeline" class="sub-section">
..................
</section>
<section id="technologies" class="sub-section">
................................
</section>
<div class="page-section-nav">
<ul>
<li>Timeline</li>
<li>Technologies</li>
</ul>
</div>
</section>
Javascript Code:
$(document).ready(function () {
var pageSection = $('.page-section');
var subSection = $('.sub-section');
var navLink = $('nav ul li a');
var subLink = $('.page-section-nav li a');
var sectionToggle = {
nav:
function (event) {
pageSection.hide();
$(this.getAttribute('href')).show();
navLink.removeClass('highlight');
$(this).addClass('highlight');
$('#nav-trigger').prop( "checked", false);
},
sub:
function (event) {
subSection.hide();
$(this.getAttribute('href')).show();
subLink.removeClass('highlight');
$(this).addClass('highlight');
}
};
pageSection.not(":first").hide();
subSection.not(":first").hide();
$("a[data-action]").on("click", function (event) {
var link = $(this),
action = link.data("action");
event.preventDefault();
if( typeof sectionToggle[action] === "function" ) {
sectionToggle[action].call(this, event);
}
});
});
It could look like this:
function hideNotFirstChild(ancestor){
let allchilds=ancestor.children;
for each(allchilds as child ){
if(child!=ancestor.firstchild){
child.hide();
}
}
}
Applied function to all the nodes of the pages because you've to know ancestor in order to know who's the first child.
I barely use jQuery here (only the .hide() method) because it won't change much.
I was able to get it to work by adding on the nav toggle function :
$('.sub-section:first-child).show();
and removing:
subSection.not("first").hide();
Thanks for the help. This is what I did:
var sectionToggle = {
nav:
function (event) {
pageSection.hide();
$(this.getAttribute('href')).show();
$('.sub-section:first-child').show();
navLink.removeClass('highlight');
$(this).addClass('highlight');
$('#nav-trigger').prop( "checked", false);
},
sub:
function (event) {
subSection.hide();
$(this.getAttribute('href')).show();
subLink.removeClass('highlight');
$(this).addClass('highlight');
}
};

fullCalendar + Bootstrap tabs glitch: not rendering events until resizing browser

I'm having a strange problem when using fullCalendar along with Bootstrap, having the calendar rendered within a non active tab pane. I'm using the AgendaView, and it's initially displayed with the column for hours with just 1 pixel of width assigned to it.
It's placed within the "Operarios" tab.
But the biggest problem is when rendering the events. They all are displayed compressed at the top of the timetable.
Then if I resize the browser, or the frame, if I'm using Chrome Dev Tools or similar, then it's automatically re-rendered and it's correctly displayed.
You may check it out here:
https://codepen.io/luisapuyen/pen/RYXZPr
The HTML:
+ function($) {
$(function() {
var opcionesCalendario = {
selectable: true,
unselectAuto: false,
locale: 'es',
defaultView: 'agendaWeek',
header: false,
footer: false,
height: 400,
columnHeaderFormat: 'ddd',
eventColor: '#ffdc11',
views: {
agenda: { // name of view
titleFormat: '',
allDaySlot: false,
slotEventOverlap: false,
minTime: '07:00:00',
maxTime: '23:00:00',
slotDuration: '01:00:00',
footer: false
}
},
select: function(startDate, endDate, event, view) {
var evento = [{
start: startDate,
end: endDate
}];
$calendario.fullCalendar('addEventSource', evento);
console.log('selected ' + startDate.format() + ' to ' + endDate.format(), view);
}
},
$body = $('body'),
$tabs = $body.find('#tabs-panel-autovisita'),
$forms = $body.find('form'),
$operariosSel = $forms.filter('[name="operarios"]').find('select[name="operarios"]')
$calendario = $body.find('.calendario').fullCalendar(opcionesCalendario);
// INICIO
init();
function init() {
mostrarRangos();
$operariosSel.on('change', function() {
mostrarRangos();
});
}
function obtenerDiaInicial() {
return moment().isoWeekday(1);
}
function mostrarRangosOperarioCalendario(rangos) {
var diaInicialMoment = obtenerDiaInicial(),
diaMoment,
diaSemana,
eventos = [];
$.each(rangos, function(i, rango) {
diaSemana = +rango.dia_semana - 1;
diaMoment = diaInicialMoment.clone().add(diaSemana, 'days');
eventos.push({
start: moment(diaMoment.format('YYYY-MM-DD') + 'T' + rango.hora_inicio),
end: moment(diaMoment.format('YYYY-MM-DD') + 'T' + rango.hora_fin)
});
});
$calendario.fullCalendar('removeEvents')
$calendario.fullCalendar('renderEvents', eventos);
}
function obtenerRangosOperario(idOp) {
// ajax request that returns:
var res = JSON.parse('{"rangos":[{"dia_semana":"2","hora_inicio":"11:00:00","hora_fin":"13:00:00"},{"dia_semana":"1","hora_inicio":"09:00:00","hora_fin":"14:00:00"},{"dia_semana":"4","hora_inicio":"10:00:00","hora_fin":"17:00:00"},{"dia_semana":"3","hora_inicio":"14:00:00","hora_fin":"18:00:00"}],"ok":"1"}');
mostrarRangosOperarioCalendario(res.rangos);
}
function mostrarRangos() {
var idOp = +$operariosSel.val();
obtenerRangosOperario(idOp);
}
});
}(jQuery);
<div class="container">
<div class="row">
<div class="col-sm">
<h3>Configuración Auto-visitas</h3>
<nav>
<div class="nav nav-tabs" id="tabs-autovisita" role="tablist">
<a class="nav-item nav-link active" data-toggle="tab" role="tab" href="#general">General</a>
<a class="nav-item nav-link" data-toggle="tab" role="tab" href="#operarios">Operarios</a>
<a class="nav-item nav-link" data-toggle="tab" role="tab" href="#companyias">Compañías</a>
</div>
</nav>
<div class="tab-content">
<div class="tab-pane show active" id="general" role="tabpanel">
</div>
<div class="tab-pane" id="operarios" role="tabpanel">
<form method="post" name="operarios">
<div class="form-group">
<label>Operarios</label>
<select name="operarios" class="form-control dato">
<option value="0">Todos</option>
</select>
</div>
<div class="calendario dato"></div>
<button type="submit" class="btn btn-primary guardar">Guardar</button>
</form>
</div>
<div class="tab-pane" id="companyias" role="tabpanel">
</div>
</div>
</div>
</div>
</div>
I'm not sure whether it's a bug produced when using fullCalendar and Bootstrap together.
The only way I've found it works is having the calendar in the active pane at first. But since semantically it corresponds to the first tab to be the one which must be active, I'd like to find a better solution.
Any ideas?
Fullcalendar is failing to retrieve sizes and dimensions of elements because they are set to display: none. You can see that from computed styles on page refresh. Your events are supposed to have a top and bottom set but instead they receive a value of 0 for both.
This is why your events are all "displayed compressed at the top of the timetable".
A simple fix is to listen for a tab change event and re-render fullcalendar.
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
$calendario.fullCalendar( 'rerenderEvents' );
});
Here's a functioning example.
In React fullcalendar (version 5), I could not call the render or rerender method.
FullCalendar automatically updates size if it listens to window resize events. I just the trigger resize event when the calendar tab is visible with some delay.
Refer following code
setTimeout(() => window.dispatchEvent(new Event('resize')), 500)

Add class to elements with same id on click, remember class on page refresh

I'm trying to build a page that contains multiple inner pages - a front page that displays by default, and child pages which display when relevant links on the front page are clicked.
What I am trying to achieve is that when a page-link element is clicked, the class active-page is added to the inner page with the same id, and the intro section has a class off-canvas added, & the active page is set in localStorage - so that if for any reason the page is refreshed, the last page that was being viewed is displayed.
Alternatively, when a lnk-rtn-home element is clicked, the current inner-page should lose the active page class while front-page loses its off-canvas class. Likewise, this should update the localStorage.
The HTML structure is as follows:
<body>
<div class="container">
<section id="intro" class="front-page row">
{{ content }}
<a data-id='about-me' class='page-link'>About Me</a>
{{ more content }}
<a data-id='contact' class='page-link'>Contact</a>
</section>
<section id="about-me" class="inner-page row">
{{ content }}
<a class='lnk-rtn-home'>Return Home</a>
</section>
<section id="contact" class="inner-page row">
{{ content }}
<a class='lnk-rtn-home'>Return Home</a>
</section>
</div>
</body>
The current JS stands at
$(document).ready(function(){
var activePageSet = localStorage.getItem('current-page');
// Check if an active page has been set
if (activePageSet) {
$('#' + activePageSet).addClass('active-page');
$('#intro').addClass('off-canvas');
}
// Links to inner pages
$('.page-link').click(function() {
var currentPage = $(this).data("id");
$('#' + currentPage).addClass("active-page");
$('#intro').addClass('off-canvas');
localStorage.setItem('current-page', JSON.stringify(currentPage));
});
// Link to return home
$('.lnk-rtn-home').click(function() {
if ($('.inner-page').hasClass('active-page')) {
$(this).removeClass('active-page');
localStorage.removeItem('current-page');
}
$('#intro').removeClass('off-canvas');
});
});
No amount of playing around with this has got it working, and at this stage I'm lost as to how to achieve it.
This problem can be solved with using only 1 class. You have made your code more complex by using 2 classes. I replaced .active-page and .off-canvas with the class .hidden. This gives a simpler code to follow.
var activePageSet = null; //localStorage.getItem('current-page');
//not able to do localStorage in snippet
// Check if an active page has been set
if (activePageSet) {
$('#' + activePageSet).removeClass('hidden');
$('#intro').addClass('hidden');
}
// Links to inner pages
$('.page-link').click(function() {
var activePageId = $(this).data("id");
$('#' + activePageId).removeClass("hidden");
$('#intro').addClass('hidden');
//localStorage.setItem('current-page', JSON.stringify(activePageId));
});
// Link to return home
$('.lnk-rtn-home').click(function() {
var activePage = $(this).parent();
activePage.addClass('hidden');
$('#intro').removeClass('hidden');
//localStorage.removeItem('current-page');
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<section id="intro" class="front-page row ">
{{ intro content }}
<a data-id='about-me' class='page-link'>About Me</a>
{{ more content }}
<a data-id='contact' class='page-link'>Contact</a>
</section>
<section id="about-me" class="inner-page row hidden">
{{ about content }}
<a class='lnk-rtn-home'>Return Home</a>
</section>
<section id="contact" class="inner-page row hidden">
{{ contact content }}
<a class='lnk-rtn-home'>Return Home</a>
</section>
</div>
you just need to select right element for hasClass condition.
You can use a parent, like this:
$(document).ready(function(){
// Links to inner pages
$('.page-link').click(function() {
var currentPage = $(this).data("id");
$('#' + currentPage).addClass("active-page");
$('#intro').addClass('off-canvas');
//localStorage.setItem('current-page', JSON.stringify(currentPage));
});
// Link to return home
$('.lnk-rtn-home').click(function() {
var jqSection = $(this).parent();
if (jqSection.hasClass('active-page')) {
jqSection.removeClass('active-page');
localStorage.removeItem('current-page');
}
$('#intro').removeClass('off-canvas');
});
});
Here is an example: https://plnkr.co/edit/xfgHpWdDpnDTyjLYYrGd?p=preview

Response menu not collapsing and reloads page

At http://www.dentalo.se/contact it is using a responsive menu for mobile devices.
When clicking on the menu button it collapses the menu but the same time reloads the page.
Can anyone tell my why and how I can fix it?
Thanks for the time you are taking to help me.
Edit
HTML
<div class="container">
<div class="navbar-header">
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<button type="button" class="navbar-toggle btn navbar-btn" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN LOGO (you can use logo image instead of text)-->
<a class="navbar-brand logo-v1" href="/">
<img src="/assets/img/logo_blue.png" id="logoimg" alt="">
</a>
<!-- END LOGO -->
</div>
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="MainMenuHome">Start</li>
<li class="dropdown" id="MainMenuDentalo">
<a class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="0" data-close-others="false" href="#">
Dentalo
<i class="icon-angle-down"></i>
</a>
<ul class="dropdown-menu">
<li id="SubMenuAbout">Om Dentalo</li>
<li id="SubMenuJob">Lediga tjänster</li>
<li id="SubMenuConnect">Anslut</li>
</ul>
</li>
<li id="MainMenuLogIn">Logga in</li>
<li id="MainMenuContact">Kontakt</li>
<li class="menu-search">
<span class="sep"></span>
<i class="icon-search search-btn"></i>
<div class="search-box">
<form action="#">
<div class="input-group input-large">
<asp:TextBox runat="server" placeholder="Sök..." CssClass="form-control" ID="textBoxSearch"></asp:TextBox>
<span class="input-group-btn">
<asp:Button runat="server" CssClass="btn theme-btn" ID="ButtonSearch" OnClick="ButtonSearch_Click" Text="Sök" />
</span>
</div>
</form>
</div>
</li>
</ul>
</div>
<!-- BEGIN TOP NAVIGATION MENU -->
</div>
JavaScript
/*
* Project: Twitter Bootstrap Hover Dropdown
* Author: Cameron Spear
* Contributors: Mattia Larentis
*
* Dependencies?: Twitter Bootstrap's Dropdown plugin
*
* A simple plugin to enable twitter bootstrap dropdowns to active on hover and provide a nice user experience.
*
* No license, do what you want. I'd love credit or a shoutout, though.
*
* http://cameronspear.com/blog/twitter-bootstrap-dropdown-on-hover-plugin/
*/
;(function($, window, undefined) {
// outside the scope of the jQuery plugin to
// keep track of all dropdowns
var $allDropdowns = $();
// if instantlyCloseOthers is true, then it will instantly
// shut other nav items when a new one is hovered over
$.fn.dropdownHover = function(options) {
// the element we really care about
// is the dropdown-toggle's parent
$allDropdowns = $allDropdowns.add(this.parent());
return this.each(function() {
var $this = $(this),
$parent = $this.parent(),
defaults = {
delay: 500,
instantlyCloseOthers: true
},
data = {
delay: $(this).data('delay'),
instantlyCloseOthers: $(this).data('close-others')
},
settings = $.extend(true, {}, defaults, options, data),
timeout;
$parent.hover(function(event) {
// so a neighbor can't open the dropdown
if(!$parent.hasClass('open') && !$this.is(event.target)) {
return true;
}
if(shouldHover) {
if(settings.instantlyCloseOthers === true)
$allDropdowns.removeClass('open');
window.clearTimeout(timeout);
$parent.addClass('open');
}
}, function() {
if(shouldHover) {
timeout = window.setTimeout(function() {
$parent.removeClass('open');
}, settings.delay);
}
});
// this helps with button groups!
$this.hover(function() {
if(shouldHover) {
if(settings.instantlyCloseOthers === true)
$allDropdowns.removeClass('open');
window.clearTimeout(timeout);
$parent.addClass('open');
}
});
// handle submenus
$parent.find('.dropdown-submenu').each(function(){
var $this = $(this);
var subTimeout;
$this.hover(function() {
if(shouldHover) {
window.clearTimeout(subTimeout);
$this.children('.dropdown-menu').show();
// always close submenu siblings instantly
$this.siblings().children('.dropdown-menu').hide();
}
}, function() {
var $submenu = $this.children('.dropdown-menu');
if(shouldHover) {
subTimeout = window.setTimeout(function() {
$submenu.hide();
}, settings.delay);
} else {
// emulate Twitter Bootstrap's default behavior
$submenu.hide();
}
});
});
});
};
// helper variables to guess if they are using a mouse
var shouldHover = false,
mouse_info = {
hits: 0,
x: null,
y: null
};
$(document).ready(function() {
// apply dropdownHover to all elements with the data-hover="dropdown" attribute
$('[data-hover="dropdown"]').dropdownHover();
// if the mouse movements are "smooth" or there are more than 20, they probably have a real mouse
$(document).mousemove(function(e){
mouse_info.hits++;
if (mouse_info.hits > 20 || (Math.abs(e.pageX - mouse_info.x) + Math.abs(e.pageY - mouse_info.y)) < 4) {
$(this).unbind(e);
shouldHover = true;
}
else {
mouse_info.x = e.pageX;
mouse_info.y = e.pageY;
}
});
});
// for the submenu to close on delay, we need to override Bootstrap's CSS in this case
var css = '.dropdown-submenu:hover>.dropdown-menu{display:none}';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
$('head')[0].appendChild(style);
})(jQuery, this);
It appears that your button element (navbar-btn) is submitting your form. Try adding type="button" to the button element.
Also in the click event handler you can also try to add e.preventDefault() to your click event handler.
I cant seem to find the JavaScript from the click event of your button so I can help much more. If this does not work, please edit your question to show the relevant HTML and JavaScript sections.

Categories

Resources