focus on the same tab - javascript

I'm using jquery UI to create tabs. Requirement is when i select tab2 or any other tab and reload/refresh the page, focus should be on the selected tab. Please find the fiddle http://jsfiddle.net/CnEUh/500/
I have gone through many online forums but could not get the expected result.
I followed the link Set Jquery ui active tab on page load/reload , but didn't got the result.
Tried the below code :
$(document).ready(function() {
$("#tabs").tabs({active: tabs-2});
// Set active tab on page load
var SelectedTab = tabs-2;
if(tabSelectedId!=""){
$("#tabs").tabs({selected: tabSelectedId});
}
});
Please suggest how can i keep the focus on the selected tab on page reload. My fiddle http://jsfiddle.net/CnEUh/500/

You can accomplish it by using location.href
On click, just add #tab=2 and then on page load, here you can retrieve location.href and choose which tav is selected.

Add jquery.cookie.js library and the following code
$(document).ready(function() {
var $tabs = $( "#tabs" ).tabs({
activate: function(event ,ui){
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
var selectedIndex=parseInt($.cookie('active_tab'));
if(selectedIndex) {
$tabs.tabs({ active: selectedIndex });
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
// set cookie on tab select
});
Or without jquery.cookie.js, pass the active tab index as a parameter
var activeTab;
var $tabs = $("#tabs").tabs({
activate: function (event, ui) {
activeTab = ui.newTab.index();
}
});
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var selectedIndex = parseInt(params.selectedIndex);
if (selectedIndex) {
$tabs.tabs({
active: selectedIndex
});
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
$('#tabs').click(function() {
window.location.href = window.location.href.replace( /[\?#].*|$/, "?selectedIndex="+activeTab );
});
Hopefully it works.
Thanks

Related

Multiple accordions simultaneously open. How to open only 1 JQuery accordion at a time

Currently open accordion is not closing when another opens.
This is the code I used, not sure where I got it wrong.
<script>
$(document).ready(function () {
//each accordion has a text entry and a corresponding image
var accordionEntries = document.querySelectorAll('.accordion-entry');
var accordionImages = document.querySelectorAll('.accordion-image');
for ( var i = 0; i < accordionEntries.length; i++ ) {
accordionEntries[i].dataset.target = 'accordion-image-' + i;
accordionImages[i].classList.add('accordion-image-' + i);
}
//toggles accordion open state
$(document).on('click', '.accordion-header', function () {
if ($(this).is(".accordion-open")) return $(this).removeClass("accordion-open");
var parent = $(this).closest('.accordion-entry, .accordion-image');
if(!parent.hasClass('.accordion-open')){
parent.toggleClass('accordion-open');
} else {
$('.accordion-open').removeClass('accordion-open')
}
$('.' + parent.data('target')).toggleClass('accordion-open')
})
})
</script>
Thanks for everyone's help in trying to answer the question, a colleague eventually helped me solve this. Here is the solution with comments for anyone else's benefit.
<script>
$(document).ready(function () {
var accordionEntries = document.querySelectorAll('.accordion-entry');
var accordionImages = document.querySelectorAll('.accordion-image');
for ( var i = 0; i < accordionEntries.length; i++ ) {
accordionEntries[i].dataset.target = 'accordion-image-' + i;
accordionImages[i].classList.add('accordion-image-' + i);
}
$(document).on('click', '.accordion-header', function () {
// close currently opened accordion
// add class to open clicked accordion
var accordionEntry = $(this).closest('.accordion-entry');
var open = 'accordion-open';
/* If the accordion that was clicked is in open state,
* remove all occurrences of the 'accordion-open' class and DO NOTHING
* AFTER.
*/
if (accordionEntry.hasClass('accordion-open')) {
accordionEntry.removeClass(open);
$('.' + open).removeClass(open);
} else {
/* If the accordion that was clicked is NOT in open state,
* remove all occurrences of the 'accordion-open' class and add 'accordion-open' class
*. to the accordion that was clicked.
*/
accordionEntry.removeClass(open);
$('.'+ open).removeClass(open);
accordionEntry.addClass('accordion-open');
$('.'+ accordionEntry.data['target']).addClass(open)
$('.'+ accordionEntry[0].dataset.target).addClass(open)
}
});
});
</script>

JS popup does't works comparison operator

I have 5 link and mini preview photo and url 3 links its good link opsss and upsss is wrong when i click good link i'm going to new page when i click error link attr href change to adresError and then we have popup This only works for the first time second time click all links have a popup and should have only opsss and upsss
http://jsfiddle.net/3ptktp47/1/
Here is my code :
var nameError = [
"opsss",
"upsss",
];
$(function() {
$('#prev').hide();
$(function() {
var title_link = 'kliknij aby podejżeć';
$(".preview-link a")
.attr({title: title_link})
//.tooltip()
.click(function(){
$('.preview-link a img').css('opacity',1);
var sciezka = $(this).attr("href");
var tytul = $(this).attr("title");
var adres = $(this).text();
//alert(adres);
$(".duzy").attr({ src: sciezka, alt: tytul, style:'cursor:pointer;', href:'http://www.'+ adres,'target':'_blank'});
$('.link').html(adres).attr({href:'http://www.'+ adres,'target':'_blank'});
$('#prev').show();
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.link, .duzy').click(function(event){
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({href:'http://'+ adresError,'target':'_blank'});
});
};
if(adres == 'opsss.com'){
var adresError = 'x4ql.nazwa.pl/'+ nameError[0];
errorDomain();
}else if(adres == 'upsss.com' ){
var adresError = 'x4ql.nazwa.pl/'+ nameError[1];
errorDomain();
}else{
//$('#popup, .popup-bg').fadeOut();
};
$('.cancel, .popup-bg').click(function(event){
$('#popup, .popup-bg').fadeOut();
});
return false;
});
$('.close').click(function(){
$('#prev').hide();
});
$('.link').mouseover(function(){
$(this).css({style: 'color:#000;'});
});
});
});
EDITED:
Ok, I was able to handle your problem.
Your .click() event in the errorDomain() method was firing every time you clicked this square. I managed it to toggle a class on a.duzy element with toggleClass('error') in your if-statement where you check the address.
Inside your click() event, a if-statement is checking if the .duzy element has class named error with hasClass('error') , this has following result -
TRUE- your popup will be displayed
FALSE - nothing happens
I hope my answer is clear enough, but please check out the edited fiddle.
EDITED SOURCE:
Your errorDomain() Method
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.duzy, .link').click(function (event) {
if ($(this).hasClass("error")) {
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({
href: 'http://' + adresError,
'target': '_blank'
});
}
});
}
The if-statements
if (adres == 'opsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[0];
$('a.duzy').toggleClass("error");
errorDomain();
} else if (adres == 'upsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[1];
$('a.duzy').toggleClass("error");
errorDomain();
} else {
$('a.duzy').removeClass("error");
}
Edited fiddle

How can I traverse through cookie and then upon clicking a button change the url depending on values from cookie

I have a cookie dataid giving data as below
"D_2781467,D_2792290,D_2803725,D_2677313,D_2799569,D_2805134,D_2758142,D_2802506,D_2802509,D_2802508,D_2803726,D_2652515"
And in the body we have valies as below
<body class="mycars" data-listing-id="2792290">
And the URL will be like
http://www.abcd.com/c_f_s/D_2792290/xyz.html
What I want is that in this page upon clicking a button , the user is taken to next url as in
http://www.abcd.com/c_f_s/D_2803725
So basically somehow we need to traverse through the cookie and get the index and on pressing the button change the url with the number received from the cookie
You can do it like,
HTML
Next
SCRIPT
$(function(){
var dataArr = ['D_2781467', 'D_2792290', 'D_2803725', 'D_2677313', 'D_2799569',
'D_2805134', 'D_2758142', 'D_2802506', 'D_2802509','D_2802508',
'D_2803726', 'D_2652515'];
var index = 0;
$.cookie('index', 0);
$('#next').on('click', function (e) {
e.preventDefault();
if (index < dataArr.length-1) { // check index length
index++ ;// increment index
} else {
index = 0; // reset index
}
var currentIndex = $.cookie('index'); // get current cookie index from cookie
$.cookie('index', index);
alert('http://www.abcd.com/c_f_s/' + dataArr[currentIndex]);
});
});
You can use cookie plugin
Live Demo
Here is how I would do it (not tested, but this is the basic idea).
using the getCookie function from:
http://www.w3schools.com/js/js_cookies.asp
$('#button').click(function() {
var cook = getCookie('dataid').split(',')
var myId = $('body').eq(0).attr('data-listing-id')
var index = cook.indexOf('D_'+myId)
if (index == -1 || index == cook.length - 1)
return;
document.location = 'http://www.abcd.com/c_f_s/D_'+cook[index+1]
}

How to link to tabs with jtabs?

I added tabs to a section of my page I am working on (stridertechnologies.com/stoutwebsite/products.php)using the steps found at this website: http://code-tricks.com/create-a-simple-html5-tabs-using-jquery/
I want to link to the different tabs from the home page, but I am not sure how to do that outside of anchor names with html and that doesn't work with this, and there aren't any instructions on how to do it on the site.
It seems like there should be something really simple I can add to my javascript to detect which link they clicked on and make it the active tab.
javascript:
;(function($){
$.fn.html5jTabs = function(options){
return this.each(function(index, value){
var obj = $(this),
objFirst = obj.eq(index),
objNotFirst = obj.not(objFirst);
$("#" + objNotFirst.attr("data-toggle")).hide();
$(this).eq(index).addClass("active");
obj.click(function(evt){
toggler = "#" + obj.attr("data-toggle");
togglerRest = $(toggler).parent().find("div");
togglerRest.hide().removeClass("active");
$(toggler).show().addClass("active");
//toggle Active Class on tab buttons
$(this).parent("div").find("a").removeClass("active");
$(this).addClass("active");
return false; //Stop event Bubbling and PreventDefault
});
});
};
}(jQuery));
This answer is from a duplicated question here: https://stackoverflow.com/a/20811416/3123649.
You could pass the tab div id in the url from the link and use that to select.
Home page links from index.html:
tile
metal
Add this javascript to the tab page
<script type="text/javascript">
// To get parameter from url
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$.extend($.expr[':'], {
attrNameStart: function (el, i, props) {
var hasAttribute = false;
$.each(el.attributes, function (i, attr) {
if (attr.name.indexOf(props[3]) !== -1) {
hasAttribute = true;
return false;
}
});
return hasAttribute;
}
});
// deselect tabs and select the tab by id
function focusTab(id) {
$("#tile").hide().removeClass("active");
$("#metal").hide().removeClass("active");
$("#shingle").hide().removeClass("active");
$("#flat").hide().removeClass("active");
$("#custom").hide().removeClass("active");
var toggle = $(id).parent().find("div");
toggle.hide().removeClass("active");
$('a:attrNameStart(data-toggle)').removeClass("active");
var id1 = getParameterByName("tabId");
var toggler = $('*[data-toggle=' + id1 + ']');
$(toggler).addClass("active");
$(id).show().addClass("active");
}
$(function() {
$(".tabs a").html5jTabs();
// Get the tab id from the url
var tabId = "#" + getParameterByName("tabId");
// Focus the tab
focusTab(tabId);
});
</script>
EDIT: Replace the original focusTab function with the edit. Also add the extend function attrNameStart. This should deselect the default active tab.
EDIT2: focusTab had a bug, it should work now
** I looked at your site and my solutions seems to be working for you. One thing I noticed. You initialize the html5jTabs() twice.
Remove the first call at the top
<script type="text/javascript">
$(function() {
$(".tabs a").html5jTabs();
});
</script>
How about something like this? Basically we are taking the value of data-toggle in our buttons, and passing it into the selector for each tab content
JS
$('a[data-toggle]').on('click', function () {
var dataToggle = $(this).data('toggle');
$('.tabContent > div').removeClass('active');
$('.tabContent > div#'+dataToggle+'').addClass('active');
});
working example:
http://jsfiddle.net/whiteb0x/VdeqY/

Jquery remember last selected tab using local storage

i have this jquery code:
<script type="text/javascript">
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
});
</script>
i am trying to make it so the tab is remembered if the page is refreshed by using this code:
<script type="text/javascript">
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
localStorage.selectedTab = $(this).index() + 1;
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
// search for local storage
if (localStorage.selectedTab) {
$(".tabLink:eq(" + (localStorage.selectedTab - 1) + ")").click();
}
});
</script>
HTML:
<div class="tab-box">
View Customer
View Reseller Customer
View Salesman Customer
View Archived Customer
</div>
<div class="tabcontent" id="viewcustomer-1">
content...
</div>.....
it works fine, but the tabs are on multiple pages so if i go to a different page, a different tab is selected as its trying to remember the last selected tab.
how can i make it remember the last selected tab for each page?
localStorage to persist the selection :
$(document).ready(function () {
function activate(tab) {
// switch all tabs off
$(".active").removeClass("active");
// switch this tab on
tab.addClass("active");
// slide all content up
$(".content").slideUp();
// slide this content up
var content_show = tab.attr("title");
$("#" + content_show).slideDown();
}
if (localStorage) { // let's not crash if some user has IE7
var index = parseInt(localStorage['tab'] || '0');
activate($('a.tab').eq(index));
}
// When a link is clicked
$("a.tab").click(function () {
if (localStorage) localStorage['tab'] = $(this).closest('li').index();
activate($(this));
});
});
You could create a map linking URLs to selected tabs, like
tabStorage = {
"page_url_1" : 1,
"page_url_2" : 3
}
You can get the URL of current page using winow.location.
Then to save/retrieve it use JSON.stringify / JSON.parse, because localStorage only keeps key/value pairs, not objects. The key here is 'tabs', the value - a strigified representation of the map.
$(document).ready(function() {
var tabStorage = (localStorage && localStorage.tabs) ? JSON.parse( localStorage.tabs ) : {};
$(".tabLink").click(function(){
tabStorage[ window.location ] = $(".tabLink").index( this );
if(localStorage) {
localStorage.tabs = JSON.stringify( tabStorage );
}
});
if (tabStorage[ window.location ]) {
$(".tabLink").eq( tabStorage[ window.location ] ).trigger('click');
}
});

Categories

Resources