Home > front end >  How to center active list-item in horizontally-scrollable ordered-list?
How to center active list-item in horizontally-scrollable ordered-list?

Time:03-29

Details:

I'm trying to simultaneously center the active list-item inside a vertically-scrollable ordered-list and the active list-item inside a horizontally-scrollable ordered-list.

Problem:

I get the expected result for my vertically-scrollable ordered-list as the active list-item aligns nicely in the center.

However, the active list-item inside the the horizontally-scrollable ordered-list "sticks" to the right hand side, and does not align nicely in the center...

problem visual

I Tried:

$("ol > li.active").each(function() {
  $(this)[0].scrollIntoView({block: "center"});
})

I fail to understand why this approach is not working...

Current Code:

$('button').click(function() {
    $("ol > li.active").each(function() {
      $(this)[0].scrollIntoView({block: "center"});
    })
});
ol {
  position: relative;
  border:1px solid silver;
  margin:0;
  padding:0;
  margin-top:20px;
}

ol.vertical {
  height:100px;
  width:200px;
  overflow-y: auto;
}

ol.horizontal {
  width:200px;
  height:50px;
  display: flex;
  overflow-x: auto;
}

li {
  padding:5px 20px;
}

ol.horizontal li {
  display: inline-block;
  min-width: auto;
  white-space: nowrap;
  list-style-type: none;
}

li.active {
color: blue;
background: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>test</button>

<ol >
  <li>01</li>
  <li>02</li>
  <li>03</li>
  <li>04</li>
  <li>05</li>
  <li>06</li>
  <li >07</li>
  <li>08</li>
  <li>09</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ol>

<ol >
  <li>01</li>
  <li>02</li>
  <li>03</li>
  <li>04</li>
  <li>05</li>
  <li>06</li>
  <li >07</li>
  <li>08</li>
  <li>09</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ol>

CodePudding user response:

$('button').click(function() {
    $("ol > li.active").each(function() {
      $(this)[0].scrollIntoView({behavior: 'auto', block: 'center', inline: 'center'});
    })
});

You are missing some properties to function properly

  • Related