Rick Jellema Rick Jellema - 4 months ago 21
CSS Question

Why doesn't my jquery fixed div work?

I'm trying to make a portfolio site for my course, but everytime I try to use this jquery code it doesn't work however it does in the fiddle http://jsfiddle.net/gxRC9/2701/
what it's suposed to do is that after scrolling down the header should fix itself to the top, meaning it will scroll down with you.
jquery code:

$(document).ready(function(){

$(window).scroll(function(){
var bier = $("#header"), scroll = $(window).scrollTop();

if (scroll >= 100) bier.addClass("fixed");
else bier.removeClass("fixed");
});

});

Answer

It actually does work. In your jsFiddle, you were alternating using the varname 'sticky' and 'bier'.

jsFiddle Demo

$(document.ready(function() {

  $(window).scroll(function() {
    var bier = $('#header'),
        scroll = $(window).scrollTop();

    if (scroll >= 100) bier.addClass('fixed');
    else bier.removeClass('fixed');
  }); //window.scroll

}); //END document.ready
body {margin:0;}
section {height:2000px;padding-top:100px;}
#header{width:1903px;height:60px;background-color:#333;float:left;z-index:11;border-bottom:solid #545454 6px;}
.sticky {background:orange;}
.fixed {position:fixed;top:0;left:0;width:100%;}

@media only screen and (max-width:1920px) {ul {list-style-type:none;margin:0;margin-top:7px;margin-left:25px;padding:0;padding-left:25px;overflow:hidden;background-color:#333;}
li {float:left;}
li a {display:block;color:white;text-align:center;padding:14px 16px;text-decoration:none;font-size:20px;}
/* Change the link color to #111 (black) on hover */
li a:hover {background-color:#111;text-decoration:underline;}
@media only screen and (max-width:1440px) {ul {list-style-type:none;margin:0;margin-top:7px;margin-left:25px;padding:0;padding-left:25px;overflow:hidden;background-color:#333;}
	li {float:left;}
	li a {display:block;color:white;text-align:center;padding:14px 16px;text-decoration:none;font-size:20px;}
	/* Change the link color to #111 (black) on hover */
	li a:hover {background-color:#111;text-decoration:underline;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<section>
  <div id="header">
    <ul>
      <li><a href="index.php">Home</a>
      </li>
      <li><a href="index.php">FaQ</a>
      </li>
      <li><a href="index.php">Portfolio</a>
      </li>
      <li><a href="index.php">Contact</a>
      </li>

    </ul>
  </div>
</section>

The most probable reason why it doesn't work on your local system is one of these two possibilities:

(1) Did you include the reference to load the jQuery library?

(2) Did you wrap your scroll in a

$(document).ready(function(){ 
    //all code here
}); 

wrapper function?

Comments