Reputation: 1133
I want to add a css class to parent if the last child is in visible range.
HTML
<div class="container">
<div class="left"></div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
More items will be here
<li id="last-child">Last item</li>
</ul>
<div class="right">
<p> Some content </p>
</div>
</div>
CSS
.left{position:absolute;}
.left-fixed{position:fixed;}
So when the #last-child is in visible range I want to add css class .left-fixed to div class .left
3 things I want to achieve.
#last-child
is visible add css class .left-fixed
#last-child
visible css class .left-fixed
and remove if not visible#last-child
visible css class .left-fixed
and remove if not visible on scroll.Can someone point me a way to achieve this? I search but couldn’t find an answer to these questions. Appreciate your time.
Upvotes: 0
Views: 821
Reputation: 1
You can use .getBoundingClientRect()
, window.innerHeight
const last = $("#last-child")[0];
const left = $(".left");
$(window).on("resize", function(event) {
if ((last.getBoundingClientRect().top < -(last.clientHeight)
|| last.getBoundingClientRect().bottom > window.innerHeight)) {
if (!left.is(".left-fixed")) {
left.addClass("left-fixed");
}
} else {
if (left.is(".left-fixed")) {
left.removeClass("left-fixed")
}
}
}).resize();
jsfiddle https://jsfiddle.net/hfv89veu/3/
Upvotes: 2
Reputation: 2455
Try this:
$(document).ready(function(){
CheckLastVisible();
$(window).resize(function() {
CheckLastVisible();
});
});
function CheckLastVisible(){
if($("#last-child").is(":visible")){
$("#last-child").parents(".left:eq(0)").addClass("left-fixed");
}
else{
$("#last-child").parents(".left:eq(0)").removeClass("left-fixed");
}
}
Upvotes: 1
Reputation: 693
You can do like below,
$(document).ready(function(){
iflastvisible();
$(window).resize(function() {
iflastvisible();
});
});
function iflastvisible(){
if($("#last-child").is(":visible")){
$("#last-child").parents(".left:eq(0)").addClass("left-fixed");
}
else{
$("#last-child").parents(".left:eq(0)").removeClass("left-fixed");
}
}
Upvotes: 1
Reputation: 3384
For this you have to use jquery :
//When window load if #last-child is visible add css class .left-fixed
if($("#last-child").is(":visible")){
$(this).parent().addClass("left-fixed");
}
//If window is resize #last-child visible css class .left-fixed and remove if //not visible
if($("#last-child").is(":visible")){
$(this).parent().addClass("left-fixed");
}
else{
$(this).parent().removeclass("left-fixed");
}
// there is one more way to do this without using jquery:
.last-child{ display:none; }
.parent:hover .last-child{ display:block; }
Upvotes: 1
Reputation: 4378
Very simple!
jQuery:
if($("#last-child").is(":visible")){
$(".left").addClass("left-fixed");
}
Upvotes: 2