Skip to content
Advertisement

How to keep selected item top of a sidebar menu after reloading a page

I have a scrolling sidebar menu.so when, I select a menu items it should be showed top position of the sidebar. No problem about set active menu. I got it. but I can’t set top position of the sidebar. Please don’t suggest jQuery. rather suggest me vanilla JavaScript here is some code reference

.sidebar{
    height:100px
    overflow-y:scroll;
}
.sidebar ul li{
    padding:30px;
}
<!-- CSS -->

 <!-- html  -->
<div class="sidebar">
  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item7</li>
    <li>item8</li>
    <li>item9</li>........
    <li>item100</li>
  </ul>
</div>

Advertisement

Answer

Pure CSS solution using :target pseudo-class, flexbox layout with the order property.

.sidebar {
  background-color: #ddd;
  height: 200px;
  overflow-y: scroll;
}
.sidebar ul {
  display: flex;
  flex-direction: column;
  margin: 0;
}
.sidebar li {
  padding: 1em;
  order: 1;
}
.sidebar :target {
  background-color: #aaa;
  order: 0;
}
<div class="sidebar">
  <ul>
    <li id="item1"><a href="#item1">item1</a></li>
    <li id="item2"><a href="#item2">item2</a></li>
    <li id="item3"><a href="#item3">item3</a></li>
    <li id="item4"><a href="#item4">item4</a></li>
    <li id="item5"><a href="#item5">item5</a></li>
    <li id="item7"><a href="#item7">item7</a></li>
    <li id="item8"><a href="#item8">item8</a></li>
    <li id="item9"><a href="#item9">item9</a></li>
    <li id="item100"><a href="#item100">item100</a></li>
  </ul>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement