SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Feb 2014
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Script to scroll to anchor links divs and offset them

    Hi there!

    I'm in need of a script to scroll to anchor links divs and offset them. So far I found a few versions but none of them seem to work. I got this in my head:

    Code:
    <script>/**
      * Check a href for an anchor. If exists, and in document, scroll to it.
      * If href argument ommited, assumes context (this) is HTML Element,
      * which will be the case when invoked by jQuery after an event
      */
    function scroll_if_anchor(href) {
        href = typeof(href) == "string" ? href : $(this).attr("href");
    
        // You could easily calculate this dynamically if you prefer
        var fromTop = 50;
    
        // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
        // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
        if(href.indexOf("#") == 0) {
            var $target = $(href);
    
            // Older browser without pushState might flicker here, as they momentarily
            // jump to the wrong position (IE < 10)
            if($target.length) {
                $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
                if(history && "pushState" in history) {
                    history.pushState({}, document.title, window.location.pathname + href);
                    return false;
                }
            }
        }
    }    
    
    // When our page loads, check to see if it contains and anchor
    scroll_if_anchor(window.location.hash);
    
    // Intercept all anchor clicks
    $("body").on("click", "a", scroll_if_anchor);</script>
    And nothing happens

    the markup is as follows:

    Code:
    <div id="header">
        <a href="#home"><img class="header" src="images/logo.png" width="133" height="86" alt="Wildfire Images"></a>
        <nav>
        <ul id="navigation">
            <li><a class="scroll" href="#home">Home</a></li>
    <li><a class="scroll" href="#about">About Us</a>
                <ul>
                  <li><a class="scroll" href="#contact">Contact Us</a></li>
                </ul>
            </li>
    etc


    and the divs are as follows:

    Code:
    <div id="about" class="panel">


    Please help, I have to fix this problem...
    Last edited by Pullo; Feb 16, 2014 at 06:34. Reason: Added code tags

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2013
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are there any console log errors?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •