Redirect to a div on a different page with smooth scrolling?

后端 未结 8 1156
悲哀的现实
悲哀的现实 2021-01-01 15:33

Question Background:

I have a 2 page website. Both pages use the same masterlayout.cshtml page which features a Navbar. Within the

相关标签:
8条回答
  • 2021-01-01 16:36

    How do you redirect to another page, using href value?

    If so, also add in data-id for this <a> tag too.

    So when you click on Events link, it will go to another html page and you want to scroll to Events div, right?

    Then using sessionStorage, you can store and get back the page id, then scroll to its specific div.

    Add below script and let's see.

    JQUERY

    $(document).ready(function(){
    
        // get sessionStorage for page id
        var get_id = sessionStorage.getItem('pg_id');
    
        // check page id, then scroll to its div
        if(get_id)
            scrollToID(get_id, 300);
    
        // click event to scroll to div
        $('.nav li a').on('click', function(){
            var id = '#'+$(this).data('id');
            sessionStorage.setItem('pg_id', id);
            scrollToID(id, 300);
        }); 
    
    });
    function scrollToID(id, speed) {
        var offSet = 70;
        var obj = $(id).offset();
        var targetOffset = $(id).offset().top - offSet;
        $('html,body').animate({ scrollTop: targetOffset }, speed);
    }
    

    HTML (My sample)

    <ul class="nav navbar-nav">
        <li><a href="#" class="scroll-link" data-id="Welcome">Welcome</a></li>
        <li><a href="#" class="scroll-link" data-id="features">Club</a></li>
        <li><a href="#" class="scroll-link" data-id="About">About Us</a></li>
        <li><a href="#" class="scroll-link" data-id="Location">Location</a></li>
        <li><a href='page2.html' data-id="Event">Events</a></li>
        <!-- use your script to redirect to another page, but add "data-id" -->
    </ul>
    
    0 讨论(0)
  • 2021-01-01 16:40

    I guess you may use $.cookie every time you scroll on the first page.

    For Example :

    $(document).ready(function()
    {
        $('.scroll-link').on("click",function()
        {
           $.cookie('page',$(this).attr('data-id')); 
        });
        if($.cookie('page') != null || $.cookie('page') != "")
        {
            scrollToID($.cookie('page'), 1000);
        }
    })
    
    0 讨论(0)
提交回复
热议问题