Nima Bastani
Nima Bastani

Reputation: 41

what exactly is happening here in the 4th line?

I am editing my question as suggested in the comments to demonstrate a better overview on what make me confuse about the .on callback function in the following line:

$(document).ready(function(){
  $('.nav').on('click', 'li > a', function(){
    var $li = $(this).parent();
    $li.siblings().not($li.addClass('active')).removeClass('active');
  });
});

What is really happening in the line

$li.siblings().not($li.addClass('active')).removeClass('active');

I mean, Is it adding and removing active class base on their current state with not($li.addClass('active')) or it's just wrong syntax to achieve this goal.

Upvotes: -1

Views: 105

Answers (2)

Buh Buh
Buh Buh

Reputation: 7545

$li.addClass('active')

This returns $li, just in case you wanted to chain multiple functions together.

So

$li.siblings().not($li.addClass('active')).removeClass('active');

is the same as:

$li.addClass('active');
$li.siblings().not($li).removeClass('active');

Which means all the siblings of $li, which are not the $li itself. Which is silly because it was never its own sibling to begin with.

So let's simplify it to:

$li.addClass('active');
$li.siblings().removeClass('active');

Which says, add the active class to the li which had been clicked on and remove the class from the other lis.

Upvotes: 0

SirPilan
SirPilan

Reputation: 4847

Added your code and explained hover example.

$(document).ready(function(){
  
  $('.nav').on('click', 'li > a', function(){
    var $li = $(this).parent();
    $li.siblings().not($li.addClass('active')).removeClass('active');
  });
  
  $('.nav').on('mouseover', 'li > a', function(){
    var $li = $(this).parent(); // get parent of hovered <a> (<li>)
    $siblings = $li.siblings(); // get all siblings of <li> containing the hovered <a>
    $li.addClass('hover'); // add 'active' to <li> containing hovered <a>
    $siblings_except_clicked = $siblings.not($li); // get all siblings NOT <li> containing hovered a
    $siblings.removeClass('hover'); // remove 'active' class from every <li> except the one with hovered <a>
  });
  
  
});
ul.nav {
  margin: 0px pading: 0px;
}

ul.nav li {
  display: inline-block;
  text-align: center;
  width: 80px;
  border-bottom: 3px solid transparent;
  border-top: 3px solid transparent;
}

ul.nav li.active {
  border-bottom: 3px solid black;
}

ul.nav li.hover {
  border-top: 3px solid grey;
}

a {
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='nav'>
  <li class='active hover'><a href='#'>Entry A</a></li>
  <li><a href='#'>Entry B</a></li>
  <li><a href='#'>Entry C</a></li>
</ul>

Upvotes: -1

Related Questions