1

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>
student42
  • 161
  • 1
  • 2
  • 9
  • You have some discrepancies in your example. In your description of the problem you have jQuery v3.1.1 listed, but in your code snippet you have 2.1.1. There's also a typo in your HTML in the last closing ` – disinfor Nov 30 '16 at 21:02
  • The code was not wrapped in '$(document).ready()', no. It is now, with the exact same code as in the snippet. The snippet did not have a 3.1.1 jquery listed. – student42 Nov 30 '16 at 21:10

1 Answers1

0

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: What's the difference between '$(this)' and 'this'?

Community
  • 1
  • 1
disinfor
  • 10,865
  • 2
  • 33
  • 44