What could be the reason behind the button's lack of color change with this particular code?

I'm a beginner in web development and currently practicing HTML, CSS, and Javascript. I've added a button to my html file and would like the color of the button to change when it's clicked on.

Here is my HTML code:

<button id="box" style="padding: 20px; background-color: black;"></button>

This is the Javascript I have written:

document.addEventListener('click', event => {
    if (event.target.id === 'box') {
        document.style.backgroundColor="red";
    }
})

I can't figure out why it's not working as expected.

Answer №1

document does not come with a style property as standard in spec-compliant browsers. If this is the issue, your developer console would likely display an error message like:

Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')

To resolve this, you need to be more specific about which element's background color you want to change. In the revised code example below, I have targeted document.body to access the style property:

document.addEventListener('click', event => {
    if (event.target.id === 'box') {
        document.body.style.backgroundColor="red";
    }
})
<button id="box" style="padding: 20px; background-color: black;"></button>

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

Determine the position of the cursor in an editable span

Is there a way to add text at the cursor position in an editable span when a button is clicked? The span contains multiple lines of text and HTML tags. [Take a look at this example on JSFiddle](http://jsfiddle.net/8txz9sjs/) ...

The nuSelectable plugin enhances the functionality of jQuery

I am currently experimenting with the jQuery nuSelectable plugin in order to enable users to select multiple items simultaneously. Unfortunately, I am encountering difficulties in making the selection work as intended. You can find the plugin here. After ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...

What is the best way to retrieve all of a user's records based on a specified selection

My HTML text input field looks like this: <input id="CustID" name="CustID" dir="rtl" value="<?php echo $CustID;?>" size="35" required="true" maxlength="9" > Whenever a user enters their number, I want a select box to display all tickets assoc ...

Encountering an issue while trying to convert a JSON object into an array of a specific class type

When I receive a JSON object from a service, I want to iterate through this object and populate an array of class types. Below is the code used to call the service: public GetMapData(): Observable<Response> { var path = 'http://my.blog.net ...

Applying CSS to an iframe using JavaScript: A Step-by-Step

I have an Iframe editor and I am trying to change some CSS inside the editor. However, when I attempt to apply the CSS, it does not affect the styles within the Iframe. <div id="editor" style="flex: 1 1 0%;"> <iframe src="https://editor.unlay ...

Having trouble retrieving a value from the $http promise, causing the code within the then() function to not run as expected

In the past, I encountered a challenge with the $http service which I managed to solve by creating a dedicated service for handling my requests. However, as my requests grew larger, this solution started to seem inefficient. Instead of just assigning a sim ...

Issues with AngularJS Directives not functioning properly when elements are added dynamically through an AJAX request

I am facing a scenario where I have a page featuring a modal window that is created using the AngularUI Bootstrap modal directive. The DOM structure for this modal is being dynamically loaded from the server, and it is triggered to open when a specific but ...

What is the best way to utilize nav and main-nav in CSS?

Working with HTML and CSS <nav class="nav main-nav"> </nav> Styling with CSS main-nav li{ Padding:0 5% } I am a beginner in HTML and CSS and facing an issue. I noticed that when using main-nav in CSS, I'm not getting the de ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

The visibility of the button background created with :before will only be apparent when a content property is specified

There's an unusual issue I've encountered... I have a simple button, nothing out of the ordinary, just a basic button like this <button class="btn btn--error"> Button Text </button> Now, I want to add an image next to my button ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Retrieve the class name based on the ID of the final appearance of the div using jQuery

<div class='user user1' id='newuser'></div> <div class='user user2' id='newuser'></div> <div class='user user3' id='newuser'></div> To retrieve the class name ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

Convert a JSON array into a new format

Here is the JSON data input provided: "rows": [ [ 1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement" ], [ 2, "ADM ...

An issue with asynchronous execution in Protractor

I have been using and learning protractor for over a month now. Despite the documentation stating that Protractor waits for Angular calls to complete (http://www.protractortest.org/#/), ensuring all steps are executed synchronously, I have not found it ...

Heading made of ribbon without increasing the scrolling space

Incorporating a unique ribbon-style heading that stretches out from the content area on both sides to create a 3D effect using an image background without relying on CSS3 techniques. I experimented with floating elements, negative margins, and relative po ...