javascript – Extremely accurate Jquery Anchor!

Question:

I'm using the following code:

<?php       
   foreach($sqlPortfolio2 as $dPortfolio2):
    echo '<li><a href="#guia'.$dPortfolio2['id'].'" class="scroll">'.$dPortfolio2['nome'.$lg].'</a></li>';
                endforeach;
                ?>


<script type="text/javascript">
jQuery(document).ready(function($) { 
    $(".scroll").click(function(event){        
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 800);
   });
});
</script>

The problem is that I use the fixed menu, that is, when I click on a menu item, the menu comes together, and ends up over the title of the element I clicked on! Can you make an extremely accurate anchor?

Answer:

You must discount the height of the menu when scrolling.

<script type="text/javascript">
jQuery(document).ready(function($) { 
    $(".scroll").click(function(event){        
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top - $("#MENU").outerHeight(true) - 20}, 800);
   });
});
</script>

We've discounted 20 pixels so that the menu doesn't "stick" to the topmost element. This makes it more visually pleasing.

Scroll to Top