Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twin unordered lists

So i have this structure:

  <ul>
      <li class="paginator"><a class="active">1</a></li>
      <li class="paginator"><a>2</a></li>
      <li class="paginator"><a>3</a></li>
  </ul>
  ... bunch of html code
  <ul>
      <li class="paginator"><a class="active">1</a></li>
      <li class="paginator"><a>2</a></li>
      <li class="paginator"><a>3</a></li>
  </ul>

Which is an unordered anchor, every time the user clicks on an anchor it becomes of the active class. My question is: What's the best way to duplicate this effect on both anchors. So far, when i click on the anchor 2 of the bottom, it succesfully get the active class, but the anchor 2 of top doesn't. Is there a way to have something like twin or cloned elements?

like image 237
Julio Bastida Avatar asked Aug 08 '26 16:08

Julio Bastida


1 Answers

You can get the index of the clicked li.paginator element, and set the active class to any other li.paginator with the same index using nth-child, that way the class gets added to both UL's

var lis = $('.paginator').on('click', function(e) {
	e.preventDefault();
    var idx = $(this).closest('li').index();
    
	lis.find('a').removeClass('active');
    lis.filter(':nth-child('+(idx+1)+')').find('a').addClass('active');
});
a {cursor : pointer}
a.active {
    text-decoration: underline;
    color: red!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
      <li class="paginator"><a class="active">test 1</a></li>
      <li class="paginator"><a>test 2</a></li>
      <li class="paginator"><a>test 3</a></li>
  </ul>
  <!-- ... bunch of html code -->
  <ul>
      <li class="paginator"><a class="active">test 1</a></li>
      <li class="paginator"><a>test 2</a></li>
      <li class="paginator"><a>test 3</a></li>
  </ul>
like image 56
adeneo Avatar answered Aug 10 '26 06:08

adeneo