1

I have been using this script to switch CSS background colour on click and I am trying to add a third colour option but can't seem to get it working. Can anyone help to get the third colour to work?

Here is my jsfiddle link:

https://jsfiddle.net/pkrWV/70/

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
    'imageOne',
    'imageTwo',
     'imageThree',
];

function updateIndex(){
    if(index === 0){
        index = 1;
    }else{
        index = 0;
    }
}

bodyObj.onclick = function(e){
    e.currentTarget.className = className[index];
    updateIndex();
}

Thanks,

James

3 Answers 3

1

You can use modulus operator (%):

function updateIndex(){
    index = (index+1)%(className.length);   
}

JSFiddle: https://jsfiddle.net/pkrWV/71/

Sign up to request clarification or add additional context in comments.

1 Comment

You can also get rid of function Fiddle e.currentTarget.className = className[index++%className.length];
0

Try this jsfiddle:

three colors

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
    'imageOne',
    'imageTwo',
     'imageThree',
];

function updateIndex(){
    index++;
    if (index===3) {
        index = 0;
    }
}

bodyObj.onclick = function(e){
    e.currentTarget.className = className[index];
    updateIndex();
}

1 Comment

This is perfect! Is it possible to make the red above on hover and the black appear on click?
0

https://jsfiddle.net/pkrWV/72/

function updateIndex(){
    if(index === className.length-1){
        index = 0;
    }else{
        index = index+1;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.