Search code examples
jquerytransitionslidedownslideup

slideUp/Down using jquery from one section of a page to another


I'm trying to use the slideUp and Down effect to transition between sections of the same webpage. Basically, I set up

My code for the HTML, CSS, and JQuery can be seen on jsfiddle: (http://jsfiddle.net/dbartolome/2s0jy72q/1/)

   $("#work").click(function(){
   event.preventDefault();
   $("header").slideDown(700);

Update: I found this thing called scroll to anchor online. What are your thoughts? I don't understand a part of their code. This is their jsfiddle: (http://jsfiddle.net/BjpWB/4/)

    function scrollToAnchor(aid){
     var aTag = $("a[name='"+ aid +"']");
     $('html,body').animate({scrollTop: aTag.offset().top},'slow');
     }

     $("#link").click(function() {
     scrollToAnchor('id3');
    });

I got lost with the content for function scrollToAnchor(aid)


Solution

  • Get the position of the section with offset and animate scrollTop down to the element's top point

    $('a').on('click', function(e){
        e.preventDefault();
        var targetID = $(this).attr('href')
        var elementPosition = $(targetID).offset().top
        $('html,body').animate({scrollTop: elementPosition},'slow');
    }); 
    

    jsFiddle Example

    It works up or down, so you can even use this to add a "Back to Top" link

    <header id="top">...</header>
    

    Just link to #top

    <a href="#top">Back to top</a>
    

    In the example and above code, notice that the href of the link is the id of where it scrolls to


    In the jquery code, it takes the href of the clicked a and selects the element with an ID equal to it. The code then finds the top offset point of the element with that id, and animates scrollTop to it.

    References

    • animate() - used for CSS property animation, also find scrollTop explanation in there
    • attr() - used to get the href value
    • offset() - used to find the top position of the element within the document scope.
    • on() - used to listen for a click before performing the scroll - same as click()