Search code examples
javascriptjqueryhtmlcssfixed

Fixed element animation scrolls body at top


I posted this again, but I guess I wasn't clear enough on my problem.

I have a 'hidden' fixed element that I want to open from the side when clicking on it.

Style:

<style>
#fixed {
    position: fixed;
    width: 200px;
    top: 120px;
    left: -200px;
    height: 200px;
    z-index: 5;
}

.leftc {
    left: 0 !important;
}
</style>

Html:

<div id="fixed">
<div id="fixedbtn"><a href=#>btn</a></div>
</div>

Jquery:

<script>
$("#fixedbtn a").click(function(e) {
  $('#fixed').toggleClass('leftc');
})
</script>

So, my problem is that when I click on the button the body scrolls back to the top! I have no idea why this is happening. I have tried using this code:

var windowPos = $(window).scrollTop();
$('body, html').animate({scrollTop: windowPos}, "fast");

...but I can see the scrollbar move at the top and back to the correct position. I tried removing the 'fast', but no luck.

Help! I would really like someone to also EXPLAIN why this is happening; I have tried everything!


Solution

  • The reason it's scrolling the body back to the top is because of your href tag,

    <a href="#">btn</a>
    

    "#" is an anchor. Example: If i set my a tag's href to "#myDiv", it'll scroll to the div with the id "myDiv". Since you only put a "#", it'll just scroll to the top.

    edit

    If you really want your a tag to go nowhere, you can try this

    <a href="JavaScript:void()">btn</a>