Adjusting the background color of an HTML element with CSS through the power of Javascript

I am looking to dynamically change the background color of an element in CSS using JavaScript when a button is clicked.

Currently, my CSS code looks like this:

div.box {
    width:100px;
    height:100px;
    background-color:#FF2400;
}

I want the background color to change dynamically to different options by clicking on multiple buttons, each representing a different color.

Answer №1

Task Completed: http://jsfiddle.net/iambriansreed/zmtU4/

Updated without using jQuery.

HTML

<div id="box"></div><div id="box"></div>

<button type="button" onclick="button_click('red');">Red</button>
<button type="button" onclick="button_click('blue');">Blue</button>
<button type="button" onclick="button_click('green');">Green</button>
<button type="button" onclick="button_click('yellow');">Yellow</button>
<button type="button" onclick="button_click('purple');">Purple</button>​

Implemented in Pure JavaScript

function button_click(color){
    document.getElementById("box").style.backgroundColor=color;
}​

Answer №2

To change the color of an element using vanilla JavaScript, you can reference the element and use style.backgroundColor:

For instance, if the div is identified by myBox, you can do the following:

document.getElementById("myBox").style.backgroundColor="#000000"; // changes to black

See it live in action: http://jsfiddle.net/QWgcp/

If you find yourself frequently performing this type of manipulation, frameworks like jQuery offer simplified solutions for writing the code. Using jQuery, the same functionality becomes easier:

$('#myBox').css('background-color','#000000');

Answer №3

So if I understand correctly, you're looking to change a CSS rule that will affect all matching elements rather than just one specific element? Here is an example of how you can dynamically change the style in your scenario to make the color blue:

<html>
<head>
<style>
div.box{
    width:100px;
    height:100px;
    background-color:#FF2400;
}
</style>
<script>
    var sheet = document.styleSheets[0];
    var rulesList = sheet.cssRules || sheet.rules;
    var rule = rulesList[0];
    rule.style.backgroundColor = 'blue';
</script>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
</body>
</html>

Simply assign this code as a click event handler to a button and you're good to go.

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

Struggling to create responsive embedded videos?

https://i.sstatic.net/R0GUn.jpgI have successfully created a responsive video, but there seems to be an issue with the width to height ratio when the browser is fully stretched. The iframe appears narrow and tall in this situation. However, when the browse ...

What is the process for connecting a Google font to my Nuxt project files?

Recently delving into SCSS, I've been working on loading a local font into my SCSS file. Oddly enough, while it works perfectly fine in a CSS file, in a SCSS file it doesn't show anything at all, not even an error message: @font-face { font-fa ...

What is the best way to uninstall yarn from angular cli so that I can switch to using npm for installing packages?

When attempting to install packages using yarn for tooling, an error occurred stating: 'yarn' is not recognized as an internal or external command, operable program or batch file. Package installation failed with the details provided above. For f ...

What causes the while loop in a threejs render function to not refresh each frame?

I'm struggling with handling an array of 8 cubes, each only 1 pixel tall. When a button is pressed, I want them to smoothly animate to a new height using a while loop. Here's my current implementation: if (buttonPressed) { console.log(' ...

How can one make the image pop and stand out from its background?

I am trying to achieve a similar effect as shown in this design where the image stands out from its background. I have managed to do that, but I am struggling with aligning the image to the center and bottom with overflow. Can anyone help me with this? Th ...

What is the best way to position a <div> in the center of a container?

I am currently designing a cart page for an online store, and I have decided to showcase all the items in the cart using a table format. Here is my plan: https://i.sstatic.net/PJBpo.jpg My goal is to have the name, quantity, and price of each product dis ...

The loop seems to be disregarding the use of jQuery's .when() function

I've encountered a challenge with a custom loop that needs to perform a specific function before moving on to the next iteration. Below is the code snippet: function customIteration(arr, i) { if (i==arr.length) return; var message = arr[i]; ...

Fix the style of the CSS for the Bootstrap button

I am currently testing two social media buttons, one using an Anchor Tag and the other using a Button Tag for experimental purposes. The problem I am facing is that when I click on the button, its color and border change to the default bootstrap .btn styl ...

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

Is there a way to include string data in an object?

I'm encountering an issue when trying to input text into innerState.feedType. Unfortunately, I keep receiving the error message "Cannot read property 'toString' of undefined". How can I troubleshoot and resolve this problem in my code? Here ...

html retrieve newly updated page from the provided link

I am facing an issue where I set a cookie on one page and try to unset it on the next page that I reach via a link. However, the cookie only gets unset when I refresh the second page by pressing F5. To test this scenario, I have added a link and some cook ...

Tips for avoiding automatic updates to .js scripts after pressing F5

Is there a method to stop a JavaScript script from resetting when the user refreshes the page? For instance, if I have a picture slider that is constantly changing images, I would like the script to continue where it left off instead of starting over wit ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

I'm having trouble utilizing toastify.js after installing it via npm. I keep receiving the error message "Failed to resolve module specifier." Any advice

Currently, I am attempting to utilize Toastify-js, a library designed for toast type messages, by installing it through npm. In the provided documentation, following the execution of the installation command, there is a direction that states: - To begin ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...

Incorporate new functions through the css class name "javafx"

On my dashboard, I have 10 labels that share the same CSS class for mouse over events. Now, I want to change the button style after it is pressed and remove the mouse over effect. How can I achieve this? ...

Is it not possible to unselect the radio button?

I've been trying to implement a jQuery solution that allows radio buttons to be deselected, but I'm encountering difficulties with the prop function. Every time this code is executed, my condition ($(e.currentTarget).prop('checked')) al ...

How can I ensure that I am correctly choosing specific fields in a Mongoose query?

After carefully reading the documentation that explains how to extract specific fields from an object based on its id, I attempted to implement a similar code. However, I noticed that the output stored in the user variable includes all fields of the indi ...

Is there a way to remove a checkbox node that has already been generated?

I've been working on creating a to-do list, and I've run into an issue with deleting the checkbox once the task is complete. I attempted to create a function within the main function containing an if/else statement, but it didn't seem to wo ...

An issue of an infinite loop arises when utilizing the updated() lifecycle hook in VueJS

I am working on a VueJS application where I need to fetch a list of articles in one of my components. The logic is such that if the user is logged in, a specific request is made, and if not, another request is executed. Below is the snippet of code: <s ...