Change the background color of a webpage by clicking with the help of Javascript

I've been experimenting with a script that changes the CSS background color on click, but I'm having trouble adding a third color option. Can anyone provide guidance on how to make the third color work?

Check out my jsfiddle here:

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();
}

Thank you,

James

Answer №1

To achieve this, you can utilize the modulus operator (%):

function adjustValue(){
    value = (value+1)%(arrayName.length);   
}

Check out the code in action on JSFiddle: https://jsfiddle.net/pkrWV/71/

Answer №2

Check out this jsfiddle for a cool demo:

Color-changing images

var bodyElement, classNames, index;

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Where should the Java directory be included in the PATH environment variable, or how do you set the

Setting up my PC for Scala programming requires adding Java to the path. I have downloaded and successfully installed Java, ensuring it is the correct version 1.8.0_261. There seems to be conflicting information in tutorials on whether to add the Java di ...

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

Errors occurred when trying to use Jquery to handle a JSON response

enter code here function customPaging(action, action1, page) { alert("in customPaging"); $.getJSON("./paging.do?action="+escape(action)+"&p="+escape(action1)+"&str="+escape(page), function(data){ alert("Length: "+data.length); var options = ...

In Three.js, objects are consistently displayed in a hierarchical manner, with each one appearing on top

As a newcomer to JavaScript and Three.js, I managed to write some code that successfully renders a sphere representing Earth and a smaller sphere as a Satellite in orbit. However, a perplexing issue arises when the Satellite passes behind Earth – it rema ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

Encountering an issue with Invariant Violation when attempting to retrieve a frame that is outside of the specified

I have created a VenueList component for my React Native app. I want to utilize the FlatList component to display a list of venues, but I keep encountering an error message that says "Invariant Violation tried to get frame out of range index" (refer to the ...

What is the best approach to merge multiple songs using core Java code?

I am interested in creating a Java code that can combine songs in various formats such as mp4, mp3, Avi, and wmv into a single file. I currently only have access to the JDK environment on my server and have been utilizing core Java file operation code to ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Guide to creating a fresh blank tab in Firefox with the help of Selenium and Java

I attempted the following method: driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t"); However, it did not create a new tab. I also experimented with: ((JavascriptExecutor) driver).executeScript("window.open();"); Unfortunately, th ...

An issue of InvalidFragmentDeletionException encountered while attempting to remove fragments

Hello! I am using a viewPager2 with 5 fragments. Depending on a specific condition, I need to display either all 5 fragments or allow the user to scroll through only 3 of them (pages: 1, 4, 5). To remove fragments 2 & 3, I attempted the following appr ...

Refreshing ApolloClient headers following a successful Firebase authentication

I am encountering an issue while trying to send an authorization header with a graphql request when a user signs up using my React app. Here is the flow: User signs up with Firebase, and the React app receives an id token. User is then redirected to ...

I am having trouble retrieving a JsonResult from an asp.net mvc controller using $resource in angular

I am new to Angularjs and trying to integrate it with asp.net mvc. I am facing an issue where I am unable to access an asp.net mvc controller to return a JsonResult using $resource in angular. Strangely, when I use $.getJson in JavaScript directly, it work ...

Is the rotate() method in SVG supported on web browsers when passing in additional parameters like angle, centerX, and centerY similar to the CSS rotate

I have recently learned about a rotate transform that allows for rotating around a specified center point using the `rotate(angle, centerX, centerY)` method. However, I have noticed that this method does not seem to work when applied via CSS. Interestingl ...

The error message is causing all blocks to change width. What steps can be taken to correct this issue

When the error message pops up, it causes the login form width to change. A shorter message makes it narrow while a longer message widens it. How can this be resolved without setting a fixed width? I am using FormHelperText element to show the error messa ...

Discovering the wonders of React and Javascript through the powerful Map function

I've exhausted all my knowledge of map functions and syntax, but I keep encountering the error TypeError: Cannot read property 'action' of undefined. This issue seems to stem from this line: constructor(data=[]). Typically, I am only familia ...

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected. ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...