0

I am looking to get a method to dynamically get scroll position height instance as long as I scroll page, update CSS as well.

I used this snippet, however the value of bodyHeight is fixed on first page load, not updating while scroll and the CSS as well.

var bodyHeight = $('body').scrollTop();
var fixedTop = bodyHeight - 50;//(50)topnav height
$('.fixed-inner').css('top', fixedTop + 'px');

4 Answers4

1

Try with something similar to:

<!DOCTYPE html>
<html>
<head>
    <style>
        div#main{
            background-color:green;
        }
    </style>
</head>
<body>
<br /><br /><br /><br />
<div id="main" style="height:300px; position:relative; overflow:scroll;">
    <div class="stairsImage" style="height:500px; width:300px; background-color:yellow; ">
       <h1 id="testName">Lorem Ipsum</h1>
    </div>
</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> 

<script>
$(document).ready(function() {
//-------------------------
   $(window).scroll(function(){
      var wScroll = $(this).scrollTop();
        console.log(wScroll);

      $("#testName").css({'transform' : 'translate(0px, '+ wScroll +'px)'});

   });  
//-------------------------
   $("div#main").scroll(function(){
      var wScroll = $(this).scrollTop();
        console.log(wScroll);

      $("#testName").css({'transform' : 'translate(0px, '+ wScroll +'px)'});

   }) 
});
</script>       
</body>
</html>
Javier Haro
  • 1,255
  • 9
  • 14
0

Try this

var bodyHeight = $(window).scrollTop();
var fixedTop = bodyHeight - 50;//(50)topnav height
$('.fixed-inner').css('top', fixedTop + 'px');
Ahmadbaba46
  • 221
  • 2
  • 7
0

I hope this helps you

$(window).scroll(function () { 
    //You've scrolled this much:
       $('div').text("The scrool position is " + $ (window).scrollTop() + " pxs");
});

jsFiddle here

good luck :)

Luan
  • 81
  • 7
0

You need to recalculate the bodyHeight when you scroll the page, and there is an jquery event for that, and you can have bodyHeight as a global variable.

var bodyHeight = $('body').scrollTop();
$(window).scroll(function () { 
    //recalculate the value every time the user scroll
    var bodyHeight = $(window).scrollTop();
    //doSomething()
});

further reading:

Community
  • 1
  • 1
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85