简体   繁体   中英

Scroll to element with ID when user click on MENU button ( also redirect to another page if its subpage)

I fight with specific problem. I have a menu in different file and include it to each sub-site. (to avoid repeating my self) And I also need to roll user over the site if he click some of the buttons.

In other words:

  • If user click HOME: Redirect him to Page:default
  • If user click menu REF: Redirect him to Page:default#ref
  • If user click LOGIN: Redirect him to Page:login
  • If user click JOBS: Redirect him to Page:default#jobs

hrefs like: n:href="Page:default#jobs" is Nette framework functionality however this is not nette problem because it basically just replace something like : index.html#jobs

How I scroll can be seen below:

<script>
    jQuery(document).ready(function($) {
        $('a[href^="#"]').bind('click.smoothscroll',function (e) {
            e.preventDefault();
            var target = this.hash,
            $target = $(target);

            $('html, body').stop().animate( {
                'scrollTop': $target.offset().top-40
            }, 900, 'swing', function () {
                window.location.hash = target;
            } );
        } );
    } );
</script>

What is the problem:
This JQUERY function want just to scroll down to some ID when in some id is placed. But unfortunately doesn't help when user is at eg jobs.php and click menu to go to index.php#ref

Can someone help me solve this issue? I am up for any advise or alternative doesn't need to be as code below.

ps Modern browsers enable to directly go to some id with href with hashtag with simple index.php#ref unfortunately this just directly open site without any effect of scrolling.

Say you redirect to another page, for example: default.php#jobs, all the pages that can perform the animate scrool must contain the following:

jQuery(document).ready(function() {
    // check if exist the hash inmmediatly
    if(window.location.hash){
        // get the hash
        var target = window.location.hash;
        $('html, body').stop().animate( {
             // here you need the top atribute, in your example is $(target).offset(), but this is an object, we need extract the top
            'scrollTop': $(target).offset().top-40
        }, 1900);   
    };
}

Include this script to every page you want the animated scrolling on.

$(document).ready(function(){
    if( window.location.hash != "" ){
        window.scrollTo(0, 0); // denies initial scroll to #

        $target = $(window.location.hash);

        $('html, body').stop().animate( {
            'scrollTop': $target.offset().top-40
        }, 900, 'swing');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM