JQuery scroll down to element id

I am trying to create a button that scrolls a page to a given element id. I currently have a Fiddle , but I would like it to be slightly different:

  • Scroll to the bottom of the blue div ( #three) at the bottom of the page, not up from scrolling the div to the top of the page.
  • Only scroll if the item is not displayed on the screen to the user.

How can I do that?

HTML

<button id="btn">CLICK</button>
<div class="test" id="one"></div>
<div class="test" id="two"></div>
<div class="test" id="three"></div>
<div class="test" id="four"></div>

CSS

.test {
    width: 100%;
    height: 400px;
}

#one { background: red; }

#two { background: green; }

#three { background: blue; }

#four { background: yellow; }

Js

$("#btn").click(function() {
    $('html, body').animate({
        scrollTop: $("#three").offset().top
    }, 500);
});
+4
source share
2 answers

Ok, here is the first part -

$('html, body').animate({
    scrollTop: ($("#three").offset().top + $("#three").height() - $(window).height())
}, 500);

just a little math, and you can easily understand what is going on.

and for the second part -

if(($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < $(window).scrollTop() + $(window).height())) { ...
}

, , scrollTop() + height() (, ).

fiddle

UPDATE: , , #three, scrollTop() . , -

var eloffbottom = $('#three').offset().top + $('#three').height();
var winoffbottom = $(window).scrollTop() + $(window).height();
if((($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < winoffbottom)) || ((eloffbottom >= $(window).scrollTop()) && (eloffbottom < winoffbottom))) {
                alert('already in view');
    }

Fiddle !

, jQuery, . . . - $('#three').visible() - true false.

+5

, , .

$("#btn").click(function() {
  var winHeight = $(window).height(),
    topOffset = $("#three").offset().top,
    elementHeight = $('#three').height()
  var top = topOffset - winHeight + elementHeight;

  $('html, body').animate({
    scrollTop: top
  }, 500);
});
.test {
  width: 100%;
  height: 400px;
}
#one {
  background: red;
}
#two {
  background: green;
}
#three {
  background: blue;
  border: solid 3px gray;
}
#four {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button id="btn">CLICK</button>
<div class="test" id="one"></div>
<div class="test" id="two"></div>
<div class="test" id="three"></div>
<div class="test" id="four"></div>
Hide result
+2

Source: https://habr.com/ru/post/1609130/


All Articles