I have created a simple tabs widget, here is a working jsfiddle: http://jsfiddle.net/G3eRn/1/
When I add another Tabs widget "as you will see in the example" in the same page, everything get missed up! I really don't know how to describe it... after looking into it and trying to debug it, I have concluded that it is the JavaScript that needs to be looked at, so I have researched, but didn't really find an answer that would fix it. However, I found that using .each might fix it? so I did try it but didn't work - maybe I used it wrong.
What I am doing wrong?
Here is the JS:
//Tabs Navigation
$('.tabs .tabs-menu a:eq(0)').addClass('active');
$('.tabs .tabs-sections .tabs-section:not(:first-child)').hide();
$('.tabs .tabs-menu a').on('click', function() {
$('.tabs-menu a').removeClass('active');
$(this).addClass('active');
$('.tabs .tabs-sections > .tabs-section:eq(' + $(this).index() + ')').show().siblings().hide();
});
You have to make sure only the current tab group is being affected (using .each):
http://jsfiddle.net/G3eRn/2/
//Tabs Navigation
$('.tabs').each(function(){
var $tabs = $(this);
$tabs.find('.tabs-menu a:eq(0)').addClass('active');
$tabs.find('.tabs-sections .tabs-section:not(:first-child)').hide();
$tabs.find('.tabs-menu a').on('click', function () {
$tabs.find('.tabs-menu a').removeClass('active');
$(this).addClass('active');
$tabs.find('.tabs-sections > .tabs-section:eq(' + $(this).index() + ')').show().siblings().hide();
});
});
And here's a version that's a little more performant:
http://jsfiddle.net/G3eRn/7/
//Tabs Navigation
$('.tabs').each(function(){
var $tabs = $(this);
$tabs.find('.tabs-sections .tabs-section:not(:first-child)').hide().end()
.find('.tabs-menu a').on('click', function () {
$tabs.find('.tabs-menu a').removeClass('active').end()
.find('.tabs-sections > .tabs-section:eq(' + $(this).index() + ')').show().siblings().hide();
$(this).addClass('active');
}).eq(0).addClass('active');
});
The second example uses end() which "undoes" the last selector.
So for example
$('.el').find('div').end().addClass('test')
would add the class "test" to the .el element instead of all div's inside it.
In your "click" handler, you have to make sure that you're applying changes only to the relevant group of tabs. As your code is currently written, the handler code will affect all the matching tab groups on the page.
You can use jQuery DOM navigation methods to do it:
$('.tabs .tabs-menu a:eq(0)').addClass('active');
$('.tabs .tabs-sections .tabs-section:not(:first-child)').hide();
$('.tabs .tabs-menu a').on('click', function () {
// find the current menu group and deactivate all tab labels
$(this).closest('.tabs-menu').find('a').removeClass('active');
// activate this tab
$(this).addClass('active');
// find the tab section corresponding to this tab menu
$(this).closest('.tabs').find('.tabs-sections > .tabs-section:eq(' + $(this).index() + ')').show().siblings().hide();
});
The .closest() method walks up the DOM looking for a match. From that point, .find() looks down the DOM in that isolated subtree.
Here's your fiddle, updated.
Personally I'd use a delegated handler setup so that tab groups could be added dynamically without needing to re-run the code:
$('body').on('click', '.tabs-menu a', function() {
// as above
});
You need to apply the functions to every .tabs element.
$('.tabs').each(function() {
var $tabs = $(this);
$('.tabs-menu a:eq(0)', $tabs).addClass('active');
$('.tabs-sections .tabs-section:not(:first-child)', $tabs).hide();
$('.tabs-menu a', $tabs).on('click', function() {
$('.tabs-menu a', $tabs).removeClass('active');
$(this).addClass('active');
$('.tabs-sections > .tabs-section:eq(' + $(this).index() + ')', $tabs).show().siblings().hide();
});
});
The syntax jQuery( 'selector', node ) selects child elements only inside the given HTML element node. In this case an element with the class .tabs. This is similar to do jQuery( node ).find( 'selector' ).
Using $ is just a way for me to always know, which variable is a jQuery object. For example: var $this = jQuery( this );.
If you want more performance in your script store selected node in a variable (e.g. .tabs-menu a in your code). You may even querySelector to get the elements via plain JS instead of jQuery. The jQuery each on the other hand is very comfortable.
An example mixup of different methods:
$('.tabs').each(function() {
var tabs = this,
links = this.querySelectorAll( '.tabs-menu a' );
/* passing a DOMNodeList to jQuery and filter it */
$(links).filter(':eq(0)', tabs).addClass('active');
$('.tabs-sections .tabs-section:not(:first-child)', tabs).hide();
/* setup event handler */
/* without jQuery, one need to itererate over the list of elements */
for( var i = links.length; i--; ) {
var currentLink = links[i];
currentLink.addEventListener('click', function() {
var currentTab = this;
/* jQuery does the loop internally */
$(links).removeClass('active');
currentTab.classList.add('active');
$('.tabs-sections > .tabs-section:eq(' + $(currentTab).index() + ')', tabs).show().siblings().hide();
}, false);
}
});
For documentation and browser support see here:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
https://developer.mozilla.org/en-US/docs/Web/API/Element.classList
There is a JS ployfill for nearly any modern feature:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
Related
adding active class to parent list when link is clicked/active , am trying to inject that using JavaScript as follow:
$(document).ready(
function()
{
//injecting active status to the navigation bar lists
var element = document.getElementById("navbar-ul");
var links = element.getElementsByTagName("a");
for(var i = 0; i < links.length ; i++) {
links[i].onclick(function () {
links[i].parent().addClass('active');
});
}
}
);
but am getting the following error:
TypeError: links[i].onclick is not a function
how I supposed to achieve that?
A more verbose JQuery way to approach this
$('#navbar-ul a').each(function() {
$(this).on('click', function() {
$(this).parent().addClass('active');
});
});
This is very simply with jQuery:
$("#navbar-ul a").click(function(){
$(this).parent().addClass("active");
});
EXAMPLE 1
I'm guessing you're trying to add an active state to the link thats being clicked on and remove the others? If so you can use .siblings() to find the other links and remove their class:
$("#navbar-ul a").click(function(){
$(this).closest("li").addClass("active").siblings("li").removeClass("active");
});
EXAMPLE 2
You would be better of with adding a class to the tags who needs an eventListener. (with jquery)
$(document).ready(function() {
$("#navbar-ul a").on("click", function() {
var active = document.querySelector('#navbar-ul .active');
if(active){
$("#navbar-ul a").removeClass('active');
}
$(this).addClass("active");
});
);
I'm having a bit of trouble with a dropdown menu that triggers fadeOut as soon as the mouse leaves the grandparent div, I've searched this problem to death and have yet to find an elegant solution. Here is my code : link
var main = function() {
$('nav').mouseenter(function() {
$('ul li ul').fadeIn('400');
});
$('nav ul li').mouseleave(function(){
$('ul li ul').fadeOut('400');
});
}
$(document).ready(main);
DEMO: MY FIDDLE
You need to specify what element(s) you are trying to attach the event to. By adding '>' youre forcing to only attach the event to that element's children. Try this:
var main = function() {
$('nav').mouseenter(function() {
$(this).find('ul').fadeIn('400');
});
$('nav>ul>li').mouseleave(function() {
$(this).find('ul').fadeOut('400');
});
};
FIDDLE
$(this).find('ul').fadeOut('400');
is correct as $('ul>li>ul').fadeOut('400'); Could not target specific (current) li.
Use following hierarchical flow of TAGS
var main = function() {
$('nav').mouseenter(function() {
$('ul li ul').fadeIn('400');
});
$('nav ul li').mouseleave(function() {
$(this).find('ul').fadeOut('400');
});
};
I have some code that uses jquery:
$(document).ready(function(){
$('#tabs div').hide();
$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');
$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div').hide();
$(currentTab).show();
return false;
});
});
And I converted it to use mootools
window.addEvent('domready', function() {
$$('#tabs div').hide();
$$('#tabs div:first').show();
$$('#tabs ul li:first').addClass('active');
$$('#tabs ul li a').addEvent('click', function(event) {
$$('#tabs ul li').removeClass('active');
$$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$$('#tabs div').hide();
$$(currentTab).show();
return false;
});
});
But I get an error: $$(this).parent is not a function
How do I fix it?
this is quite poor. many bad practices and api differences.
window.addEvent('domready', function() {
// cache what we will reuse into vars
var tabs = document.id('tabs'),
divs = tabs.getElements('div'),
// for loop
len = divs.length,
ii = 1;
// hide all but the first one w/o extra lookups.
for (;ii < len;++ii)
divs[ii].hide();
// first match
tabs.getElement('ul li').addClass('active');
// attach the events to all links
tabs.getElements('ul li a').addEvent('click', function(event) {
event && event.stop();
tabs.getElement('ul li').removeClass('active');
this.getParent().addClass('active');
tabs.getElement(this.get('href')).show();
return false;
});
});
basically, a few practices you need to consider:
cache your selectors, esp repetitive stuff
avoid going to dom and work from memory
use normal js array looping or methods to avoid an extra selector like :first or :last, you already have the data
stop the event directly, don't return false
.getElement() will return the first match
avoid storing stuff into variables that you won't reuse
consider using event delegation and attaching a click handler once to the ul rather than to all child A's - eg, tabs.getElement('ul').addEvent('click:relay(li a)', fn) will achieve the same but only create a single event handler
there is no parent method in mootools, instead, the method name is getParent.it is not difficulty to convert from jquery to mootools. it is helpful having a look on docs.
We've got a few pages using ajax to load in content and there's a few occasions where we need to deep link into a page. Instead of having a link to "Users" and telling people to click "settings" it's helpful to be able to link people to user.aspx#settings
To allow people to provide us with correct links to sections (for tech support, etc.) I've got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element.
Is there a way to disable this? Below is how I'm doing this so far.
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
//return false;
});
});
I had hoped the return false; would stop the page from scrolling - but it just makes the link not work at all. So that's just commented out for now so I can navigate.
Any ideas?
Use history.replaceState or history.pushState* to change the hash. This will not trigger the jump to the associated element.
Example
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);
});
Demo on JSFiddle
* If you want history forward and backward support
History behaviour
If you are using history.pushState and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration setting (Chrome 46+ only).
history.scrollRestoration = 'manual';
spec
info
Browser Support
replaceState
pushState
polyfill
Step 1: You need to defuse the node ID, until the hash has been set. This is done by removing the ID off the node while the hash is being set, and then adding it back on.
hash = hash.replace( /^#/, '' );
var node = $( '#' + hash );
if ( node.length ) {
node.attr( 'id', '' );
}
document.location.hash = hash;
if ( node.length ) {
node.attr( 'id', hash );
}
Step 2: Some browsers will trigger the scroll based on where the ID'd node was last seen so you need to help them a little. You need to add an extra div to the top of the viewport, set its ID to the hash, and then roll everything back:
hash = hash.replace( /^#/, '' );
var fx, node = $( '#' + hash );
if ( node.length ) {
node.attr( 'id', '' );
fx = $( '<div></div>' )
.css({
position:'absolute',
visibility:'hidden',
top: $(document).scrollTop() + 'px'
})
.attr( 'id', hash )
.appendTo( document.body );
}
document.location.hash = hash;
if ( node.length ) {
fx.remove();
node.attr( 'id', hash );
}
Step 3: Wrap it in a plugin and use that instead of writing to location.hash...
I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash="btn_"+$(this).attr("id")
//return false;
});
});
Now the URL appears as page.aspx#btn_elementID which is not a real ID on the page. I just remove "btn_" and get the actual element ID
I was recently building a carousel which relies on window.location.hash to maintain state and made the discovery that Chrome and webkit browsers will force scrolling (even to a non visible target) with an awkward jerk when the window.onhashchange event is fired.
Even attempting to register a handler which stops propogation:
$(window).on("hashchange", function(e) {
e.stopPropogation();
e.preventDefault();
});
Did nothing to stop the default browser behavior.
The solution I found was using window.history.pushState to change the hash without triggering the undesirable side-effects.
$("#buttons li a").click(function(){
var $self, id, oldUrl;
$self = $(this);
id = $self.attr('id');
$self.siblings().removeClass('selected'); // Don't re-query the DOM!
$self.addClass('selected');
if (window.history.pushState) {
oldUrl = window.location.toString();
// Update the address bar
window.history.pushState({}, '', '#' + id);
// Trigger a custom event which mimics hashchange
$(window).trigger('my.hashchange', [window.location.toString(), oldUrl]);
} else {
// Fallback for the poors browsers which do not have pushState
window.location.hash = id;
}
// prevents the default action of clicking on a link.
return false;
});
You can then listen for both the normal hashchange event and my.hashchange:
$(window).on('hashchange my.hashchange', function(e, newUrl, oldUrl){
// #todo - do something awesome!
});
A snippet of your original code:
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
});
Change this to:
$("#buttons li a").click(function(e){
// need to pass in "e", which is the actual click event
e.preventDefault();
// the preventDefault() function ... prevents the default action.
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
});
Okay, this is a rather old topic but I thought I'd chip in as the 'correct' answer doesn't work well with CSS.
This solution basically prevents the click event from moving the page so we can get the scroll position first. Then we manually add the hash and the browser automatically triggers a hashchange event. We capture the hashchange event and scroll back to the correct position. A callback separates and prevents your code causing a delay by keeping your hash hacking in one place.
var hashThis = function( $elem, callback ){
var scrollLocation;
$( $elem ).on( "click", function( event ){
event.preventDefault();
scrollLocation = $( window ).scrollTop();
window.location.hash = $( event.target ).attr('href').substr(1);
});
$( window ).on( "hashchange", function( event ){
$( window ).scrollTop( scrollLocation );
if( typeof callback === "function" ){
callback();
}
});
}
hashThis( $( ".myAnchor" ), function(){
// do something useful!
});
Adding this here because the more relevant questions have all been marked as duplicates pointing here…
My situation is simpler:
user clicks the link (a[href='#something'])
click handler does: e.preventDefault()
smoothscroll function: $("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
then window.location = link;
This way, the scroll occurs, and there's no jump when the location is updated.
Erm I have a somewhat crude but definitely working method.
Just store the current scroll position in a temp variable and then reset it after changing the hash. :)
So for the original example:
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
var scrollPos = $(document).scrollTop();
document.location.hash=$(this).attr("id")
$(document).scrollTop(scrollPos);
});
I don't think this is possible. As far as I know, the only time a browser doesn't scroll to a changed document.location.hash is if the hash doesn't exist within the page.
This article isn't directly related to your question, but it discusses typical browser behavior of changing document.location.hash
if you use hashchange event with hash parser, you can prevent default action on links and change location.hash adding one character to have difference with id property of an element
$('a[href^=#]').on('click', function(e){
e.preventDefault();
location.hash = $(this).attr('href')+'/';
});
$(window).on('hashchange', function(){
var a = /^#?chapter(\d+)-section(\d+)\/?$/i.exec(location.hash);
});
Save scroll position before changing url fragment.
Change url fragment.
Restore old scroll position.
let oldScrollPosition = window.scrollY;
window.location.hash = addressFragment;
window.scrollTo(0, oldScrollPosition);
It's fast, so client won't notice anything.
The other way to do this is to add a div that's hidden at the top of the viewport. This div is then assigned the id of the hash before the hash is added to the url....so then you don't get a scroll.
Here's my solution for history-enabled tabs:
var tabContainer = $(".tabs"),
tabsContent = tabContainer.find(".tabsection").hide(),
tabNav = $(".tab-nav"), tabs = tabNav.find("a").on("click", function (e) {
e.preventDefault();
var href = this.href.split("#")[1]; //mydiv
var target = "#" + href; //#myDiv
tabs.each(function() {
$(this)[0].className = ""; //reset class names
});
tabsContent.hide();
$(this).addClass("active");
var $target = $(target).show();
if ($target.length === 0) {
console.log("Could not find associated tab content for " + target);
}
$target.removeAttr("id");
// TODO: You could add smooth scroll to element
document.location.hash = target;
$target.attr("id", href);
return false;
});
And to show the last-selected tab:
var currentHashURL = document.location.hash;
if (currentHashURL != "") { //a tab was set in hash earlier
// show selected
$(currentHashURL).show();
}
else { //default to show first tab
tabsContent.first().show();
}
// Now set the tab to active
tabs.filter("[href*='" + currentHashURL + "']").addClass("active");
Note the *= on the filter call. This is a jQuery-specific thing, and without it, your history-enabled tabs will fail.
This solution creates a div at the actual scrollTop and removes it after changing hash:
$('#menu a').on('click',function(){
//your anchor event here
var href = $(this).attr('href');
window.location.hash = href;
if(window.location.hash == href)return false;
var $jumpTo = $('body').find(href);
$('body').append(
$('<div>')
.attr('id',$jumpTo.attr('id'))
.addClass('fakeDivForHash')
.data('realElementForHash',$jumpTo.removeAttr('id'))
.css({'position':'absolute','top':$(window).scrollTop()})
);
window.location.hash = href;
});
$(window).on('hashchange', function(){
var $fakeDiv = $('.fakeDivForHash');
if(!$fakeDiv.length)return true;
$fakeDiv.data('realElementForHash').attr('id',$fakeDiv.attr('id'));
$fakeDiv.remove();
});
optional, triggering anchor event at page load:
$('#menu a[href='+window.location.hash+']').click();
I have a simpler method that works for me. Basically, remember what the hash actually is in HTML. It's an anchor link to a Name tag. That's why it scrolls...the browser is attempting to scroll to an anchor link. So, give it one!
Right under the BODY tag, put your version of this:
<a name="home"></a><a name="firstsection"></a><a name="secondsection"></a><a name="thirdsection"></a>
Name your section divs with classes instead of IDs.
In your processing code, strip off the hash mark and replace with a dot:
var trimPanel = loadhash.substring(1); //lose the hash
var dotSelect = '.' + trimPanel; //replace hash with dot
$(dotSelect).addClass("activepanel").show(); //show the div associated with the hash.
Finally, remove element.preventDefault or return: false and allow the nav to happen. The window will stay at the top, the hash will be appended to the address bar url, and the correct panel will open.
I think you need to reset scroll to its position before hashchange.
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash) {
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function() {
var scrollLocation = $(window).scrollTop();
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash = $(this).attr("id");
$(window).scrollTop( scrollLocation );
});
});
If on your page you use id as sort of an anchor point, and you have scenarios where you want to have users to append #something to the end of the url and have the page scroll to that #something section by using your own defined animated javascript function, hashchange event listener will not be able to do that.
If you simply put a debugger immediate after hashchange event, for example, something like this(well, I use jquery, but you get the point):
$(window).on('hashchange', function(){debugger});
You will notice that as soon as you change your url and hit the enter button, the page stops at the corresponding section immediately, only after that, your own defined scrolling function will get triggered, and it sort of scrolls to that section, which looks very bad.
My suggestion is:
do not use id as your anchor point to the section you want to scroll to.
If you must use ID, like I do. Use 'popstate' event listener instead, it will not automatically scroll to the very section you append to the url, instead, you can call your own defined function inside the popstate event.
$(window).on('popstate', function(){myscrollfunction()});
Finally you need to do a bit trick in your own defined scrolling function:
let hash = window.location.hash.replace(/^#/, '');
let node = $('#' + hash);
if (node.length) {
node.attr('id', '');
}
if (node.length) {
node.attr('id', hash);
}
delete id on your tag and reset it.
This should do the trick.
This worked for me using replaceState:
$('a[href^="#"]').click(function(){
history.replaceState({}, '', location.toString().replace(/#.*$/, '') + $(this).attr('href'));
});
Only add this code into jQuery on document ready
Ref : http://css-tricks.com/snippets/jquery/smooth-scrolling/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
We've got a few pages using ajax to load in content and there's a few occasions where we need to deep link into a page. Instead of having a link to "Users" and telling people to click "settings" it's helpful to be able to link people to user.aspx#settings
To allow people to provide us with correct links to sections (for tech support, etc.) I've got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element.
Is there a way to disable this? Below is how I'm doing this so far.
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
//return false;
});
});
I had hoped the return false; would stop the page from scrolling - but it just makes the link not work at all. So that's just commented out for now so I can navigate.
Any ideas?
Use history.replaceState or history.pushState* to change the hash. This will not trigger the jump to the associated element.
Example
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);
});
Demo on JSFiddle
* If you want history forward and backward support
History behaviour
If you are using history.pushState and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration setting (Chrome 46+ only).
history.scrollRestoration = 'manual';
spec
info
Browser Support
replaceState
pushState
polyfill
Step 1: You need to defuse the node ID, until the hash has been set. This is done by removing the ID off the node while the hash is being set, and then adding it back on.
hash = hash.replace( /^#/, '' );
var node = $( '#' + hash );
if ( node.length ) {
node.attr( 'id', '' );
}
document.location.hash = hash;
if ( node.length ) {
node.attr( 'id', hash );
}
Step 2: Some browsers will trigger the scroll based on where the ID'd node was last seen so you need to help them a little. You need to add an extra div to the top of the viewport, set its ID to the hash, and then roll everything back:
hash = hash.replace( /^#/, '' );
var fx, node = $( '#' + hash );
if ( node.length ) {
node.attr( 'id', '' );
fx = $( '<div></div>' )
.css({
position:'absolute',
visibility:'hidden',
top: $(document).scrollTop() + 'px'
})
.attr( 'id', hash )
.appendTo( document.body );
}
document.location.hash = hash;
if ( node.length ) {
fx.remove();
node.attr( 'id', hash );
}
Step 3: Wrap it in a plugin and use that instead of writing to location.hash...
I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash="btn_"+$(this).attr("id")
//return false;
});
});
Now the URL appears as page.aspx#btn_elementID which is not a real ID on the page. I just remove "btn_" and get the actual element ID
I was recently building a carousel which relies on window.location.hash to maintain state and made the discovery that Chrome and webkit browsers will force scrolling (even to a non visible target) with an awkward jerk when the window.onhashchange event is fired.
Even attempting to register a handler which stops propogation:
$(window).on("hashchange", function(e) {
e.stopPropogation();
e.preventDefault();
});
Did nothing to stop the default browser behavior.
The solution I found was using window.history.pushState to change the hash without triggering the undesirable side-effects.
$("#buttons li a").click(function(){
var $self, id, oldUrl;
$self = $(this);
id = $self.attr('id');
$self.siblings().removeClass('selected'); // Don't re-query the DOM!
$self.addClass('selected');
if (window.history.pushState) {
oldUrl = window.location.toString();
// Update the address bar
window.history.pushState({}, '', '#' + id);
// Trigger a custom event which mimics hashchange
$(window).trigger('my.hashchange', [window.location.toString(), oldUrl]);
} else {
// Fallback for the poors browsers which do not have pushState
window.location.hash = id;
}
// prevents the default action of clicking on a link.
return false;
});
You can then listen for both the normal hashchange event and my.hashchange:
$(window).on('hashchange my.hashchange', function(e, newUrl, oldUrl){
// #todo - do something awesome!
});
A snippet of your original code:
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
});
Change this to:
$("#buttons li a").click(function(e){
// need to pass in "e", which is the actual click event
e.preventDefault();
// the preventDefault() function ... prevents the default action.
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
});
Okay, this is a rather old topic but I thought I'd chip in as the 'correct' answer doesn't work well with CSS.
This solution basically prevents the click event from moving the page so we can get the scroll position first. Then we manually add the hash and the browser automatically triggers a hashchange event. We capture the hashchange event and scroll back to the correct position. A callback separates and prevents your code causing a delay by keeping your hash hacking in one place.
var hashThis = function( $elem, callback ){
var scrollLocation;
$( $elem ).on( "click", function( event ){
event.preventDefault();
scrollLocation = $( window ).scrollTop();
window.location.hash = $( event.target ).attr('href').substr(1);
});
$( window ).on( "hashchange", function( event ){
$( window ).scrollTop( scrollLocation );
if( typeof callback === "function" ){
callback();
}
});
}
hashThis( $( ".myAnchor" ), function(){
// do something useful!
});
Adding this here because the more relevant questions have all been marked as duplicates pointing here…
My situation is simpler:
user clicks the link (a[href='#something'])
click handler does: e.preventDefault()
smoothscroll function: $("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
then window.location = link;
This way, the scroll occurs, and there's no jump when the location is updated.
Erm I have a somewhat crude but definitely working method.
Just store the current scroll position in a temp variable and then reset it after changing the hash. :)
So for the original example:
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
var scrollPos = $(document).scrollTop();
document.location.hash=$(this).attr("id")
$(document).scrollTop(scrollPos);
});
I don't think this is possible. As far as I know, the only time a browser doesn't scroll to a changed document.location.hash is if the hash doesn't exist within the page.
This article isn't directly related to your question, but it discusses typical browser behavior of changing document.location.hash
if you use hashchange event with hash parser, you can prevent default action on links and change location.hash adding one character to have difference with id property of an element
$('a[href^=#]').on('click', function(e){
e.preventDefault();
location.hash = $(this).attr('href')+'/';
});
$(window).on('hashchange', function(){
var a = /^#?chapter(\d+)-section(\d+)\/?$/i.exec(location.hash);
});
Save scroll position before changing url fragment.
Change url fragment.
Restore old scroll position.
let oldScrollPosition = window.scrollY;
window.location.hash = addressFragment;
window.scrollTo(0, oldScrollPosition);
It's fast, so client won't notice anything.
The other way to do this is to add a div that's hidden at the top of the viewport. This div is then assigned the id of the hash before the hash is added to the url....so then you don't get a scroll.
Here's my solution for history-enabled tabs:
var tabContainer = $(".tabs"),
tabsContent = tabContainer.find(".tabsection").hide(),
tabNav = $(".tab-nav"), tabs = tabNav.find("a").on("click", function (e) {
e.preventDefault();
var href = this.href.split("#")[1]; //mydiv
var target = "#" + href; //#myDiv
tabs.each(function() {
$(this)[0].className = ""; //reset class names
});
tabsContent.hide();
$(this).addClass("active");
var $target = $(target).show();
if ($target.length === 0) {
console.log("Could not find associated tab content for " + target);
}
$target.removeAttr("id");
// TODO: You could add smooth scroll to element
document.location.hash = target;
$target.attr("id", href);
return false;
});
And to show the last-selected tab:
var currentHashURL = document.location.hash;
if (currentHashURL != "") { //a tab was set in hash earlier
// show selected
$(currentHashURL).show();
}
else { //default to show first tab
tabsContent.first().show();
}
// Now set the tab to active
tabs.filter("[href*='" + currentHashURL + "']").addClass("active");
Note the *= on the filter call. This is a jQuery-specific thing, and without it, your history-enabled tabs will fail.
This solution creates a div at the actual scrollTop and removes it after changing hash:
$('#menu a').on('click',function(){
//your anchor event here
var href = $(this).attr('href');
window.location.hash = href;
if(window.location.hash == href)return false;
var $jumpTo = $('body').find(href);
$('body').append(
$('<div>')
.attr('id',$jumpTo.attr('id'))
.addClass('fakeDivForHash')
.data('realElementForHash',$jumpTo.removeAttr('id'))
.css({'position':'absolute','top':$(window).scrollTop()})
);
window.location.hash = href;
});
$(window).on('hashchange', function(){
var $fakeDiv = $('.fakeDivForHash');
if(!$fakeDiv.length)return true;
$fakeDiv.data('realElementForHash').attr('id',$fakeDiv.attr('id'));
$fakeDiv.remove();
});
optional, triggering anchor event at page load:
$('#menu a[href='+window.location.hash+']').click();
I have a simpler method that works for me. Basically, remember what the hash actually is in HTML. It's an anchor link to a Name tag. That's why it scrolls...the browser is attempting to scroll to an anchor link. So, give it one!
Right under the BODY tag, put your version of this:
<a name="home"></a><a name="firstsection"></a><a name="secondsection"></a><a name="thirdsection"></a>
Name your section divs with classes instead of IDs.
In your processing code, strip off the hash mark and replace with a dot:
var trimPanel = loadhash.substring(1); //lose the hash
var dotSelect = '.' + trimPanel; //replace hash with dot
$(dotSelect).addClass("activepanel").show(); //show the div associated with the hash.
Finally, remove element.preventDefault or return: false and allow the nav to happen. The window will stay at the top, the hash will be appended to the address bar url, and the correct panel will open.
I think you need to reset scroll to its position before hashchange.
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash) {
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function() {
var scrollLocation = $(window).scrollTop();
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash = $(this).attr("id");
$(window).scrollTop( scrollLocation );
});
});
If on your page you use id as sort of an anchor point, and you have scenarios where you want to have users to append #something to the end of the url and have the page scroll to that #something section by using your own defined animated javascript function, hashchange event listener will not be able to do that.
If you simply put a debugger immediate after hashchange event, for example, something like this(well, I use jquery, but you get the point):
$(window).on('hashchange', function(){debugger});
You will notice that as soon as you change your url and hit the enter button, the page stops at the corresponding section immediately, only after that, your own defined scrolling function will get triggered, and it sort of scrolls to that section, which looks very bad.
My suggestion is:
do not use id as your anchor point to the section you want to scroll to.
If you must use ID, like I do. Use 'popstate' event listener instead, it will not automatically scroll to the very section you append to the url, instead, you can call your own defined function inside the popstate event.
$(window).on('popstate', function(){myscrollfunction()});
Finally you need to do a bit trick in your own defined scrolling function:
let hash = window.location.hash.replace(/^#/, '');
let node = $('#' + hash);
if (node.length) {
node.attr('id', '');
}
if (node.length) {
node.attr('id', hash);
}
delete id on your tag and reset it.
This should do the trick.
This worked for me using replaceState:
$('a[href^="#"]').click(function(){
history.replaceState({}, '', location.toString().replace(/#.*$/, '') + $(this).attr('href'));
});
Only add this code into jQuery on document ready
Ref : http://css-tricks.com/snippets/jquery/smooth-scrolling/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});