Change URL with javascript - javascript

I have a tab system in HTML that uses the following javascript:
(function() {
var $tabsNav = $('.tabs-nav'),
$tabsNavLis = $tabsNav.children('li'),
$tabContent = $('.tab-content');
$tabContent.hide();
$tabsNavLis.first().addClass('active').show();
$tabContent.first().show();
$tabsNavLis.on('click', function(e) {
var $this = $(this);
$tabsNavLis.removeClass('active');
$this.addClass('active');
$tabContent.hide();
$( $this.find('a').attr('href') ).fadeIn();
e.preventDefault();
});
})();
The HTML Markup is:
<ul class="tabs-nav">
<li class="active">
TAB 1
</li>
<li>
TAB 2
</li>
<li>
TAB 3
</li>
</ul><!-- end .tabs-nav -->
<div class="tabs-container">
<div class="tab-content" id="1">
CONTENT OF TAB 1
</div><!-- end #tab1 -->
<div class="tab-content" id="2">
CONTENT OF TAB 2
</div><!-- end #tab2 -->
<div class="tab-content" id="3">
CONTENT OF TAB 3
</div><!-- end #tab3 -->
The UL are the names of the tabs, when you click one they take you to the content of that tab. As you can see when you click a tab the link is www.thepage.com#tab1 etc but in the adress bar doesnt appear anything. I want to be able to go to thepage.com#tab2 and to show the tab 2, but this isnt working.
I had searched different methods like window.location in javascript or pushstate in html5 posted in this page but I didnt know how to make them function. It will be best to use thepage.com/tab1 and not the hash tag for SEO purposes. I know you can achieve this with the pushstate in html5 like:
window.history.pushState(“object or string”, “Title”, “/new-url”);

If you use the pushstate html5 feature it won't work with IE8 and other older browsers, but if you just want to be able to have ajaxy-history you can use the hash portion of the url. You can modify the hash of the url by using:
window.location.hash="mytabid";
// url will be http://foo.com/#mytabid
Using this inconjuction with the hash change event (you'll probably want to use jQuery or a plugin to handle cross-browser event issues) you can react on the use of the back button or when the page loads by accessing the location.hash property.
window.onhashchange = function(a){
console.log(a); //probably easiest to access the location.hash here.
}

Related

Change page and change URL without refresh and keep content after refresh , like ReactJS website

I've tried to use jQuery's load() function to change/load content without reloading. That works, but the problem is: the URL keeps the same!
Even if i use history.pushState() to change URL, that does not solve the problem. Example:
with the famous window.history.pushState("object or string", "Title", "/new-url");
With that, I am creating a "fake URL" for each page - If I try to enter the website with this changed URL again, i get an error, basically the link does not exist;
If I refresh the page, i lost all Ajax loaded content - I need to keep the content when refresh;
When I click to change Ajax loaded page, keeps putting new links next to the previous one, as in the image sent;
I want to get this result: https://reactjs.org/ - transiting the pages, they do not reload and the link changes, it is updatable and the link works separately - how do i do it?
3) printscreen of my page and its url
Important: index.html, about.html and contact.html are existing files that will load with the jquery function below.
HTML:
<div class="navbar">
<div class="content">
<div class="logo">My logo</div>
<ul class="pages">
<li id="index">Index</li>
<li id="about">About us</li>
<li id="contact">Contact</li>
</ul>
</div>
</div>
<section id="page">
<div class="content">
<!-- PAGES LOAD HERE -->
</div>
</section>
<div class="footer">
<div class="content">
--Footer-- All rights reserved.
</div>
</div>
JS:
$(document).ready(function () {
$('li').on("click", function () {
$pageName = $(this).attr('id');
$('#page .content').load(`pages/${$pageName}.html`);
$('li').removeClass('active'); //only to remove the selection of actual page in CSS
$(this).addClass('active'); //only to add the selection of actual page in CSS
window.history.pushState("object or string", "Title", `pages/${$pageName}.html`);
})
})
you're describing "routing" which is the idea of URLs matching the content that is being display.
In jquery i'd recommend googling: jquery router or javascript router
IF you're writing other languages you can google [language] router.
most recently google is bringing up https://www.npmjs.com/package/jqueryrouter which is now forwarding to https://github.com/scssyworks/silkrouter
Once you choose a router, read the docs and come back with more questions.

