Force scroll on a specific url - javascript

I am trying to achieve an effect/redirect on a website I'm developing for my company.
Previously we have had a mydomain.com/weather, direct to a specific page showing the weather. Now, since we moved the weather to a section of the root page (/), we want the users who go to mydomain.com/weather to land on the root page but with the window scrolled to the weather section.
Essentially, i'm trying to achieve the same effect of a same page anchor (#myAnchor) but with a url.
I've searched on Google for same page anchor url slash but I only could find stuff regarding the regular anchors.
Any help would be appreciated.

Firstly, give your "weather" section an id
<div id="weather">
<!-- weather content -->
</div>
Voila! Visit mydomain.com/#weather now. The browser should scroll you to corresponding element. This also applied to anchor tag
Weather
Implementing animation
Suppose you're going to apply scroll animation when certain element clicked
<a class="to-weather" href="javascript:void(0);">See weather here</a>
<button type="button" class="to-weather">See weather here</button>
with jQuery
$('.to-weather').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#weather").offset().top
}, slow);
});
Redirect
Either .htaccess and PHP both can handle redirection
.htaccess
RewriteEngine On
RewriteRule ^weather$ /#weather$ [R=301,NE,L]
PHP
header("Location: /#weather", true, 301);
Implementing animation
A hacky solution but works. First, Set the #weather on element on topper area of document such as body
<body id="weather">
Browser will stayed at top as the id its bound to is on body tag. And once document is ready, you can do scrolling animation to desired element with just a simple validation. I'll name it #weather-area
$(document).ready(function() {
//Not all browser contains # in location.hash
var hash = location.hash.replace('#', '');
if(hash === 'weather') {
$('html, body').animate({
scrollTop: $('#weather-area').offset().top
}, 3000);
}
});

I managed to get the desired result using a combination of the answer above and window.pathname
essentially:
$(window).load(function() {
if(window.pathname == '/weather') {
$('html, body').animate({
scrollTop: $('#weather-area').offset().top
}, 3000);
}
});

Related

Scroll down to specific position after page refresh issue

I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}

ScrollToTop is working but i want to scroll down to page

I'm working on an angular5 app. In that app, I need to go down to the current page based on data. ScrollToTop is working fine, I want to go down to the current page. Is there any way like scrollTop in angular5.
You can scroll to the bottom of the page with this line:
window.scrollTo(0,document.body.scrollHeight);
If you want to scroll a specific html element, try this one:
window.scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);
See also this demo, it can help you.
You can make it using animate and scrollTop from jQuery as following:
HTML :
Contact
<!-- set the H2 deep down in the page -->
<h2 id="contact">Contact</h2>
jQuery :
$('a[href^="#"]').on('click', function(){
var the_id = $(this).attr("href");
if (the_id === '#') {
return;
}
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;
});

Page scroll to right page from menu anchor but not from direct link

I'am using this free script
http://codyhouse.co/gem/css-faq-template/
http://codyhouse.co/demo/faq-template/index.html#payments
The demo has the same problem as my website, although it's even worse on my website.
If you use the menu, everything works fine. You have some space above the header.
But if you visit the direct link http://codyhouse.co/demo/faq-template/index.html#payments not from the menu
it looks like this
As you can see, there is no space above the header "payments".
It is even worse on my page. It starts at "Can I have.." and the header is hidden. Can not find where I can adjust this when I visit the page direct from the link without it effects how it looks when I visit the section from the menu.
When user clicks on a section
//select a faq section
faqsCategories.on('click', function(event){
event.preventDefault();
var selectedHref = $(this).attr('href'),
target= $(selectedHref);
if( $(window).width() < MqM) {
faqsContainer.scrollTop(0).addClass('slide-in').children('ul').removeClass('selected').end().children(selectedHref).addClass('selected');
closeFaqsContainer.addClass('move-left');
$('body').addClass('overlay');
} else {
$('body,html').animate({ 'scrollTop': target.offset().top - 69}, 200);
}
});
Javascript code: http://codyhouse.co/demo/faq-template/js/main.js
Style: http://codyhouse.co/demo/faq-template/css/style.css
Just a quick hack, use
if(window.location.hash) {
// if url contain '#'
// scroll down a few pixle
}
EDIT:
it's hard to demenstrated this in jsfiddle, since it won't let me play with the # hash.
var url = 'http://example.com/test.html#hash';
//you can get by using window.location.href
var hash = url.split('#')[1];
// this get the 1st hash variable
if(hash) {
// if hash exist
$('html, body').animate({
scrollTop: "5000px"
}, 0);
// scroll down a little bit
}
It's seems there's a couple of problems here. For me it looks like everything happens when a scrolling event fire.
Try this:
$(document).ready(function(){
$(window).scroll();
})

