Stephanie Kim
Stephanie Kim

Reputation: 13

Little issue with div sticking to top of the page

http://jsfiddle.net/j2qjgob5/

   <div id="wrapper">
     <div id="new_country">
      <div id="new_country_text" >
       New Country
     </div>
    </div>
   </div>
  <div id="space"><br><br>blablablablabballabla</div>

#container {
padding: 100px 0 2500px;
}

#wrapper {
   width: 100%;
   height: 57px;
   border: solid;
}

#new_country {
  width: 162px;
  height: 42px;
  position: relative;
  background-color: #1abc9c;
  border-radius: 5px;
  top: 8px;
}

#new_country:hover {
    opacity: 0.8;
}

#new_country:active {
    box-shadow: 0px 0px 9px 4px #16a085 inset;
}

#new_country_text {
    position: absolute;
    width: inherit;
    height: inherit;
    top: 50%;
    text-align: center;
    line-height: 0;
    display: table;
    color: whitesmoke;
}

function fixDiv() {
    var $div = $("#wrapper");
    if ($(window).scrollTop() > $div.data("top")) {
        $('#wrapper').css({
            'position': 'fixed',
                'top': '0',
                'width': '100%'
        });
    } else {
        $('#wrapper').css({
            'position': 'static',
                'top': 'auto',
                'width': '100%'
        });
    }
}

$("#wrapper").data("top", $("#wrapper").offset().top); // set original position on load
$(window).scroll(fixDiv);

Every time the wrapper div sticks to the top, div below it kind of spazzes upwards and then the wrapper div twitches. How do I get the div to stick to the top smoothly, without affecting any other divs? Thanks.

Upvotes: 0

Views: 132

Answers (1)

jmore009
jmore009

Reputation: 12923

For one you need to clear the default margin from the document:

html,body{
   margin: 0;
   padding: 0;
}

Your JS is changing the width and height on .wrapper to:

$('#wrapper').css({'position': 'static', 'width': '100%', 'height': '57px', })  

But your CSS for .wrapper on page load is:

#wrapper {
   width: 50%;
   height: 44px;
   ...
}

Make them the same:

#wrapper {
   width: 100%;
   height: 57px;
   ...
}

FIDDLE

UPDATE 2

So the issue is the .wrapper becomes fixed which removes it from the flow of the document and that causes the #space section to just jump to the top of the page (because the header is no longer being recognized). A simpler way of doing all of this is to just add/remove a class like so:

if ($(window).scrollTop() > $div.data("top")) { 
    $('#wrapper').addClass("fixed"); 
}
else {
    $('#wrapper').removeClass("fixed"); 
}   

and then in your CSS you can add your rules and also adjust the padding of #space since it's a sibling:

.fixed{
   position: fixed;
   top: 0;
   //any other styles
}

.fixed + #space{ //target sibling #space
   padding: 57px 0 0; //set padding to height of .wrapper
}

NEW FIDDLE

Upvotes: 1

Related Questions