Activating tab using link of the another page

How to activate the tab when I click the link on the other page like:
when i click www.wakeke.com#go-to-tab2 the page will go to www.wakeke.com#go-to-tab2 and the tab 2 is activated.
here is my sample:
<div class="section group">
<div class="col span_1_of_4"> <!-- tab 1 -->
<img src="http://wakeke.com/media/wysiwyg/call_center.png" alt="" />
<h3>sample</h3>
<p>sample/p>
</div>
<div class="col span_1_of_4"> <!-- tab 2 -->
<img src="http://wakeke.com/media/wysiwyg/marketing.png" alt="" />
<h3>sample</h3>
<p>sample/p>
</div>
</div>
and here is the tab code:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li class="active"><a href="#business" data-toggle="tab"><img src="http://wwww.wakeke/media/wysiwyg/call_center_thumb.png" alt="" />
<div class="job-desc">
<h4>sample</h4>
<h5>sample</h5>
</div>
</a></li>
<li><a href="#marketing" data-toggle="tab"><img src="http://www.wakeke/media/wysiwyg/business_dev_thumb.png" alt="" />
<div class="job-desc">
<h4>sample</h4>
<h5>sample</h5>
</div>
</a></li>
</ul>
</div>
here is the image sample:
When I click the image:
image1
it will go to another page and the tab is activated
image 2
Please help me. :)
thank you
You can use the JavaScript location.hash and some usefull jQuery this way:
<script>
$(document).ready(function(){
if(window.location.hash!=""){
// Get the hash value and remove the # from it.
var hash = window.location.hash.substr(1);
// In the nav-tabs,
// find the right tab by targetting the `h4` which contains the word you used has a hash
// and click it.
$(".nav-tabs").find("li h4:constains('"+hash+"')").click();
}
});
</script>
So now, since you provided only a sample,
You will have to find the right words to use as a hash for each tabs.
Be carefull about case sensitivity.
Use one words contained in the h4 tag inside the li (the tab) that you want to be active.
This small script must be in the page where tabs are... Anywhere in the <body>.
It takes the hash from the URL and remove the # character.
Then it uses it to find a tab.
It may find more than one! Which will not do what you want.
I think it is a good starter for you to try.
I didn't test this code as I'm used to do before posting here... So I hope there is no mistake.
;)
If you do not already use it, you have to include the jQuery library in your <head> like this:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
EDIT
I just noticed that you are using the same hash in the anchor's href.
So here is a variant of the same thing that should avoid the possibility of clicking more than one tab.
<script>
$(document).ready(function(){
if(window.location.hash!=""){
// Get the hash value keeping the #.
var hash = window.location.hash;
// In the nav-tabs,
// find the right tab by targetting the `a` which has the same href as your hash
// and click it.
$(".nav-tabs").find("li a[href='"+hash+'"]").click();
}
});
</script>

i am struggling to add active class to my navigation menus with ajax

i used ajax on my site to load pages dynamically and add hashes to urls to preserve history and browser back button, and for this i am using jquery bbq plugin that is based on html5 history api and i have to say everything working fine except one issue and that is active class to current link.
i have two navigation main menu which is only on homepage and a second one is included on every page with php include function and its kind of a subnav of main menu.
as i said my problem is how to add active class to any link that is clicked so its look different from others and users should know where they are right now!
i tried different techniques but those only works with main menu and some kind of problem with secondary nav for better understanding please watch this video
as you can see in the video it works fine on main menu but only adds class to the secondary menu after click once on any link then click another link and then click back to original link, moreover when i refresh it removes the active class.
here is my code.
main menu
<div id="vertical-menu">
<!--<h2 class="logo">LOGO</h2>-->
<div class="logo">
<span class="arcd-male97"></span>
<h2 class="logo-name">AMR</h2>
<h6 class="logo-desc">ARCADE MUSIC REPOSITORY</h6>
</div>
<nav>
<ul id='menu' class="menu-items">
<li><i class="arcd-archive"></i></br>Browse</li>
<li><i class="arcd-music97"></i></br>Top albums</li>
<li></i></br>Top artists</li>
<li></i></br>Top lists</li>
<li></i></br>Charts</li>
</ul>
</nav>
</div>
secondary navbar
<div class="header_container" id="header_container"> <!--start header div-->
<div id="header_titles">
<h1 class="browse-heading">BROWSE</h1>
<h2 class="browse-subheading">GENRES & MOODS</h2>
</div>
</div> <!--end header div-->
<div id="tabnav_container"> <!--start tabnav_container-->
<div class="navtab_background"></div>
<nav>
<ul id="tabnav">
<li class="pop_tab"><i class="arcd-microphone352"></i>pop</li>
<li class="country_tab"><i class="arcd-guitarcountry"></i>country</li>
<li class="rock_tab"><i class="arcd-electricclone"></i>rock</li>
<li class="blues_tab"><i class="arcd-harmonicblues"></i>blues</li>
<li class="edm_tab"><i class="arcd-disc62edm"></i>edm</li>
<li class="jazz_tab"><i class="arcd-trumpet12jazz"></i>jazz</li>
<li class="rnb_tab"><i class="arcd-mic102"></i>r&b</li>
<li class="hip-hop_tab"><i class="arcd-musicplayer1hiphop"></i>hip hop</li>
<li class="reggae_tab"><i class="arcd-mic102"></i>reggae</li>
<li class="classical_tab"><i class="arcd-violin62classical"></i>classical</li>
<li class="folk_tab"><i class="arcd-guitar92folk"></i>folk</li>
<li class="soul_tab"><i class="arcd-mic102"></i>soul</li>
</ul>
</nav>
</div><!--end tabnav_container-->
and this is ajax script
$(function() {
// Keep a mapping of url-to-container for caching purposes.
var cache = {
// If url is '' (no fragment), display this div's content.
'': $('#default-homepage-contents')
};
// Bind an event to window.onhashchange that, when the history state changes,
// gets the url from the hash and displays either our cached content or fetches
// new content to be displayed.
$(window).bind( 'hashchange', function(e) {
// Get the hash (fragment) as a string, with any leading # removed. Note that
// in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
var url = $.param.fragment();
// Hide any visible ajax content.
$( '#main-container' ).children( ':visible' ).hide();
if ( cache[ url ] ) {
// Since the element is already in the cache, it doesn't need to be
// created, so instead of creating it again, let's just show it!
cache[ url ].fadeIn(1000);
} else {
// Show "loading" content while AJAX content loads.
$( '#loading' ).delay(500).show();
// Create container for this url's content and store a reference to it in
// the cache.
cache[ url ] = $( '<div class="bbq-item"/>' )
// Append the content container to the parent container.
.appendTo( '#main-container' )
// Load external content via AJAX. Note that in order to keep this
// example streamlined, only the content in .infobox is shown. You'll
// want to change this based on your needs.
.load( url, function() {
// Content loaded, hide "loading" content.
$( '#loading' ).fadeOut(1000);
});
}
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).trigger( 'hashchange' );
});
thanks for any help!
I had problems with new browsers and found this, I think the only correctly working plugin: jquery address
and docs are here: http://www.asual.com/jquery/address/docs/#api-reference example usage is
$(function() {
//push it to history
$('#tabnav > li').click(function(e) {
e.preventDefault();
$.address.parameter("browse", $(this).attr("href"), false);
});
//catch changes
$.address.change(function () {
$.each($.address.parameterNames(), function (index, value) {
url = $.address.parameter(value);
$('a[href="'+url+'"]').addClass('active');
});
});
});

How do I keep the current tab active after a page reload?

I'm currently using tabs and want to select the same tab after a user has posted data and the page reloads.
Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $items = $('#vtab>ul>li');
$items.mousedown(function() {
$items.removeClass('selected');
$(this).addClass('selected');
var index = $items.index($(this));
$('#vtab>div').hide().eq(index).show();
}).eq(0).mousedown();
});
</script>
Tabs:
<div id="vtab">
<ul>
<li class="user">User</li>
<li class="category">Category</li>
</ul>
<!--user-->
<div>Content</div>
</div>
<!--category-->
<div>Content</div>
</div>
Thank you!
One easy way is to post the data via XMLHttpRequest aka AJAX. That way, your whole page won't redirect. The other solution is to put the active tab in the URL. That has the side benefit of allowing bookmarks to return to the correct tab too. To put the tab in the URL, look at pushstate (and consider a polyfill/backwards compatible approach to work with browsers that do not have pushstate).

