Next Slide 1: Why is it necessary to use variables here?


#1



https://www.codecademy.com/courses/web-beginner-en-seyrq/0/4?content_from=make-an-interactive-website%3Ajquery-effects#

Why does the following code not work without variables?

$('.arrow-next').click(function(){
     $('.active-slide').fadeOut(600).removeClass('active-slide');
     $('.active-slide').next().fadeIn(600).addClass('active-slide');
});

However if I use variables it works:

$('.arrow-next').click(function(){
    var currentSlide = $('.active-slide');
    var nextSlide = currentSlide.next();
    currentSlide.fadeOut(600).removeClass('active-slide');
    nextSlide.fadeIn(600).addClass('active-slide');
});

#3

Hi @lordperro7,

$('.active-slide').fadeOut(600).removeClass('active-slide');
$('.active-slide').next().fadeIn(600).addClass('active-slide');

The reason that doesn't work is because on line 1, you've removed the active-slide class from all elements with that class. Then on line 2, you're trying to select the element(s) with the active-slide class, but, since you just removed the class from all elements with it, your $('.active-slide') selector will not return any elements, which is why it doesn't work.

The second version with variables stores the element, so even after modifying it's classes, the computer still knows which element you're trying to find the next() of, so that method does work.

Make sense? :slight_smile:


#4

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.