Change the background color according to the user's input text

I want to create a text box where users can input color keywords like blue, lime, or black. When they click submit, I want the background color of the page to change accordingly.
This is what I have so far:

<label for="color">Color: </label><input type="text" name="color" size="20" id="color" />
<button type="button" onClick="javascript:changeBGC(color)">Submit</button>

And in my script:

function changeBGC(color){
    document.bgColor = color;
}

Answer №1

Give this a try:

document.body.style.backgroundColor = document.getElementById('color').value;  

The code above changes the background color of the body based on the value of an input element with the id 'color'.

If you want to learn more about setting CSS styles using JavaScript, check out this documentation.

Here's a live example on JSFiddle for you to experiment with.

Answer №2

Alternatively, you have the option to modify the code as shown below:

<input type="button" onClick="updateBackground(color.value)">Click Here</input>
                                                        ^

See live example here

Answer №3

Alternatively, you have the option to utilize a more effective method

<label for="shade">Shade:</label>
<input type="text" name="shade" size="20" id="shade" value=""/>
<button type="button">Enter</button>

var input = document.getElementById('shade');
var button = document.querySelector('button');
button.addEventListener('click', function( event ) {
   event.preventDefault();    
   var shade = input.value;
   document.body.style.background = shade;
});

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

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

What is the best way to insert images into a div in Ionic framework?

I am facing an issue with fitting an image inside a div container. Here is my code structure: <div style="background-color: red; height: 200px; width: 200px;"> <ion-img src="{{kategori[i].img}}"></ion-img> & ...

The Challenge of CSS Transition and Checkbox Label Discrepancies

I'm looking to adjust the position of my label when a checkbox is checked. Everything works smoothly if I don't include a transition for the top offset property in the CSS of my label. However, when this transition is added (as seen in the commen ...

React does not display the items enclosed within the map function

I am facing an issue with rendering elements from a map function. Despite trying to modify the return statement, I have not been able to resolve the issue. class API extends Component { myTop10Artists() { Api.getMyTopArtists(function (err, data) { ...

Is it possible to view the CSS of a PDF file in print template mode using Chrome?

https://i.stack.imgur.com/XlcWm.png Currently facing an issue with debugging CSS on my PDF template. I am unable to inspect the styles directly in the CSS due to limitations. When using inspect element in Chrome, only the styles for text and elements are ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

The Android smartphone is experiencing issues with the responsive design not aligning properly on the

I'm encountering difficulties with creating a Viewport that functions properly on an android smartphone. My website is fully responsive, scaling down to 480 pixels wide. At this point, a min-width of 480px is set on the body tag. Initially, my viewp ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

A error was encountered stating that the formValidation function is not defined when the HTML form element is submitted

Having trouble calling a function and receiving an error message. How can I resolve this issue? The error message reads: index.html?email=&gebruikersnaam=&wachtwoord=&submit=Submit:1 Uncaught ReferenceError: formValidation is not defined at HT ...

Open the URL in a new tab based on certain conditions

Currently, my page redirects if a specific checkbox is selected and the "submit" button is clicked: if request.Form("myCheckbox") = "on" then response.Redirect("/newPage.asp?txt="staff"") else response.Redirect("/thisPage.asp") end if I ...

Is it possible to nest CSS Variables within CSS Variable names?

Is it feasible to embed a CSS Variable inside another CSS variable's name or perform a similar action like this: :root { --color-1: red; --index: 1; } span { color: var(--color-var(--index)) } ...

Press on Selenium with Python

I am experiencing an issue with clicking in Selenium as it is not able to click on the button. Below is the code I am using: from selenium import webdriver import time import click from selenium.webdriver.support.select import Select from selenium.webdriv ...

Creating a step wizard form with ReactJs can be accomplished by breaking down the form into

I have developed a resume generation application with two main components: BasicDetails and EmploymentDetails. To see a working example, click here: https://codesandbox.io/s/next-dynamic-testing-issue-forked-h1nt8 index.js file: <form onSubmit={ha ...

Having trouble implementing the page object model with cucumber.js: bug detected!

I have been working on implementing a page object pattern in my cucumber.js test automation suite with selenium webdriver. However, I am facing an error when trying to call the page object from my test step. The folder structure I am using is as follows: ...