Set Jquery ui active tab on page load/reload

I'm using a basic implementation of Jquery UI Tabs that are working fine but I want to set (or reset) the active tab dynamically based on a user action.
How can I set the active tab based on a querystring value? With my previous tab solution I was able to pass a querystring value and set the active tab when the page loaded. (I had to abandon this older solution due to other technical challenges.)
When the user selects the Save button in my browser application, and the browser page reloads, how can I maintain focus on the tab they were on before they pressed save?
How can I set the active tab when a user returns to the Tasks page of my browser application? For example, all within my web application, if the user browses to the Projects page and then returns to the Task page, how can I reset the tab they were previously on?
Javascript:
$(function() {
$("#tabs").tabs();
});
HTML Example code:
<div id="tabs">
<ul>
<li>Description</li>
<li>Action</li>
<li>Resources</li>
<li>Settings</li>
</ul>
<div id="tabs-1">
<p>Description content</p>
</div>
<div id="tabs-2">
<p>Action content</p>
</div>
<div id="tabs-3">
<p>Resources content</p>
</div>
<div id="tabs-4">
<p>Settings </p>
</div>
</div>
I solved my own jQuery tab issues after additional research and trial and error. Here's a working example. I don't know if this is the most elegant solution but it works. I hope this helps.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/redmond/jquery-ui-1.10.1.custom.min.css">
<script language="javascript" type="text/javascript" src="js/jquery/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery/jquery-ui-1.10.1.custom.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs({active: document.tabTest.currentTab.value});
$('#tabs a').click(function(e) {
var curTab = $('.ui-tabs-active');
curTabIndex = curTab.index();
document.tabTest.currentTab.value = curTabIndex;
});
});
</script>
</head>
<body>
<form name="tabTest" method="post" action="tab">
<!-- default tab value 2 for Tab 3 -->
<input type="hidden" name="currentTab" value="2"/>
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div id="tabs-1">Tab 1 Content</div>
<div id="tabs-2">Tab 2 Content</div>
<div id="tabs-3">Tab 3 Content</div>
</div>
</form>
</body>
Here's how I answered each of my previous questions.
1. How can I set the active tab based on a querystring value?
I ended up not needing to use a querystring. I added the #tabs-x to the end of my url. For example, if I wanted a link directly to Tab 3 I coded a link as:
localhost:8080/pm/detail?prjID=2077#tabs-3
2. When the user selects the Save button in my browser application, and the browser page reloads, how can I maintain focus on the tab they were on before they pressed save?
I solved this by capturing the click event, getting the current tab index and then setting a hidden forms element "currentTab" to store the current tab value. Then back in the Java Servlet I retrieved the hidden forms elements and reset it when the page reloads.
$(document).ready(function() {
// Set active tab on page load
$("#tabs").tabs({active: document.tabTest.currentTab.value});
// Capture current tab index. Remember tab index starts at 0 for tab 1.
$('#tabs a').click(function(e) {
var curTab = $('.ui-tabs-active');
curTabIndex = curTab.index();
document.tabTest.currentTab.value = curTabIndex;
});
});
3. How can I set the active tab when a user returns to the Project page of my browser application? For example, all within my web application, if the user browses to the Task page and then returns to the Project page, how can I reset the tab they were previously on?
This is solved by setting a session variable in my Java Servlet to store the hidden forms element "currentTab". That way when I return the Project page, I can reset the "currentTab" value the same way I set it in the Save forms action.
I hope this example can help someone else with their jQuery tab issues!
jQuery UI Tabs can take in options. The ones that are particularly useful for your questions are cookie and selected. You can read about the options here.
var currentTab = $('.ui-state-active a').index();
currentTab = $('#divMainContent').find('#sel_tab')[0].value;
Note: Where Sel_tab is hidden field.
onclick on tabs achor link assign value to hidden feild

Categories

Resources