Instructions for creating a button that has the ability to alter the background color of a document:

Looking to add some interactivity to your webpage? I've been attempting to create a button that changes the background color when clicked using JavaScript and CSS, but haven't had any luck so far. Here is the code I've been working with:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Test
        </title>
        <style>
        .bgcolor1{
            background-color:black;
        }
        .bgcolor2{
            background-color:grey;
        }
        </style>
        <script type="text/javascript">

        </script>
    </head>
    <body class="bgcolor1">
        <button onclick="this.className = 'bgcolor2'">Change COLOUR</button>
    </body>
</html>

Unfortunately, despite setting up the code so that clicking the button should change the class to "bgcolor2" and update the background color to grey, it seems to only affect the button itself rather than the entire document. Any suggestions on how to get this working properly or spot what might be wrong with the code? Thanks for your help!

Answer №1

<button onclick="document.body.className = 'bgcolor2'">Change COLOR</button>

this points to the button, not the body.

document.body.className = 'bgcolor2';

Answer №2

it is recommended to utilize the document.body instead of using this

<!DOCTYPE html>
<html>
    <head>
        <title>
            Test
        </title>
        <style>
        .bgcolor1{
            background-color:black;
        }
        .bgcolor2{
            background-color:grey;
        }
        </style>
        <script type="text/javascript">

        </script>
    </head>
    <body class="bgcolor1">
        <button onclick="document.body.className = 'bgcolor2'">Change COLOUR</button>
    </body>
</html>

Answer №3

Here's an example you can try out:

HTML

<div class="box" onclick="changeColor()">Click me</div>

Javascript

function changeColor(){
    document.body.className = 'newColor';
}

CSS

.newColor{
    background:blue;
}

DEMO

Answer №4

To achieve the desired outcome, it is recommended to target document.body.className instead of using this. In this context, this refers to the button element itself. Modify the onclick attribute as shown below:

onclick="document.body.className = 'customBackgroundColor'"

Remember to replace customBackgroundColor with the name of your CSS class. Ensure that the CSS class has been defined beforehand.

Below is a demonstration with sample CSS and HTML code:

.bg1{
    background-color: blue;
}
.bg2{
    background-color: green;
}
<body class="bg1">
    <button onclick="document.body.className = 'bg2'">Change Color</button>
</body>

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

What is the process for executing an HTML file on localhost3000?

After linking all my .js files and HTML to my server file, I encountered an issue when launching localhost3000 - it displayed "cannot get/". Despite attempting various solutions, the problem persists. Is there anyone who knows how to resolve this? My serv ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

Having trouble with the Mongoose FindOne function?

I'm encountering an issue with Mongoose FindOne returning a null response when I pass a dateString argument as a parameter. My setup involves using nodejs and mongoose. Below is the snippet of my code: var Service = app.models.service; controller.ne ...

Display or conceal several elements upon hover using JQuery and HTML

Here is the current progress I have made: <div style = "position: relative;"> <a href = "#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "positio ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

What is the method for retrieving a specific value from an array in AngularJS that can be utilized directly in a JavaScript file?

$scope.login = function () { var userLoginData = JSON.parse(localStorage.getItem('userData')); userName = (userLoginData.Name) console.log(userLoginData); } This information is stored in my browser's local storage [{"Name":" ...

Animating an element when another one fades away

const myVueInstance = new Vue({ el: '#app', data: { showBlueElement: true } }) .a, .b { height: 50px; width: 50px; background: red; } .b { background: blue; transition: transform 1s ease-in-out; } <script src="https://unpk ...

issues with conditional statement

I'm encountering an issue with the if statement not functioning as expected, and I can't seem to figure out why. The if condition always gets displayed regardless of the input. To troubleshoot, I initially used a temporary code snippet for the co ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

Obtaining the href value with selenium webdriver in the presence of javascript triggered by a link click

Greetings for taking the time to review my query. In examining a webpage, I have come across more than 200 links and have verified that they are all functioning properly. The challenge arises when extracting the 'href' value as it does not always ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...

Improving the method of accomplishing a task using AngularJS

Clicking on an item in the tobeclicked list will transfer the data to the find empty list. The goal is to locate an empty list and update it by cloning the image there. The actual values and lists will include images. When an image is clicked, the system s ...

Retrieving width and height of the content block inner in Framework7, excluding navbar and toolbar dimensions

Is there a reliable way to determine the width and height of the page content-block-inner, excluding the navbar and toolbar? This measurement can vary across different devices and operating systems. I attempted to assign an id to the content-block-inner a ...

Is there a way to automatically zoom out a web page without manually adjusting it?

After constructing a JavaScript calculator, I encountered an issue with its display on mobile devices. The page is automatically zoomed in slightly, resulting in the calculator not fitting perfectly on the screen. However, when users manually adjust the zo ...

What is the best way to print text using the class name in Selenium with Python?

I'm encountering an issue with this code snippet: try: price = wait(driver, 10).until(EC.presence_of_element_located((By.ID, "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"))).text print(price) except Exception: print("element n ...

Tips for hiding database credentials in a JavaScript MVC framework such as Angular

When working with an MVC framework like AngularJS, I've noticed that many examples store the database credentials in an app.constant property within an app.js file. Unfortunately, this method makes the credentials easily readable by users. In my situ ...

Send the XML data to PHP to support all iterations of Internet Explorer

When passing XML to a PHP file, everything seems to work smoothly in browsers other than Internet Explorer. Surprisingly, it works fine in IE8 and IE11, but not in versions 9 and 10. The suspect could be the first "if" condition in the stringIt function b ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

Could someone please help me understand the reason behind the map function error I'm encountering?

Currently, I am delving into the world of API fetching. After following various responses on this platform, I encountered a perplexing error with the script below: const fetcher = async () => { const url = 'https://banana1.free.beeceptor.com/c ...

Selecting a Child Component in Vue.js: A Guide to Specifying the Correct Component

Within my application, I have a variety of components that are either generic or specific to certain brands. For example, I have two brand-specific components named Product_brand_A.vue and Product_brand_B.vue, both of which I want to display in a list form ...