Set DIV between page head and footer

0

Well, I have a div that stays fixed when scrolling the page, but I want it to scroll again with the page before it reaches the wall. The code below causes that when reaching the height of the scroll 300 the div is fixed. The problem is that when I roll the page to the radapé the div overlaps the footer because it is fixed so I want the div to scroll back to the page before it reaches the footer for example 300px from the bottom.

My code looks like this:

$(function(){

    var jElement = $('.element');

    $(window).scroll(function(){
        if ( $(this).scrollTop() > 300 ){
            jElement.css({
                'position':'fixed',
                'top':'200px'
            });
        }
        else{
            jElement.css({
                'position':'relative',
                'top':'auto'
            });
        }
    });
      
    });
 .head {windth:100%; height:100px;}

.conteudo{
  height:600px;float:left;width:50%;
}
.element{float:left;
  width: 30%;
  padding: 3em;
  background: #f9f9f9;
  border: 1px solid #ddd;
  border-top: #dc0000 3px solid;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="head">
head
</div>    
<div class="conteudo">
    conteudo
</div>
<div class="element">
    div a ser fixada 
</div>
    
asked by anonymous 25.05.2017 / 18:02

1 answer

2

$(window).load(function() {
  function checkOffset() {
    if ($('#element').offset().top + $('#element').height() >=
      $('#footer').offset().top - 100)
      $('#element').css('position', 'absolute');
    if ($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
      $('#element').css('position', 'fixed');
  }
  $(document).scroll(function() {
    checkOffset();
  });
});
div.body {
  width: 100%;
  height: 2000px;
  background: #C0C0C0;
  position: relative;
}

div#element {
  float: left;
  position: fixed;
  left: 10px;
  bottom: 100px;
  width: 30%;
  padding: 3em;
  background: #f9f9f9;
  border: 1px solid #ddd;
  border-top: #dc0000 3px solid;
  text-align: center;
}

div#footer {
  width: 100%;
  height: 200px;
  background: #eee;
}

.head {
  windth: 100%;
  height: 100px;
}

.conteudo {
  height: 600px;
  float: left;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="body">
  <div class="head">
    head
  </div>
  <div class="conteudo">
    conteudo
  </div>
  <div id="element">
    div a ser fixada
  </div>
</div>

<div id="footer">
  Rodape
</div>
    
25.05.2017 / 18:32