Using Javascript to Change Background Color on Button Click

The button press does not result in a change of the background color. What could be causing this issue?

var body = document.getElementsByTagName("body");
var bgbutton = doucument.getElementById("bgchange");
bgbutton.onclick = function() {
  body.style.background-color = "green";
}
body {
  width: 600px;
  margin: 0 auto;
  background-color: #FF9500;
  padding: 0 20px 20px 20px;
}
<div id="wrapper"></div>
<button id="bgchange"></button>

Answer №1

The method document.getElementsByTagName
retrieves a node list, so you must select an element from it using [0]:

var main = document.getElementsByTagName("main")[0];

However, there is an alternative property that can be utilized:

var main = document.body;

Additionally, there is a typo in the line following this one:

var navbar = doucument.getElementById("navbar");

... should be document...

Furthermore, when referencing style attributes in JavaScript, they are typically written in camelCase:

body.style.backgroundColor

... unlike the convention used in CSS (background-color).

Answer №2

This code snippet is incorrect:

body.style.background-color = "green";

The correct version should be:

body.style = "background-color:green"

Answer №3

Aside from the suggestions provided by trincot, make sure to include relevant text or icons inside your button element to enhance its usability.

let changeButton = document.getElementById("colorChange");
changeButton.addEventListener('click', function() {
  document.body.style.backgroundColor = "blue";
}
body {
  background-color: #FF9500;
}
<button id="colorChange">Switch Color</button>

Answer №4

Initially, there is a syntax error in the code where "doucument" is used instead of "document".

 var bgbutton = doucument.getElementById("bgchange");

Secondly,

var body = document.getElementsByTagName("body");

When referencing elements in the DOM by Tag or Class name in JavaScript, it is necessary to specify which element index to target. In this scenario, it would be the first one.

var body = document.getElementsByTagName("body")[0]

A more concise way to achieve this is by treating the result of document.getElementsByTagName as an array and accessing the specific item using its index.

This alternative method works as well:

 var body = document.getElementsByTagName("body").item(0);

Lastly, the property body.style.background-color should actually be body.style.backgroundColor.

var body = document.getElementsByTagName("body").item(0);
    var bgbutton = document.getElementById("bgchange");
    bgbutton.onclick = function() {
    body.style.backgroundColor = "green";
    }
body {
    width: 600px;
    margin: 0 auto;
    background-color: #FF9500;
    padding: 0 20px 20px 20px;
    }
<div id="wrapper"></div>
    <button id="bgchange"></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

``Advanced Web Development: Dealing with HTML5, CSS3, and

I am facing an issue while implementing a design from the CSS and HTML login form templates on my project. Below is the snippet of my HTML: <p id="firstname_line"> <label>First Name:</label> <input type="text" name="firstnam ...

Utilizing data from a JavaScript array and merging it with basic HTML structure

Every day, a js array source on a remote server gets updated: var io = new Array(); nsi[0] = new Array('','Frank','','Factory worker','Mercedes',374.0,26.2,76,181,'',75,'Audi',1456.5,27 ...

Adjust the quantity of images shown in the Flex Slider carousel

My website includes a flex slider with a carousel, but it seems that I did not configure the properties of the slider correctly (or it could be a CSS issue) as shown here: . The last image in the carousel is only partially visible. While I am able to clic ...

Having trouble with uploading images?

I'm having issues with using PHP to upload an image to a folder. Can someone please help me troubleshoot this? Thank you! Here is the code for setup.php <?php include("../includes/config.php"); ?> <?php if ($_SESSION["isadmin"]) { ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Position a div element on top of Google Maps to create a floating

Currently working on a website and attempting to add shadows over Google Maps by using a <div> element for a shadow effect: Unfortunately, the desired effect is not being achieved. This is the current CSS code in use: html { height: 100% } body ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

Unable to fetch the webpage element object

While attempting to extract data from the historical table on investing.com, I encountered an issue where I couldn't retrieve the column item and an error occurred. Traceback (most recent call last): File "<ipython-input-119-ba739f477693>", ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well. After ex ...

ReactiveJS - Adding elements to an array and encountering the error of undefined

In two separate JavaScript files, I have 2 arrays declared as shown below: Index.JS: const [product, setProduct] = useState([]); const [item] = useState([ { name: 'Blue Dress', Image: '/static/media/Dress.1c414114.png', Pr ...

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

I am interested in altering the color of table rows using either JQuery or CSS

Looking to update row colors based on grouping. For example: Color the TR accordingly for every 5 rows: First 5 rows in green (0-4 Rows), Next five rows in red (5-9 Rows), Following five rows in yellow (10-14 Rows) and repeat the pattern... ...

Glitch with menu presentation in Safari browser

I'm currently working on a website for a client who specifically wants a traditional, non-responsive design. The site has been successful over time, but I've encountered an issue with the menu display in Safari. While it looks fine on other brows ...

The process of organizing and arranging the content that appears on a webpage is in

Seeking a solution to achieve a similar effect like this example. Wanting the sections to transition nicely when clicked on. Should I use a Jquery plugin or implement it with CSS? ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...