Search code examples
javascriptjqueryhtmlscrollsmooth-scrolling

How to smooth scroll two elements at the same time using scrollIntoView()?


I am trying to smooth scroll two divs at the same time using scrollIntoView(). I have tried these two ways, but only the last div called scrolls:

Attempt 1: function with two parameters: only the second parameter scrolls

function precedent_scroll(link, section) {
  document.getElementById(link).scrollIntoView({behavior: "smooth"});
  document.getElementById(section).scrollIntoView({behavior: "smooth"});
}

Attempt 2: calling function back to back: only "section2_IDname" scrolls

function precedent_scroll(section) {
  document.getElementById(section).scrollIntoView({behavior: "smooth"});
}

$("#id").click(function() {precedent_scroll("section1_IDname"), precedent_scroll("section2_IDname")});

Is this possible with only using scrollIntoView()?


Solution

  • Got it to work with jQuery:

    function double_scroll(id1, id2) {
      var id1_parent_st = $([id1 parent]).scrollTop();
      var id2_parent_st = $([id2 parent]).scrollTop();
      $([id1 parent]).animate({
        scrollTop: $(id1).position().top + id1_parent_st
      }, 500, function(){
      });
      $([id2 parent]).animate({
        scrollTop: $(id2).position().top + id2_parent_st
      }, 500, function(){
      });
    }
    
    $([div]).click(function() {double_scroll("#p1_link", "#p1_section")});