Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS.

Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external stylesheet? I know it involves a combination of attributes in CSS, but clear guidance on how to apply this in relation to the external CSS file is what I need help with.

Inspired by W3Schools:

function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";
}
}

And also from W3Schools:

onclick="this.parentElement.style.display='none';"

My question now is how do I modify the 'display='none';' part in order to take input from the popup box and use it in the onclick event to achieve my desired effect? Would something like 'this.parentElement.style.backgroundcolor='" + usercolorinput + "';' work?

Your assistance is greatly appreciated.

Answer №1

Below is my approach to changing the color based on user input.

Changing the Color with User Input

function modifyBackgroundColor(element) {
  document.body.style.backgroundColor = element.value;
}
<h4> Enter #333 or pink below: </h4>
<input oninput="modifyBackgroundColor(this)"/>

Explanation:

The <input> element can trigger various events based on user interaction. In this case, I've utilized the oninput event, which executes whenever you type in the <input>, to call a function named modifyBackgroundColor.

When calling the function, the input element itself is passed as an argument. Therefore, within the modifyBackgroundColor function, we have access to the triggering element.

Within the function, we retrieve the input's value and then set the backgroundColor of the page's body to match that value.

Alternatively Using a Button

You also have the option to change the color using a button.

function modifyColor() {
  // Retrieve the input element's value
  var inputVal = document.getElementById("colorInput").value;
  
  // Apply the value as the backgroundColor for the body
  document.body.style.backgroundColor = inputVal;
}
<h4> Enter #333 or pink below, then click "Change Color": </h4>
<input id="colorInput"/>
<button onclick="modifyColor()"> Change Color </button>

Explanation:

In this scenario, the modifyColor function is triggered by clicking the button.

Inside the function, we fetch the input's value by selecting the input through its id attribute and capturing its value.

We subsequently employ that value to set the backgroundColor of the body, replicating the behavior seen in the preceding example.

Answer №2

To start, you should create a function that will determine the display value after a click event occurs.

function changeDisplay{
var value="block";
return value;
 }

Next, call this function within the click event like so: onclick="this.parentElement.style.display=changeDisplay()";

Please note: while the method to change background color remains the same conceptually, you may need to attach this function to another event such as text input changes, selecting an option from a dropdown menu, or any other way that suits your script or webpage.

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

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Adjust the size of items using a background image that covers the element

I'm struggling with a seemingly simple task here. I've been experimenting with different methods, but I just can't seem to grasp it. On the front page of my website, there is a cover section that contains a logo and a button: <section i ...

Is there an alternative method to retrieve the client's user agent if getStaticProps and getServerSideProps cannot be used together?

I am currently facing a challenge with the website I'm working on as it lacks a responsive design. This means that the view I display is dependent on the user agent of the client. In order to achieve this, I have been using getServerSideProps to deter ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

Why does the response.json() method in the Fetch API return a JavaScript object instead of a JSON string?

After using Body.json() to read the response stream and parse it as JSON, I expected to receive a JSON string when I logged the jsonData. Instead, I received a Javascript object. Shouldn't jsonData return a JSON string until we call JSON.parse() to co ...

Switching Next.js route using pure JavaScript

Currently, I am facing a challenge in changing the route of a Next.js application using vanilla Javascript. In order for the code to be compatible with Chrome Dev Tools, I cannot dynamically change the route with Next.js and instead must find a solution us ...

"Encountering a problem with ThreeJs graphics rendering

I recently developed an application using ThreeJs, but I encountered a strange issue. After rendering the 3D graphics, the window appears blank. However, when I click on full screen or adjust the window size, the output becomes visible. Check out Screen s ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

What is the best approach to comply with the EsLint rule "react-hooks/exhaustive-deps" and properly implement componentDidMount using hooks in React with a warning level?

After reviewing the React documentation, it appears that componentDidMount is now implemented using hooks as shown below: useEffect(() => { // your code here }, []) For example, if you wish to make an API call within this hook: useEffect(() => { ...

Linking Two HTML Components in Angular 4 with Identical Values

Recently, I've started working with Angular and encountered an issue. In a table row, the value item.md_id is bound like this: <tr *ngFor="let item of driverData"> <td class="align-right" id="md_id" [(ngModel)]="item.md_id" name="driverId ...

Ajax modal login feature refuses to close

Struggling to close a modal login box? Everything seems to be functioning correctly with the modal screen and ajax features, but I'm facing issues when it comes to closing the modal form. The code snippet looks like this: HTML: <a href="#" cla ...

What is the best way to showcase SVG code as an image using Vuejs?

My API is returning an SVG image as ASCII text code, which I am trying to display on my page. However, instead of the image, I just see a blank space. You can view my attempted solution in this JSFiddle: https://jsfiddle.net/c0p4ku78/ The key parts of th ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...