How to make header menu smooth scroll if header is common? - javascript

<script>
$(document).ready(function(){
$(".nav-menu").click(function(e){
e.preventDefault();
id = $(this).data('id');
$('html, body').animate({
scrollTop: $("#"+id).offset().top
}, 2000);
});
});
</script>
In this code I have a common header where smooth scroll working only when if I am on index page because I am define id on index page. Now, I want if I am on another page but when I click any id of header then it redirect to index and open related id section. So, How can I do that? Please help me.
Thank You

For other page when click on menu item redirect to index page and send clicked data attribute id with url. When you get id from url trigger click event.
Like.
$(document).ready(function(){
var hash = location.hash.substr(1).split('-');
var id= hash[1];
if(id && hash[0] == 'clicked'){
setTimeout(function(){ $('.nav-menu[data-id="'+id+'"]').trigger('click')}, 5);
}
$(".nav-menu").on('click', function(e){
e.preventDefault();
id = $(this).data('id');
if ($("#"+id).length){
$('html, body').animate({
scrollTop: $("#"+id).offset().top
}, 2000);
}else{
window.location.href="index?#clicked-"+id;
}
});
});

Related

Scrolling to ID issue in jquery

I am trying to create smooth scrolling to IDs. When I click on a link its ID should be scroll to top (at a certain point of top. Ex: 200px from top) of the page.
I tried it something like this:
var $root = $('html, body');
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: (($(href).offset().top >= 200 ) ? $(href).offset().top : 200)
}, 500, function () {
window.location.hash = href;
});
return false;
});
But it doesn't work and its always scrolling to top of the page.
Hope somebody may help me out.
I guess, the problem is your href, the target will presumably not be found. Maybe you'd be better off to store the element to scroll to in a data attribute, like so:
$('a[href*=#]').click(function(evt) {
evt.preventDefault();
var target = $(this).data('target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
With an anchor tag like so:
Brilliant rainbow colors
Obviously, the element with the ID somewhere_over_the_rainbow must exist somewhere in your DOM.
This should do the job correctly :
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
var top = $(href).offset().top;
$('body').animate(
{
scrollTop: top - 200
},
500
);
return false;
});
Obviously, the item with the id equal to the hash of the anchor must exist.

Change hash and animate scroll to element

I have a link and an element on the same page:
Click
<div id="#about-us"></div>
And the following javascript:
var scrollto = window.location.hash;
if (window.location.hash != null && window.location.hash != '') {
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 500);
}
This should animate a scroll to #about-us element,but it doesn't , it goes straight to element without animation,probably because the hash condition is not met,though there is a hash in url,because the hash is changed after the function.
I need a way to auto scroll to that element with animation,when you click the link . As example,if this page is index.php , and you want to go from another-page.php to index.php , straight to that element, it should load the page,and then scroll to the element,same if you are on index.php but at the top of the page and you click on the link,it should scroll down to the element.
The only problem is when you are on the same page.It doesn't pass the condition,so the animation doesn't work.
UPDATE I've changed the code a little bit.Now the condition is meet,but the animation doesn't work..
$('#link').click(function(e) {
window.location.href='index.php#about-us';
var scrollto = window.location.hash;
if (window.location.hash != null && window.location.hash != '') {
alert(scrollto);
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 500);
}
});
This is because window.location.hash is not defined by the time you click on the link and the event handler is called.
Try using:
jQuery(function($) {
$('#link').on('click', function(e) {
e.preventDefault();
var scrollTo = $(this).attr('href'); // retrieve the hash using .attr()
if (scrollTo != null && scrollTo != '') {
$('html, body').animate({
scrollTop: $(scrollTo).offset().top
}, 500);
}
});
});
Also, change your HTML code with:
<div id="about-us"></div> <!-- no need for prepending id value with # -->
See this working JSFiddle
If you want to bind the event on page load, use:
$(document).on('load', function(e) { /* the codez */ });
And retrieve the location hash with var scrollTo = window.location.hash; that will be defined when the page loads.
This code works for me
HTML for same page scroll
Click for About us
<div id="about-us"></div>
HTML for external page link
Click for product introduction
HTML for external page scroll
<div id="introduction"></div>
jQuery
if(window.location.hash){
var getUrlAfterHash = window.location.hash;
if($(getUrlAfterHash).length > 0){
$('html, body').animate({ scrollTop : 0 });
scrollToTop();
}
}
$('.link').on('click', function(e){
e.preventDefault();
var getUrlAfterHash = $(this).attr('href');
scrollToTop();
});
function scrollToTop(){
var idPositionHeight = $(getUrlAfterHash).offset();
$('html, body').animate({ scrollTop : idPositionHeight.top}, 800);
}

