maxisme
maxisme

Reputation: 4245

scrolling to the beginning of an anchor

I am having trouble with scrolling to anchors. I am having 3 problems:

  1. When I am over two panels and I click a link to one of the panels. Nothing happens. Neither A or B will work

  2. When I am on for example D and I click C it goes to the end of C.

    Before clicking on C:

    enter image description here

    After clicking on C:

    Goes to the end of C

  3. When I add any jquery or javascript like this to scroll to the hashes

    function scrollTo(hash) { location.hash = "#" + hash; }

    it does not seem to work.


What I would like:

I would like the link to go to the beginning of the div (the furthest left of the div) no matter where the user is.


My code

I have a page like this:

HTML:

<ul class="links">
    <li><a href="#a">A</a></li>
    <li><a href="#b">B</a></li>
    <li><a href="#c">C</a></li>
    <li><a href="#d">D</a></li>
</ul>
<div class="panels">
    <div class="panel" id="a">I'am A</div>
    <div class="panel" id="b">I'am B</div>
    <div class="panel" id="c"><span class="stupid-long-content">I'am C (very long)</span></div>
    <div class="panel" id="d">I'am D</div>
</div>

Where each div is this size of the screen through css like this:

*
{
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box; 
    box-sizing: border-box;
}

html, body
{
   height:100%;  
}
body
{
    margin:0;
    padding:0;  
}

.panels
{
    white-space: nowrap;
    height: inherit;
}

.panel
{
   height: inherit;
   font-size: 20px;
   text-align: center;
   padding: 60px;
   display: inline-block;
   min-width: 100%;
}

.stupid-long-content
{
    width: 3000px;
    display: block;
}

JSFIDDLE

Upvotes: 4

Views: 83

Answers (1)

Stefano Dalpiaz
Stefano Dalpiaz

Reputation: 1673

You can use jQuery scrollLeft function and prevent the default browser handling:

$('.links a').click(function(e) {
    e.preventDefault();
    if (this.hash)
        $('body, html').scrollLeft($(this.hash).offset().left);
});

Here is the updated fiddle.

Upvotes: 2

Related Questions