Seifounage
Seifounage

Reputation: 51

Cannot switch between classes every 1 second

I am trying to switch my div class using a timer, and I'm always switching between 2 classes.

Here is the beginning of the div code

<div id="this" class="photobanner">

You can check the JQuery function and timer I made below

function autoAddClass(){
    if( $( '#this' ).hasClass( 'first' ))
        $('.first').addClass('last');
    if{$('#this').hasClass('last'))
        $('.last').addClass('first');
    }
	setTimeout(autoAddClass, 1000);

This is not working

Upvotes: 0

Views: 61

Answers (3)

dreamweiver
dreamweiver

Reputation: 6002

Adding new classes to the elements is fine, but shouldn't you remove the existing class before adding a new one.

JS CODE:

setInterval(function(){
autoAddClass();}
, 1000);
     function autoAddClass() {
    console.log('timer elapsed');
    if ($('#container').hasClass('green')) {
        $('.green').removeClass('green').addClass('red');
    console.log('green');
    } else {
        $('.red').removeClass('red').addClass('green');
     console.log('red');
    }
}

Live demo @ JSFiddle:http://jsfiddle.net/dreamweiver/mpLq6f7b/2/

Note:Never use this keyword for variables/id/class selectors, its a bad practice also this is reserved keyword in javascript

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Actually second if statement you wrongly put '{' instead of '('. For verey second you have to change the class means Use setInterval

Your function be using toggleClass in jquery

function autoAddClass(){
    $('#this').toggleClass("first last");
}
$('#this').addClass('first');
setInterval(autoAddClass, 1000);

Fiddle

Upvotes: 2

G_hi3
G_hi3

Reputation: 598

function autoAddClass(){
    if( $( '#this' ).hasClass( 'first' ))
        $('.first').addClass('last');
    if{$('#this').hasClass('last'))
        $('.last').addClass('first');
    }
	setTimeout(autoAddClass, 1000);

Your second if-clause is invalid. Try: if ($('#this').hasClass('last')) {...}

Also, I think you should be using toggleClass, because after the first autoAddClass, your element will have both classes.

Upvotes: 1

Related Questions