Issue
I have a ul
with fixed height, which contian dynamic number of li
elements, if too many a scrollbar appaers. You can select a li
element by clicking on it.
What I want is the li
element that is active to be fixed at the top if scrolling aboveit or fixed at the bottom if scrolling below it, so the active li
element is always showing, and the other li
elements just scrolls past the active one.
I have made a plunker. I am using Angular, and I dont know if this can be solved just using CSS or if I need a directive etc. for this.
Html:
div class="parent">
<div class="child1">
<input ng-model="vm.query" type="text" placeholder="Search" />
<ul >
<li ng-repeat="todo in todos" ng-class="{'active': todo.active}" ng-click="activeTodo($index)">
<a>{{todo.name}}</a>
</li>
</ul>
</div>
CSS:
.parent{
display: flex;
}
.child1{
background-color: #eeeeee;
height: 500px;
overflow:scroll;
}
.active{
background-color: red;
position:fixed;
}
Thanks in advance!
Solution
I managed this using some CSS and making a directive.
Made a plunker here.
I made a directive which every li
element got. Then with jquery in the directive I get the necessary elements like the div
which have the scroll, the current li
element etc.
Two booleans for checking if the li
is fixed at the top or bottom. And then just check if the current scrollPosition(scrollTop) is higher or lower then the current li
element. And it also check so the li
element got the active boolean attached too it.
return {
restrict: 'A',
link: function($scope, element, attributes){
var scrollDiv = $('#scrollDiv'),
liElement = element,
liElementTop = parseInt(liElement.offset().top),
scrollDivTop = parseInt(scrollDiv.offset().top),
isFixedTop = false,
isFixedBottom = false;
liElement.width(scrollDiv.width());
scrollDiv.on('scroll', function(){
var scrollTop = scrollDiv.scrollTop();
if (!isFixedBottom && !isFixedTop && scrollTop <= liElementTop - (scrollDivTop+(scrollDiv.height()-liElement.height())) && liElement.hasClass("active")) {
isFixedBottom = true;
liElement.css({'position': 'fixed', 'top': scrollDivTop+(scrollDiv.height()-liElement.height()+1),'list-style-type':'none','z-index':'10'});
} else if (isFixedBottom && !isFixedTop && scrollTop >= liElementTop - (scrollDivTop+(scrollDiv.height()-liElement.height()))) {
isFixedBottom = false;
liElement.css({'position': 'static', 'top': 0});
}
else if (!isFixedTop && !isFixedBottom && scrollTop >= liElementTop - scrollDivTop && liElement.hasClass("active")) {
isFixedTop = true;
liElement.css({'position': 'fixed', 'top': scrollDivTop,'list-style-type':'none','z-index':'10'});
}
else if (isFixedTop && !isFixedBottom && scrollTop <= liElementTop - scrollDivTop) {
isFixedTop = false;
liElement.css({'position': 'static', 'top': 0});
}
})
}
};
Answered By - Devl11
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.