0

How can I center the div using the window scroll event? I am searching for this answer for a long time. Any help would be appreciated.

$(window).scroll(function() {
  var offSetTop = $("#ifOne").offset().top;
  var positionTop = $("#ifOne").position().top;
  var windowHeight = $(window).height();
  var scrollTop = $(window).scrollTop();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">Some Content</div>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Billy
  • 825
  • 6
  • 21
  • 36
  • 4
    I'm not quite sure what you're asking, but if you want to keep content in the same position when scrolling just use CSS: `position: fixed` – Rory McCrossan Apr 13 '18 at 09:46
  • Please do refer this link.Hope this helps you. https://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen – Learner Apr 13 '18 at 09:50
  • @ Rory McCrossan, thanks for the reply. I want to center the div, can we do the same using jquery? – Billy Apr 13 '18 at 09:50
  • @Billy JQuery is built on top of the standard web platform. You can do anything in CSS, HTML or Javascript as normal . – Andrew Bone Apr 13 '18 at 10:30

1 Answers1

1

A simple demo shows how to center the div:

$(window).scroll(function() {
  var offSetTop = $("#div1").offset().top;
  var positionTop = $("#div1").position().top;
  var windowHeight = $(window).height();
  var scrollTop = $(window).scrollTop();
  var top = scrollTop + (windowHeight - $("#div").height())/2
  $('#div1').css('top', top)
});
#container{
  position: relative;
  height: 200vh;
  width: 100%;
}

#div1{
  position: relative;
  margin: 0 auto;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="div1">
    Some Content
  </div>
</div>
Hikarunomemory
  • 4,237
  • 2
  • 11
  • 21