Changing if statement to a switch

Hi,

I’m trying to change this if statement to a switch like this:

Before

if ($(this).attr('id') === 'right') {
			if (tabindex === slides) {
				tabindex = 1;
				move = '+=' + windowWidth * (slides - 1);
			} else {
				tabindex += 1;
				move = '-=' + windowWidth;
			}
		} else {
			if (tabindex === 1) {
				tabindex = slides;
				move = '-=' + windowWidth * (slides - 1);
			} else {
				tabindex -= 1;
				move = '+=' + windowWidth;
			}
		}

After

if ($(this).attr('id') === 'right') {

			switch (tabindex) {
			case (tabindex === slides):
				tabindex = 1;
				move = '+=' + windowWidth * (slides - 1);
				break;
			default:
				tabindex += 1;
				move = '-=' + windowWidth;
			}

		} else {
			switch (tabindex) {
			case (tabindex === 1):
				tabindex = slides;
				move = '-=' + windowWidth * (slides - 1);
				break;
			default:
				tabindex -= 1;
				move = '+=' + windowWidth;
			}

But the result is not the same.
What am I doing wrong? What is the right solution?

Thanks

Why?

That’s stupid. just use

this.id

I changed $(this).attr(‘id’) to this.id now.
Thanks for it.

The reason I need to do that is that the linting of the JavaScript is asking for it with this error:

59:4 error unexpected if as the only statement in an else block

can you post the full linter message (if it’s not the full one)?

and which is line 59?

This is the code:

$('.arrow').click(function () {
		var windowWidth = $('.js-carousel').width();

		if (this.id === 'right') {
			if (tabindex === slides) {
				tabindex = 1;
				move = '+=' + windowWidth * (slides - 1);
			} else {
				tabindex += 1;
				move = '-=' + windowWidth;
			}
		} else {
			if (tabindex === 1) {
				tabindex = slides;
				move = '-=' + windowWidth * (slides - 1);
			} else {
				tabindex -= 1;
				move = '+=' + windowWidth;
			}
		}

		$('.slider').animate({left: move});
		$('.circle').fadeOut().remove();
		$('<span class=\'circle\'></span>').appendTo('ul.carousel-page li:nth-child(' + tabindex + ')').hide().fadeIn();
	});

This is the full linting error message:

63:4 error unexpected if as the only statement in an else block

Line 63 is this line:

if (tabindex === 1) {
1 Like

yupp, you can restructure that easily.

instead of

} else {
    if () {
        // ...
    }
} 

use

} else if () {
    // ...
} 
3 Likes

Now I changed it to this and it seems to be working:

if (this.id === 'right') {
			if (tabindex === slides) {
				tabindex = 1;
				move = '+=' + windowWidth * (slides - 1);
			} else {
				tabindex += 1;
				move = '-=' + windowWidth;
			}
		} else if (tabindex === 1) {
			tabindex = slides;
			move = '-=' + windowWidth * (slides - 1);
		} else {
			tabindex -= 1;
			move = '+=' + windowWidth;
		}

Thank you

1 Like

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