Sam Assoum Sam Assoum - 2 months ago 6
Javascript Question

Adding / Removing classes to list items

So I've built this little slider with left and right nav arrows and I'm having trouble with my attempts to add a class to the list items in the ul.

Basically I want to add a class to the next item on the list, while removing that class from the previous item at the same time.

Now the thing is, I've got this working perfectly, but only in the right direction, not left.

Note that list items sort themselves properly in both directions, it's just adding the class to the left that doesn't:

$('.home_slider > li:first').addClass('active-slide');

$('#slider_arrow_right').click(function(){
$('.active-slide').next().addClass('active-slide').prev().removeClass('active-slide');
$('.home_slider > li:last').after($('.home_slider > li:first'));
});

$('#slider_arrow_left').click(function(){
$('.home_slider > li:first').before($('.home_slider > li:last'));
$('.active-slide').next().addClass('active-slide').prev().removeClass('active-slide');
});


I've tried changing up the #slider_arrow_left click function in a few different ways, but it still adds the class in the same list direction as the right arrow, or just doesn't work at all. Any help is much appreciated!

UPDATED:

Here's a JSFiddle showing the issue: Fiddle

Answer

Use the css child selector. It will make your life easier in this use case and reduce your code.

JavaScript

$('#right').click(function(){
  $('.home_slider > li:last').after($('.home_slider > li:first'));
});

$('#left').click(function(){
  $('.home_slider > li:first').before($('.home_slider > li:last')); 
});

CSS

.nav_buttons{
  display:inline-flex;
  color:#fff;
  padding:16px;
}
#left{
  width:40px;
  height:40px;
  margin-right:8px;
  background:grey;
  padding:4px;
}
#right{
  width:40px;
  height:40px;
  background:grey;
  padding:4px;
}
.home_slider{
  display:inline-flex;
  list-style-type:none;
}
.home_slider li{
  width:80px;
  height:80px;
}
#one{
  background:blue;
}
#two{
  background:red;
}
#three{
  background:yellow;
}
#four{
  background:green;
}
.home_slider>li:first-child{
   border:8px solid black;
}

Also if you need to get the first child if it holds any meaning to be used later in code.

var firstChild = $('.home_slider li:first-child');

To do animations just change the css.

Add this to css

@keyframes FadeIn { 
  from { opacity: 0; }
  to   { opacity: 1; }
}

And add this to the child selector already there.

animation: FadeIn 1s linear;
Comments