Scroll to position on another page when links already have anchor to scroll

I have this menu on home page that scrolls to the id positions:
<li>El evento</li>
<li>Asistentes</li>
<li>Contacto & Inscripciones</li>
I'm using this script for the smooth scrolling:
var $root = $('html, body');
$('a').click(function() {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
This works perfectly.
The problem is that I have another page in the site. When the user enters to it and click on any link of the menu, it just doesn't work since the divs exists only on home page. I want that if the user is in this other page and clicks on a link of the menu then the home page opens going to that section.
Any idea how can I fix this menu to be able to do both things?
Try adding index.html then hash like below in all other pages except homepage. This should work.
<li>El evento</li>
you can use this script, Need to dynamic means to get the hash url scrolldown to there.
Example:
<script>
if (window.location.href.trim().toLowerCase().indexOf('#event-section') > -1) {
$('html, body').stop().animate({
'scrollTop': $("a[href='#event-section']").offset().top
}, 800, 'swing', function () {
});
}
</script>
This is for first link page as index.html#event-section.
Simplest way is to create another nav bar for other page from where you want to redirect your end users
<li>El evento</li>
<li>Asistentes</li>
<li>Contacto & Inscripciones</li>
and on your home page run this script
<script>
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, " "));
}
$(document).ready(function(){
var param_scroll = getParameterByName('id');
if(param_scroll){
$('html, body').animate({
scrollTop: $("#"+param_scroll).offset().top
}, 3000);
}
});
</script>
jQuery not required if you implemented this fucntion:
function scrollTo(anchorName) {
location.hash = "#" + anchorName;
return false;
}
in this case you link should be:
my_link

Scroll to page depending on button that is clicked

Can anyone explain to me how I can use the jquery scroll-to to make the buttons on the yellow menu scroll to their corresponding sections (i.e distribution to the pink block)
This is my code: http://jsfiddle.net/VXkW5/5/
I think its something like this:
$(".nav").click(function () {
$('html, body').animate({
scrollTop: $(".section").offset().top + $(".section").height()
}, 500);
});
But I dont know how to relate it to it's relevant section based on the link that was clicked.
Working Demo
First of all, ID need to be unique in the page. I see both as well as uses same ID
so i have made change & Just add the corresponding div id to the href tag, it will take to that particular div on click
posting
distribution
applicantions
In terms of jQuery:
$(".nav").click(function (e) {
e.preventDefault();
var divId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(divId).offset().top;
}, 500);
});
You could have a link like
Click to jump to section 1
And a section like
<div id="section1">
<p>Section 1 content</p>
</div>
And handle the scroll to like so
<script type="text/javascript">
$(".nav").click(function (event) {
event.stopPropagation();
var theHref = $(this).attr('href');
$('html, body').animate({
scrollTop: $(theHref).offset().top + $(".section").height()
}, 500);
});
</script>

Adding effects when anchor tag is clicked

Is there a way to add a class to any div that is being scrolled to by clicking an anchor?
I currently have this code but can only add the "animated swing" class to the #ecomm div..
Ideally any anchor on the page that I click on I not only want to scroll down to it but add an animation class..
My code so far:
<script>
$('a[href=#ecomm]').click(function(){
$("#ecomm").addClass( "animated swing" );
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
</script>
Should work for all anchor tags with # hrefs.
<script>
$('a[href^=#]').click(function () { // Use all anchor tags with an href that starts with #
var href = $(this).attr('href'); // Get the href for the clicked anchor.
$(href).addClass( "animated swing" ); // The href is the same as the id.
$('html, body').animate({
scrollTop: $(href).offset().top
}, 500);
return false;
});
</script>
Taking into account #rorypicko's comment, a data attribute could be added to ensure only # hrefs you require will use this functionality:
<a href="#ecomm" data-scroll-link>Text</a>
<script>
$('a[href^=#][data-scroll-link]').click(function () { // Use all anchor tags with an href that starts with # and the specified data attribute.
var href = $(this).attr('href'); // Get the href for the clicked anchor.
$(href).addClass( "animated swing" ); // The href is the same as the id.
$('html, body').animate({
scrollTop: $(href).offset().top
}, 500);
return false;
});
</script>
something like this:
<script>
var href
$('a').click(function(){
href = this.attr('href');
$('div').each(function(){
var thisDiv = this
if(this.attr('id') == href)
{
thisDiv.addClass( "animated swing" );
}
$('html, body').animate({
scrollTop: thisDiv.offset().top
}, 500);
});
return false;
});
</script>
Hope this works.

Categories