Reputation: 1
i try to fix on the top: div with id "sticky" after scrolling, but doesnt work,ithink that the java script code is the problem. can someone help me to do it.
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
$('#sticky-anchor').height($('#sticky').outerHeight());
} else {
$('#sticky').removeClass('stick');
$('#sticky-anchor').height(0);
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
#sticky {
background-color: red;
height:140px;
z-index: 1;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sticky-anchor"></div>
<div id="sticky">
<ul class="menu">
<li><a href="#">Nos Produits</a></li>
</ul> <!-- ul end .menu -->
</div>
Upvotes: 0
Views: 699
Reputation: 36
You can achieve this by using JQuery and JQuery Magnet plugin. https://github.com/jtannous/JQuery-Magnet
$(".fix-me-to-top-after-scroll").magnet();
<div class="fix-me-to-top-after-scroll">CONTENT HERE</div>
Upvotes: 0
Reputation: 22919
You need to include jQuery:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
$('#sticky-anchor').height($('#sticky').outerHeight());
} else {
$('#sticky').removeClass('stick');
$('#sticky-anchor').height(0);
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
body {
height: 2000px;
background: grey;
}
#sticky {
background-color: red;
height: 140px;
z-index: 1;
}
#sticky.stick {
position: fixed;
top: 0;
/* added for demo */
left: 0;
right: 0;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sticky-anchor"></div>
<div id="sticky">
<ul class="menu">
<li><a href="#">Nos Produits</a></li>
</ul>
<!-- ul end .menu -->
</div>
Upvotes: 1