Open new page and scroll to page anchor

Asked

Viewed 3,229 times

0

I have a problem that when I open a link that directs to an anchor from another page and is hidden by the Fixer header.

I have a menu on my page:

Inside Index.html I have this menu

<a href="produtos.html#produto1">Produto 1</a>
<a href="produtos.html#produto2">Produto 2</a>
<a href="produtos.html#produto3">Produto 3</a>

However, when clicking and opening, anchors are hidden, because I have a header with position:fixed.

http://jsfiddle.net/thallysondias/q4hp3euv/ Jsfiddle -showing how the div is hidden

How do I be able, when clicking to open, to automatically scroll down 100px?

This is my page: http://www.omnibees.com/novo3/clientes.html#case-Studies If you use the top menus to open a new page in a particular section, see q the section title is hidden.

2 answers

0

If the anchor link is not solving, you can try using a function to check which parameter arrives at the url and scroll to the desired location.

if (param === "#produto1") {
  window.scrollTo(element)
}
  • the anchor works, my problem is that I need to give a scroll down, so the content does not get hidden by the menu

0


I found the solution:

/**
 * 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 = 180;

    // 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 } ,1000, 'easeOutSine');
            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);

It was the only way I could find to ensure that the scroll always occurs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.