[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Scroll to an element with jQuery

  • This topic is empty.
Viewing 15 posts - 16 through 30 (of 31 total)
  • Author
    Posts
  • #9765
    jonathan
    Participant

    With this solution you do not need any plugin and there’s no setup required besides placing the script before your closing </body> tag.

    $("a[href^='#']").on("click", function(e) {
      $("html, body").animate({
        scrollTop: $($(this).attr("href")).offset().top
      }, 1000);
      return false;
    });
    
    if ($(window.location.hash).length > 1) {
      $("html, body").animate({
        scrollTop: $(window.location.hash).offset().top
      }, 1000);
    }
    

    On load, if there is a hash in the address, we scroll to it.

    And – whenever you click an a link with an href hash e.g. #top, we scroll to it.

    ##Edit 2020

    If you want a pure JavaScript solution: you could perhaps instead use something like:

    var _scrollToElement = function (selector) {
      try {
        document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
      } catch (e) {
        console.warn(e);
      }
    }
    
    var _scrollToHashesInHrefs = function () {
      document.querySelectorAll("a[href^='#']").forEach(function (el) {
        el.addEventListener('click', function (e) {
          _scrollToElement(el.getAttribute('href'));
          return false;
        })
      })
      if (window.location.hash) {
        _scrollToElement(window.location.hash);
      }
    }
    
    _scrollToHashesInHrefs();
    
    #9749
    svnm
    Participant

    I set up a module scroll-element npm install scroll-element. It works like this:

    import { scrollToElement, scrollWindowToElement } from 'scroll-element'
    
    /* scroll the window to your target element, duration and offset optional */
    let targetElement = document.getElementById('my-item')
    scrollWindowToElement(targetElement)
    
    /* scroll the overflow container element to your target element, duration and offset optional */
    let containerElement = document.getElementById('my-container')
    let targetElement = document.getElementById('my-item')
    scrollToElement(containerElement, targetElement)
    

    Written with help from the following SO posts:

    Here is the code:

    export const scrollToElement = function(containerElement, targetElement, duration, offset) {
      if (duration == null) { duration = 1000 }
      if (offset == null) { offset = 0 }
    
      let targetOffsetTop = getElementOffset(targetElement).top
      let containerOffsetTop = getElementOffset(containerElement).top
      let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
      scrollTarget += offset
      scroll(containerElement, scrollTarget, duration)
    }
    
    export const scrollWindowToElement = function(targetElement, duration, offset) {
      if (duration == null) { duration = 1000 }
      if (offset == null) { offset = 0 }
    
      let scrollTarget = getElementOffset(targetElement).top
      scrollTarget += offset
      scrollWindow(scrollTarget, duration)
    }
    
    function scroll(containerElement, scrollTarget, duration) {
      let scrollStep = scrollTarget / (duration / 15)
      let interval = setInterval(() => {
        if ( containerElement.scrollTop < scrollTarget ) {
          containerElement.scrollTop += scrollStep
        } else {
          clearInterval(interval)
        }
      },15)
    }
    
    function scrollWindow(scrollTarget, duration) {
      let scrollStep = scrollTarget / (duration / 15)
      let interval = setInterval(() => {
        if ( window.scrollY < scrollTarget ) {
          window.scrollBy( 0, scrollStep )
        } else {
          clearInterval(interval)
        }
      },15)
    }
    
    function getElementOffset(element) {
      let de = document.documentElement
      let box = element.getBoundingClientRect()
      let top = box.top + window.pageYOffset - de.clientTop
      let left = box.left + window.pageXOffset - de.clientLeft
      return { top: top, left: left }
    }
    
    #9759
    shahdat
    Participant

    $('html, body').animate(...) does not work for me in the iPhone, Android, Chrome, or Safari browsers.

    I had to target the root content element of the page.

    $(‘#content’).animate(…)

    Here is what I have ended up with:

    if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
        $('#content').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
       }, 'slow');
    }
    else{
        $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
        }, 'slow');
    }
    

    All body content wired up with a #content div

    <html>
        ....
        <body>
            <div id="content">
            ...
            </div>
        </body>
    </html>
    
    #9760
    user7601056
    Participant

    Animations:

    // slide to top of the page
    $('.up').click(function () {
        $("html, body").animate({
            scrollTop: 0
        }, 600);
        return false;
    });
    
    // slide page to anchor
    $('.menutop b').click(function(){
        //event.preventDefault();
        $('html, body').animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        }, 600);
        return false;
    });
    
    // Scroll to class, div
    $("#button").click(function() {
        $('html, body').animate({
            scrollTop: $("#target-element").offset().top
        }, 1000);
    });
    
    // div background animate
    $(window).scroll(function () {
    
        var x = $(this).scrollTop();
    
        // freezze div background
        $('.banner0').css('background-position', '0px ' + x +'px');
    
        // from left to right
        $('.banner0').css('background-position', x+'px ' +'0px');
    
        // from right to left
        $('.banner0').css('background-position', -x+'px ' +'0px');
    
        // from bottom to top
        $('#skills').css('background-position', '0px ' + -x + 'px');
    
        // move background from top to bottom
        $('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
    
        // Show hide mtop menu  
        if ( x > 100 ) {
        $( ".menu" ).addClass( 'menushow' );
        $( ".menu" ).fadeIn("slow");
        $( ".menu" ).animate({opacity: 0.75}, 500);
        } else {
        $( ".menu" ).removeClass( 'menushow' );
        $( ".menu" ).animate({opacity: 1}, 500);
        }
    
    });
    
    // progres bar animation simple
    $('.bar1').each(function(i) {
      var width = $(this).data('width');  
      $(this).animate({'width' : width + '%' }, 900, function(){
        // Animation complete
      });  
    });
    
    #9762
    fajir
    Participant

    If you want to scroll within an overflow container (instead of $('html, body') answered above), working also with absolute positioning, this is the way to do :

    var elem = $('#myElement'),
        container = $('#myScrollableContainer'),
        pos = elem.position().top + container.scrollTop() - container.position().top;
    
    container.animate({
      scrollTop: pos
    }
    
    #9763
    irshad-khan
    Participant

    Easy way to achieve the scroll of page to target div id

    var targetOffset = $('#divID').offset().top;
    $('html, body').animate({scrollTop: targetOffset}, 1000);
    
    #9754
    cynya
    Participant

    This is Atharva’s answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView.
    Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:

     $('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
    
    #9744
    polaris
    Participant

    This worked for me:

    var targetOffset = $('#elementToScrollTo').offset().top;
    $('#DivParent').animate({scrollTop: targetOffset}, 2500);
    
    #9771
    object-object
    Participant

    This is achievable without jQuery:

    document.getElementById("element-id").scrollIntoView();
    
    #9750
    stardust4891
    Participant

    Updated answer as of 2019:

    $('body').animate({
        scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
    }, 'fast');
    
    #9745
    minguocode
    Participant
    jQuery(document).ready(function($) {
      $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = $(target);
    
        $('html, body').stop().animate( {
          'scrollTop': $target.offset().top-40
        }, 900, 'swing', function () {
          window.location.hash = target;
        } );
      } );
    } );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <ul role="tablist">
      <li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
      <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
      <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
    </ul>
    
    <div id="pane1"></div>
    <div id="pane2"></div>
    <div id="pane3"></div>
    #9768
    edvard-kerberg
    Participant

    This is the way I do it.

    document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
    

    Works in any browser.

    It can easily be wrapped into a function

    function scrollTo(selector) {
        document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
    }
    

    Here is a working example

    $(".btn").click(function() {
      document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
    })
    .btn {margin-bottom: 500px;}
    .middle {display: block; margin-bottom: 500px; color: red;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <button class="btn">Scroll down</button>
    
    <h1 class="middle">You see?</h1>
    
    <div id="scrollHere">Arrived at your destination</div>

    Docs

    #9755
    kamil-kielczewski
    Participant

    ONELINER

    subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior:'smooth'});
    
    subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior: 'smooth'});
    .box,.foot{display: flex;background:#fdf;padding:500px 0} .foot{padding:250px}
    <input type="text" class="textfield" value="click here" id="subject" name="subject">
    
    <div class="box">
      Some content
      <textarea></textarea>
    </div>
    
    <input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
    
    <div class="foot">Some footer</div>
    #9746
    jaber-alshami
    Participant

    You just need:

    $("selector").get(0).scrollTo(0, 0)
    
    #9761
    vu-viet-hung
    Participant

    After finding the way to get my code work, I think I should make thing a bit clear:
    For using:

    $('html, body').animate({
       scrollTop: $("#div1").offset().top
    }, 2000);
    

    you need to be on top of the page since $("#div1").offset().top will return different numbers for different positions you scroll to. If you already scrolled out of the top, you need to specify the exact pageY value (see pageY definition here: https://javascript.info/coordinates).

    So now, the problem is to calculate the pageY value of one element. Below is an example in case the scroll container is the body:

    function getPageY(id) {
        let elem = document.getElementById(id);
        let box = elem.getBoundingClientRect();
        var body = document.getElementsByTagName("BODY")[0];
        return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
    }
    

    The above function returns the same number even if you scrolled somewhere. Now, to scroll back to that element:

    $("html, body").animate({ scrollTop: getPageY('div1') }, "slow");
    
Viewing 15 posts - 16 through 30 (of 31 total)
  • You must be logged in to reply to this topic.