I'm working on Wordpress and I need to make a div fixed on the top when the page is scrolled. The div ( .details ) must have a percentage width for responsive reasons. I found a javascript to stop the div ( .details ) when it is 40px from the top, switching it from a relative position to a fixed one. It has a 25% width when in relative position, but when it become fixed, the 25% width is now based on the window and it isn't based on the parent element ( .entry ), that is smaller than the window, so it become larger when I scroll. These are the CSS and the Javascript ( .carousel is the other div inside .entry , it's on the left of .details):
<style>
.entry { position:relative; width:100%; }
.carousel { width:70%; height: auto; position: relative; float: left; margin-top: 0px;}
.details { width: 25px; height: 100%; float: right; margin-top: 0px; line-height: 20px;}
</style>
<script>
$(window).scroll(function(){
if ($(window).scrollTop() >= 90){
$('.details').css({position:'fixed',right:40,top:40,width:'25%'});
} else {
$('.details').css({position:'relative',right:0,top:0,width:'25%'});
}
});
</script>
I need to make the width of .details div based on .entry and not on the window. Anyone can find mistakes or need something else? I'm not a pro in Javascript. Thank you all!
The only way to do this is by setting the .details
width with JavaScript. Try this:
$(window).scroll(function(){
if($(window).scrollTop() >= 90){
$('.details').css({position:'fixed',right:40,top:40});
} else {
$('.details').css({position:'relative',right:0,top:0});
}
});
// set the width of the details div when window resizes
window.addEventListener('resize', function(){
var $el = $('.details')
$el.width( $el.parent().outerWidth() * .25 )
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.