Ways to update CSS following button submission?

I'm facing an issue with two input fields in my ejs file that accept hexcodes. After entering the hexcodes and clicking the submit button, I update variables in my stylesheet to these hexcodes to change the background gradient. Is there a way to refresh only the background gradient without having to redirect or refresh the entire page?

<script>
// fd is the form data
function setValue(fd) {
  let hexcode1 = fd.get('hexcode1');
  let hexcode2 = fd.get('hexcode2');

  r.style.setProperty('--color1', hexcode1);
  r.style.setProperty('--color2', hexcode2);
}
</script>

Answer №1

One way to store and retrieve hexcodes is by using cookies, even when the page refreshes.

Check out the JavaScript code snippet below:

window.addEventListener('DOMContentLoaded', function() {
  var cookieValue = getCookie('backgroundColor'),
      btns = document.querySelectorAll('.color-btn');

  if (cookieValue) {
    setBackgroundColor(cookieValue);
  }
  
  Array.from(btns).forEach(function(btn) {
    btn.addEventListener('click', function() {
      var color = this.getAttribute('data-color');
      setBackgroundColor(color);
    });
  });
});

function setBackgroundColor(color) {
  document.body.style.backgroundColor = color;
  setCookie('backgroundColor', color);
}

function getCookie(name) {
  var cookies = document.cookie.split(';'),
      cookie = cookies.find(function(str) { return str.indexOf(name + '=') === 0; });
  if (cookie) {
    return cookie.split('=')[1];
  }
  return null;
}

function setCookie(name, value) {
  document.cookie = name + '=' + value;
}

CSS styling:

body { background: red; }
button { padding: 1em; }
[data-color="red"] { background: red; }
[data-color="blue"] { background: blue; }
[data-color="green"] { background: green; }

Sample HTML buttons:

<button class="color-btn" data-color="red"></button>
<button class="color-btn" data-color="blue"></button>
<button class="color-btn" data-color="green"></button>

Here is a JSFiddle link

Keep in mind that the cookie storage in this code expires when the page closes, requiring manual re-entry. To extend the duration, add the following code (which preserves it for a year, adjust as needed):

var expiry = new Date();
expiry.setFullYear(expiry.getFullYear() + 1);
document.cookie = name + '=' + value + '; expires=' + expiry.toUTCString() + ';';

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

What is the best way to draw attention to the presence of an "onmouse over" effect in a specific location?

As I design my webpage, I plan to include several circles with onmouseover effects (tooltip pop-ups). However, I am concerned that many visitors may overlook this feature. I am curious to know what strategies you typically employ to capture visitors' ...

Stop duplicate votes on a Node/Express + Pusher JS Voting Application

I am currently in the process of developing a basic voting application where users can select an option from an HTML dropdown menu and submit their choice through a form, triggering a POST request to store the selection in a database. The updated data is t ...

Switch the displayed image(s) based on the radio button selection made by the user

I need help implementing a feature on my website where users can change an image by selecting radio buttons. For example, there are three options: 1) Fox 2) Cat 3) Dog When the user chooses "Fox," I want an image of a fox to be displayed. If they then sw ...

Can an ES6 class be utilized as a custom TypeScript type?

My goal is to accomplish the following: Developing a Typescript class and exporting it in a .ts file. Compiling that .ts file into an ES6 .js bundled file. Importing the class from the bundled .js file in a new .ts file elsewhere. Utilizing this imported ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...

Issue regarding the functionality of CSS styling when applied to a button

Trying to Style a Button with CSS div.myButton input a { display:block; height: 24px; width: 43px; padding:10px 10px 10px 7px; font: bold 13px sans-serif;; color:#333; background: url("hover.png") 0 0 no-repeat; text-decoration: none; } myButton a:hover { ...

I'm a bit uncertain about the best placement for my progress bar component during the API call

Trying to grasp material ui I managed to implement the progress bar. Struggling with loading it until my data is fully loaded. Uncertain about where to place my progress bar component. Could you guide me on how to resolve this issue during API calls, so I ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...

Encountering an error while utilizing ngForm in an HTML form

I have developed a custom component called "login", where I created an HTML form named "login.component.html". To convert this form into an Angular form, I added the code "" in login.component.html and imported import {NgForm} from '@angular/forms&apo ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Sending a 2-dimensional array from JavaScript to the server using AJAX

My JavaScript code involves working with a 2D array. var erg = new Array(); for (var i in val) { erg[i] = new Array(); for (var j in val[i]()) { erg[i][j] = val[i]()[j](); } } However, I encountered an issue where only the 1D array ...

I encountered a problem retrieving the value from a Textbox using its ID in JavaScript

When I have text boxes with values, I call my JavaScript method on one of the textboxes 'onblur'. The function looks like this: function CalculateExpectedProductPrice() { alert("hi i called"); var originalPrice = document.getElementById(&apo ...

Difficulty in loading TypeScript web component using Polymer serve

As I follow the LitElement guide provided here: , I meticulously adhere to each step mentioned and then execute polymer serve in my project's root directory. I diligently clone every file from their example stackblitz pages. Is it possible that using ...

Error: An unexpected "{", only one argument is allowed in the import call

While following the example provided on the npmjs documentation (with npmjs installed), I encountered an error in the browser: SyntaxError: Unexpected token '{'. import call expects exactly one argument. I have thoroughly searched for similar ...

Add text to a separate div element on a different webpage using jQuery Mobile

Having a list view, upon tapping by the user, there is a transition to a loading page followed by switching to an article page after completion. The issue I am facing is that although the loading works well, I am unable to append content to the div of the ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Transforming Plain Text to HTML Format

Currently, I am fetching some Strings from a database and successfully converting them to HTML using the following code: private string StripHTML(string source) { try { string result; // Code for stripping ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Receiving data through a POST request in Node

I am currently working on a project where I need to send an email via a POST request to my node/express server. However, I am facing difficulties in passing the email details through the request and accessing them on the node side. Here is what I have tri ...

JavaScript: Implement a function that returns an object with key-value pairs instead of a

Once again, I'm looking at this particular answer. var firstEvents = events.reduce(function(ar, e) { var id = e.getId(); if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) { ar.pus ...