Question about next()


#1

Can anyone explain me why this code for pressing 'n' key work only with variables?

   else if(event.which===110){
        var currentArticle=$('.current');
        var nextArticle=currentArticle.next();
        currentArticle.removeClass('current');
        nextArticle.addClass('current')
    }

I guess this should be the shame thing, but it doesn't work.

else if(event.which===110){
//var currentArticle=$('.current');
//var nextArticle=currentArticle.next();
$('.current').removeClass('current');
$('.current').next().addClass('current')
}


#2

Hey Ionutch,

So first, you select all elements with the current class, then you remove the class current. Then, you select the .current article - but wait, there isn't a current article. Since no elements have the current class anymore (because we removed it on line 1 shown above), we can't select .current.

With the variables, we select the correct elements, then do stuff with them. Since the selection happens before we modify anything when we use a variable, everything works smoothly :slight_smile:

Does this help?


currentArticle and nextArticle formatting question
#3

Istvan, you are amazing!
I get it now! I found a solution that works without variables:

        $('.current').next().addClass('current')
        $('.current').prev().removeClass('current');

Thanks!


#4

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