Refreshing the page to dynamically alter background and text hues

I'm currently dealing with a website that generates a random background color for a div every time it is refreshed. I have a code that successfully accomplishes this:

var colorList = ['#FFFFFF', '#000000', '#298ACC', '#B079E0'];

$(function() {
$('#color-change').css({
        background: colorList[Math.floor(Math.random()*colorList.length)]
        color: colorList[Math.floor(Math.random()*colorList.length)]
});
});

My issue now is that I want the text color to match the background color, but the current code changes both randomly. How can I modify it so that only the background color changes randomly and the text color simply reflects the current background color?

Answer №1

To achieve a dynamic color change effect, you should create a separate list to store different text colors and fill it with suitable color codes. Check out the following list showcasing some example colors:

var textColorList = ['#000000', '#ffffff', '#00ff00', '#ff0000'];
var backgroundColorList = ['#FFFFFF', '#000000', '#298ACC', '#B079E0'];

$(document).ready(function() {
  var randomIndex = Math.floor(Math.random() * backgroundColorList.length);
  $('#color-change').css({         
    background: backgroundColorList[randomIndex],
    color: textColorList[randomIndex]
  });
});

Answer №2

var bgcolorlist = ['#FECE1B', '#F1585D', '#3BC2D6', '#A5CE39'];

$(function() {
  var randomColor = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
  $('#color-change').css({
        background: randomColor,
        color: randomColor
  });
});

Why not extract a random color value outside of the css function?

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

Utilize the function with another function (difficult to articulate)

Apologies in advance for my beginner question. Review the code snippet below: var dt = new Date(t*1000); var m = "0" + dt.getMinutes(); Depending on the t variable (unix time), the output can be one of the following: m = 054 // 54 minutes m = 03 // 3 min ...

AJAX: How to handle a successful POST request?

I have been recently exploring AJAX and I can see why I hesitated to delve into this particular area of JavaScript; it appears quite intricate. Most discussions seem centered around how to SEND data via POST, with little focus on what happens once the POS ...

Having trouble importing d3.js and typescript in IntelliJ?

Encountering errors in browsers' console when utilizing d3.select() in typescript code. Despite trying alternative methods like d3-timer.now(), the issue persists. As a newcomer to typescript, I am utilizing intelliJ Ultimate 2019.1. Through npm, I h ...

Utilizing Redux state within _app.tsx in NextJS: A comprehensive guide

This snippet of code pertains to my _app.tsx file import '../styles/globals.css' import AppNav from '../components/AppNav' import type { AppProps } from 'next/app' import { store } from '../store' import { Provider } ...

Triggering the react state update function through an onClick event

Trying to grasp React through a tutorial, but I'm confused about why I need to create a new function to pass to an JSX onClick instead of using the one returned from a React useState call directly. The following code works because it uses the handleB ...

A single image with dual clickable areas managed by an interactive image map

Is there a way to attach two href links to one image using CSS? I want it to function like an old school image map, but purely with CSS. Is this something that can be done? The current HTML code looks like the example below. However, I need the image to h ...

The issue with getting a token from Next-auth on the server side persists

Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side. I have double-checked my callbacks configuration ...

The `required` attribute is ineffective when used with the `<form>` element

My required attribute isn't enforcing mandatory field completion before form submission. HTML Code: <!-- Modal Content --> <form class="modal-content2"> <div class="container3"> < ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...

Creating a PHP-enabled HTML button that spans multiple lines

Currently, I am working on creating a list of buttons with h5 text. The issue I'm facing is that all the buttons have the same width, but when the text exceeds this width, the button expands. I would like the text to span multiple lines without affect ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Position multiple divs at the bottom of aligned divs

I'm currently facing issues with aligning divs at the bottom within multiple vertically aligned divs. <p>Top of page</p> <div id="container"> <div class="message">area1</div> <div class="message">area2</ ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Error: Unable to access property 'addEventListener' of null. This issue appears to be related to a Chrome extension

It's been frustrating dealing with this persistent error. I'm in the process of creating my very first chrome extension and for some reason, I just can't seem to pinpoint what's wrong with this particular code snippet: let beginButton = ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

Is it necessary to uncheck the row checkbox when inputs are left empty after blurred?

Two issues have cropped up here. When clicking on an input within a row, the corresponding checkbox should be checked. Currently, only the first text input is able to check the checkbox due to the use of .prev(). Is there a different approach that can be t ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

The addition operation in JavaScript seems to be malfunctioning as it is not adding up my values

After encountering an issue with calculating the number of payments, I discovered that the addition operator was not functioning as expected. Instead of summing up values, it was treating them as strings. For instance, when trying to add 3 and 5, the out ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...