student42 student42 - 7 days ago 7
CSS Question

Jquery not responding on scroll

Im trying to make an element change position to fixed after scrolling a certain point, however nothing happens when scrolling. I have

<script src="stiler/jquery-3.1.1.min.js"></script>
referencing to jquery in
<head>
. When scrolling nothing happens at all. No error messages in DOM console, no nothing.



$(document).ready(function(){
var wrap = $('#header-wrap');

$(window).on('scroll', function(e) {

if (this.scrollTop > 147) {
wrap.addClass('fix');
} else {
wrap.removeClass('fix');
}

});
});

body {
background-color: grey;
margin: 0;
min-height: 300vh;
}
#header-wrap {
top: 0;
width: 100%;
}
#redline {
top: 0;
left: 0;
width: 100%;
position: fixed;
height: 10px;
background-color: #b30027;
z-index: 99;
}
#velkommen {
height: 300px;
width: 100%;
background-color: white;
position: relative;
top: 10px;
margin-bottom: -60px;
}
#header {
position: relative;
left: 0;
width: 100%;
background-color: white;
height: 60px;
}
.fix #header {
position: fixed;
top: 10px;
}
h1 {
margin: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header-wrap">
<div id="redline"></div>
<div id="velkommen"></div>
<div id="header"> <!--This tag should get class="fix"-->
<h1>#HEADER</h1>
</div> </header>




Answer

The problem is you are using this wrong it needs to be $(this)

$(document).ready(function(){
var wrap = $('#header-wrap');

$(window).on('scroll', function(e) {

  if ($(this).scrollTop > 147) {
    wrap.addClass('fix');
  } else {
    wrap.removeClass('fix');
  }

});
});

Here's a fiddle to show it working: https://jsfiddle.net/5sdahw83/

Here's some further reading on this vs $(this) jQuery $(this) vs this