In this case, I have a data list as shown in the image below. I want the list with class active to be at the top, instead of refreshing the top order again.
Prerequire
- Function Javascrip
offset().top
,.toFixed(0)
danscrollTop()
- Jquery
1. HTML Structure
The first thing in doing script generation is to figure out what parts script needs to handle/capture in this case; id="myTabContent"
and class="list-active"
.
<div id="myTabContent">
<div class="px-3">
<div class="row border-bottom">
<div class="col-2"><b>Hari</b></div>
<div class="col-5"><b>Tanggal</b></div>
<div class="col-5"><b>Ayat</b></div>
</div>
<a href="#">
<div class="row list list-active">
<div class="col-2">260</div>
<div class="col-5">2021-12-30</div>
<div class="col-5">Why 22</div>
</div>
</a>
<a href="#">
<div class="row list ">
<div class="col-2">259</div>
<div class="col-5">2021-12-29</div>
<div class="col-5">Why 21</div>
</div>
</a>
... dst
</div>
</div>
2. Position Script Handle
In handling positions, we must first know the position data of the initial list(conNum
) and list active(itmNum
). The data obtained from the offset().top
function is in the form of a position number, while toFixed(0)
is a function to round the number. Then after getting it, just do scrollTop(difference between itmNum position and conNum)
. In step by step:
- Declaration of object container lists
- Declaration of position
conNum
anditmNum
- Execute the
scrollTop()
. function
var con = $("#myTabContent"),
conNum = con.offset().top.toFixed(0),
itmNum = $("#myTabContent .list-active").offset().top.toFixed(0);
con.scrollTop(itmNum-conNum-15);
DONE
Top comments (1)
Kereeeeeen