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.
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);
}
});
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
<a href="#weather">Weather</a>
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);
});
Either .htaccess and PHP both can handle redirection
.htaccessRewriteEngine On
RewriteRule ^weather$ /#weather$ [R=301,NE,L]
PHPheader("Location: /#weather", true, 301);
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);
}
});