corgen corgen - 16 days ago 4
CSS Question

How to auto scroll to target div if an id exists within body?

Consider i have a full screen slider on my website, when clicking on navigation menus its really annoying to scroll down every time you visit a page or a refresh.

So lets Say i have a structure like:

<body page-section="news">

<div class="royalslider">
This is a slider and it is fullscreen

<div id="body-layouts">
This is the body layout


How do i go about auto scroll to body-layouts div if page-section="news" attribute exists within body?

More information:
Visit this website you will notice that when clicking on navigation's, you're automatically scrolled down to the targeted divs :)


Try this:

With vanilla:

// first you get the the value of page-section
var section = document.querySelector("body").hasAttribute("page-section");
// after you check the value
if(section == "news") {
// if it is ok, you redirect
    location.href = "#body-layouts";

With :

var section = $("body").attr("page-section");
if(section == "news") {
    location.href = "#body-layouts";

With multiple attributes:

var attr1 = $("body").attr("page-section1");
var attr2 = $("body").attr("page-section2");
var redirection = "";
if(attr1 == "news") {
    redirection = "something";
} else if(attr2 == "something") {
    redirection = "something"; 

$('html, body').animate({
    scrollTop: $( $(redirection) ).offset().top - NAVBARHEIGHT
}, 0);