Scroll to the anchor - javascript

Code:
function scroll_page(){
var target = document.location.hash.replace("#","");
var selector = 'div[id='+target+']';
alert(selector);
$('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
return false;
};
Сode is called here:
$(window).on('hashchange', function() {
scroll_page();
});
The problem is that when you click on the link jumps sharply to this div , and then gently pulls up to its top .

If you have an anchor in your link like <a href='#id'>, then it will trigger before your JavaScript. hashchange event occurs after the scrolling to the anchor.
To prevent this, you need to bind to click event and prevent default behaviour.
I would do something like this.
HTML:
<a class="slow-scroll" href="#first">First</a>
<a class="slow-scroll" href="#second">First</a>
<a class="slow-scroll" href="#third">First</a>
JS:
$(".slow-scroll").on('click', function(e) {
var target = $(this).attr("href").substr(1);
var selector = 'div[id='+target+']';
alert(selector);
$('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
e.preventDefault();
return false;
});
Here is the JSFiddle Demo.

Try the following code,
$(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 - 140
}, 1000);
return false;
}
}
});
});

Related

How do i redirect a li a href link?

When the user clicks the li link, i want the user to get redirected to #gameshowintro .
Html code:
<li class="about"></li>
javascript:
$(document).ready(function() {
$("body").css("display", "none");
$("body").fadeIn(2000);
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
function redirectPage() {
window.location = linkLocation;
}
});
To make your code work, you need to pass the linkLocation to the function. The linkLocation is not a global scope variable (it is local to the click event handler function), which isn't accessible from the called function. So change your code to:
$("a").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, "redirectPage('" + linkLocation + "')");
});
function redirectPage(linkLocation) {
window.location = linkLocation;
}
Or if you need to scrolled to that section. If that's the case, use this smooth scroll:
$(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;
}
}
});
});

Smooth scrolling to anchor on same page

Call me stupid, but I don't see it.
I have made a Joomla page with links to sections in the same page. very basic: <a href="#sed"> and then <p id="sed">. I include jQuery like this:
<script src="/media/jui/js/jquery.min.js" type="text/javascript"></script>
It is part of Joomla 3.
I am using this script from CSS-Tricks, which I have put in the of the page:
<script>
$(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;
}
}
});
});
</script>
I've fiddled with the CSS Tricks sample page (copy/pasted it to my own HTML editor and changed a bit of the code) and yes, it works, but I can't get it to work in my own page. The page just jumps to the anchor but doesn't scroll smoothly.
Mind you: I hardly know anything of JavaScript or jQuery, so bear with me... to a jQuery specialist this must be a piece of cake....
Here is the test page I have made: http://test.tomhiemstra.nl.
Any help appreciated.
Cheers,
Thom
I couldn't figure out what's causing this, but on your page the $ isn't getting recognized. Replace all the $ in your script to jQuery and it works.
jQuery(function() {
jQuery('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = jQuery(this.hash);
target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
if (target.length) {
jQuery('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Alternatively, it's probably a better idea to wrap your function in one that will map the $ to jQuery.
(function ($) {
$(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;
}
}
});
});
})(jQuery);
Can you try this
$('a[href^="#"]').click(function(event) {
event.preventDefault();
var target = $(this).attr("href").substring(1);
if(target) {
$('html,body').animate({
scrollTop: $('[name=' + target +']').offset().top
}, 1000);
}
});
With the help of Talya S. above, this is what I have come up with. I hope I have done it right, with all the brackets and curly brackets etc.:
<script>
(function ($) {
$(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;
}
}
});
});
})(jQuery);
</script>
Did I add too many brackets or too few?
What I still don't understand, though, is why the $ was not recognised as jQuery, which is one of the most basic things you learn in jQuery (yes, I had come that far :-P). If anyone can clarify that to me "like I'm a four year old".
Thanx again Talya S. and my apologies for misspelling :-)
Thom

Anchor link for same and different page