jQuery Smooth Scroll to ID on same and on other page: how to set offset?

Im using jQuery on my page to jump / scroll to IDs.
This works from other pages with anchors like
Jump & Scroll to ID on other page
and on the same page only with anchors like
Jump / Scroll to ID on the same page
Thats not the best solution because I have to change my nav menue but it works (I load another menue with other tags on the page).
Now im looking for a way to add an offset of -230px to the scroll / jump script, beause I have a fixed header on my page.
I think its simple but unfortunately im not a jQuery pro. How can I do this? Please Help me to add the -230 Offset to this function :)
The jQuery Code:
(function($){
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
},1000,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()
}
});
})(jQuery)
The responsible for saying how much your page will scroll down is scrollTop: $(target).offset().top, so, if you want to offset -230px just subtract 230 from $(target).offset().top.
But, if you do this in your current code it will not work, because you are changing the hash using location.hash = target;. When you do this, your browser will locate the hash and jump to it (without animating, just jumping).
Observe this demo: http://jsfiddle.net/pcyn2fvk/
If you click in the anchor, the page will scroll down to the content and after the scroll it will jump (this is caused by location.hash = target;).
Here is the demo without using location.hash = target;: http://jsfiddle.net/pcyn2fvk/1/
I assume you will need to change the hash, so, you can try a different approach, like this one explained by Lea Verou (http://lea.verou.me/2011/05/change-url-hash-without-page-jump/) that uses the History API instead of location.hash.
There are some other approaches, for example, you can remove the id of your target section (the one you clicked to scroll to) when you click to the anchor, then, when you change the location using location.hash, the browser will not find the clicked id, and will not jump to it, then, after that, you can reassign the id to your section.
Hope it helps!
I found another approach with anchor hashtags. This allows me to load a different page and scroll to my id with an offset.
In IE the scroll works well on all pages but all other browsers don't scroll on the smae page. If I click my link on the page wehre I want to scroll they jump to the hastags and dont use my jQuery scroll function. If I click the same link from an other URL the scroll works.
(other approach, only working from Link on Page A to Page B)
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top -230
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});

JQuery detect if an element with particular id is visible after page scrolling

I want to create the navigation as it is shown on page http://kiskolabs.com/
I've already created sticky menu however the problem begins with marking active element in menu.
The question is:
How can I detect if page is scrolled to particular id?
Let's say I have some headers like.
<h1 id="whatisit">What is it</h1>
<h1 id="desc">Description</h1>
<h1 id="faq">FAQ</h1>
and menu
<nav>
What is it
Description
FAQ
</nav>
I want highlight menu (add class or whatever) when page scrolls to this element.
I've found already how to scroll element to particular ID in this thread but I don't know how to detect on what id the is now. The size of page is dynamic and may change during content. So absolute solution what I thought of is bad.
What I got so far for scrolling:
$("nav a").click(function (){
$("html, body").animate({ scrollTop: $($(this).attr('href')).offset().top }, 1000);
});
I've also found this solution but maybe is there better way to achieve it?
Edit
This question is not duplicate of the question suggested by moderator. Moreover, that question does not have the accepted answer. My problem is a bit more advanced.
You could use animate callback function:
$("nav a").click(function () {
$("html, body").animate({
scrollTop: $(this.href).offset().top
}, 1000, function () {
$(this).addclass('scrolled').siblings('h1').removeClass('scrolled');
});
});
During a lot of trying and finding solutions in Internet I've solved my problem.
I've used waypoints plugin which appeared very easy to use. The plugin can be downloaded here.
The html code of menu:
<nav>
....
....
<a href="#whydata" class="scrollable" >....</a>
...
</nav>
and html code of headers where page is to be scrolled:
<h2 class="scrollable" id="whatisit">...</h2>
<h2 class="scrollable" id="spec">...</h2>
Jquery code to make page scroll on particular element with #id the same as a href attribute.
$("nav a.scrollable").click(function (){
var elementClickedHref = $(this).attr('href');
$('html, body').animate({
scrollTop: $(elementClickedHref).offset().top-100
}, 2000);
return false;
});
To change color of element which is currently active after scrolling I've used waypoint plugin. The code below finds h2 which is scrollable and get it's id. Then finds which links that are scrollable too has href same as id of a element and adds active class to this id and remove active class from inactive elements.
$('h2.scrollable').waypoint(function() {
var idToCheck = '#' + $(this).attr('id');
$('a.scrollable').removeClass('active');
$('a.scrollable[href="'+idToCheck+'"]').addClass('active');
}, {
offset: '100%'
});
It works perfectly as I wanted. I hope this solution will help someone who will face such problem.

Categories