I'm using that code:
$(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;
}
}
});
});
and <a href="#allcontentcontact"> to link to the div <div id="allcontentcontact"></div>.
The problem is:
"#allcontentcontact" is on my homepage, so the code works perfectly only when I'm on the homepage. But I have a fixed menu that links to other pages! So I need something that makes my a href links to that div when I'm on another page.
Thanks!
Thanks for the answers, I did it! :)
<script>
var url = "http://192.168.1.157/wp/";
$(function(){
if (location.href==url){
$('#menu #mylink').attr("href","#bluecontent");
$('#menu #mylink2').attr("href","#allcontentcontact");
}
});
</script>
The URL is strange because I'm coding on localhost, but the code works perfectly. :)
And the HTML
<a id="mylink" href="<?php bloginfo('url'); ?>#bluecontent"><span>Parceiros</span></a>
<a id="mylink2" href="<?php bloginfo('url'); ?>#allcontentcontact"><span>Contato</span></a>
It's almost done. All the links works perfectly taking me smoothly to their specified anchors.
The problem is: my script that slides to anchors on other pages include the #bluecontent and #allcontentcontact on the URL. Is it possible to delete that from the URL?
Here is the code:
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});

Scroll to anchors

I'm trying to code a menu for my website that has the possibility to scroll to anchors on the same page and anchors on different pages.
The first one is working. The code is:
$(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;
}
}
});
});
The menu is the same on every page, I can't edit his code on each page. So the HTML code basically is:
<a id="mylink" href="http://www.mcsoftware.com.br/sitemc/#allcontentcontact"><span>Contato</span></a>
<a id="mylink2" href="http://www.mcsoftware.com.br/sitemc/#bluecontent"><span>Parceiros</span></a>
And I'm using javascript to detect if the user is on the homepage, and if he is, it changes the href behaviour, because it's only on the homepage that the anchors are on the same page of the menu. Look:
var url = "http://www.mcsoftware.com.br/sitemc/";
$(function(){
if (location.href==url){
$('#menu #mylink').attr("href","#allcontentcontact");
$('#menu #mylink2').attr("href","#bluecontent");
}
});
Now, the problem is the second part of what I've said on the beginning of the post: Scroll to anchors on different pages.
So, what script should I use to do the trick and doesn't affect everything that I've already done? Is it possible?
(And the code need to hide the "#nameoftheanchor" from the URL, like the first code already do)
Thanks!
I did something that is working really well! But still shows the "#anchortag" on the URL when the anchor is on another page.
<script>
var url = "http://www.mcsoftware.com.br/sitemc/";
if (location.href==url) {
$(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;
}
}
});
});
} else {
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
}
</script>
any help?
To answer your second question, the browsing history can be changed using
window.history.pushState() and
window.history.replaceState().
For how to use each function, see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
window.location.pathname will retrieve the current url path. So combining these concepts, I came up with the following:
history.pushState("", "", window.location.pathname);
This should remove the hash while keeping the rest of the url in-tact. If this doesn't solve your problem, hopefully it will at least get you started on the right path.

smooth scroll and accordion conflict bootstrap

although this has been asked a few times I haven't found something which will fix my problem.
This is my code for the smooth scroll:
$(function() {
$('a[href*=#]:not([href=#]),a[href*=#]:not(a[data-toggle])').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;
}
}
});
});
it's css-tricks code with a bit of editing.
This is the site: http://redrocketwebsitedesign.co.uk/test/my3DtwinAlpha/about/#arrow6
So the accordion is still being selected for the scrolling, and it's not running the accordion js.
I think there's a problem with my javascript not selector code :
a[href*=#]:not(a[data-toggle])
Any help appreciated :-]
This is what you are really looking for :
$('a[href*="#"]:not([href="#"]):not([data-toggle])').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;
}
}
});
:not([data-toggle])
is to avoid smooth scroll with bootstrap tab, carousel etc...
The page you provided has a mistake in code:
$('a[href*=#]:not([href=#]),'a[href^="#"]:not([data-toggle])').click(function() {
^^^ - extra and unnecessary character
So your handler is not set.
You can also consider specifying the class of the element(s) that should trigger a smooth scroll animation (thus excluding others, such as the accordion tabs), like this:
$('a[href*=#][class*="smooth"]:not([href=#])').click(function()
Or vice versa, specify the class of the element(s) that shouldn't trigger the script (in this case we exclude the class of the links that trigger the accordion effect):
jQuery('a[href*=#]:not([href*=#][class*="accordion-toggle"])').click(function()
var headp = $(".pixxett-header").innerHeight();
var stick = $(".pixxett-header.sticky").innerHeight();
$(document).on('click', 'a[href^="#"]:not([href="#"]):not([data-toggle])', function (event) {
event.preventDefault();
if (scroll == 0){
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - stick}, 500);
}else{
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - headp}, 500);
}
});

Categories

Resources