What is the process to modify the font color on a webpage using a button?

I need some help figuring out how to change the font color on my website when someone clicks a button.

I already have the background functionality working, but I can't seem to get the text color to change.

This is the code I have so far:

<div class="dropdown">
<button onclick="toggleBackgroundDropdown()" 
class="dropdownButton">Background</button>
<div id="backgroundDropdown" class="backgroundDropdown">
<a class="colorbutton">Red</a>
<a class="colorbutton">Yellow</a>
<a class="colorbutton">Blue</a>
<a class="colorbutton">White</a>
</div>

<button onclick="toggleTextColorDropdown()" class="dropdownButton">Text 
Color</button>
<div id="textColorDropdown" class="textColorDropdown">
<a class="textcolorbutton">Red</a>
<a class="textcolorbutton">Yellow</a>
<a class="textcolorbutton">Blue</a>
<a class="textcolorbutton">White</a>
</div>

</div>

<script>
function toggleBackgroundDropdown() 
{   
document.getElementById("backgroundDropdown").classList.toggle("show");
}

function toggleTextColorDropdown() 
{   
document.getElementById("textColorDropdown").classList.toggle("show");
}

function changeColor()
{
var x = event.clientX; 
var y = event.clientY;
var elementMouseIsOver = document.elementFromPoint(x, y);

document.body.style.backgroundColor = elementMouseIsOver.text;
}

function changeTextColor()
{
var x = event.clientX; 
var y = event.clientY;
var elementMouseIsOver = document.elementFromPoint(x, y);

var a = document.getElementById('a');
a.style.color = elementMouseIsOver.text;
}

window.onload = function(event)
{
var colorbuttons = document.getElementsByClassName("colorbutton");
for (var i = 0; i < colorbuttons.length; i++) 
{   
    colorbuttons[i].addEventListener('click', changeColor, false);
}

var textcolorbuttons = document.getElementsByClassName("textColorButton");
for (var i = 0; i < textcolorbuttons.length; i++) 
{   
    textcolorbuttons[i].addEventListener('click', changeTextColor, false);
}
}

window.onclick = function(event)
{
if (event.target.className == "colorbutton")
{
    toggleBackgroundDropdown();
}
else if (event.target.className == "textcolorbutton")
{
    toggleTextColorDropdown();
}
}
</script>

Answer №1

Provide a unique identifier for buttons such as backgroundChange to change their appearance. Then implement the following code:

$("#backgroundChange").click(function(){
   if($(this).css('background-color')=='lightgrey')
         $(this).css('background-color', 'red');
   else {
         $(this).css('background-color', 'lightgrey');
   }
});

Similarly, you can toggle the class with:

$("#backgroundChange").click(function () {
        $(this).toggleClass('backgroundDropdown');
});

Answer №2

There is no need for jQuery, you can achieve this in two different ways:

  1. Create two different class names with different colors and call a function to change the class onClick
    <p onclick="function(event){event.target.className = your new class}"></p>
  2. Update your CSS style directly using JavaScript
    <p onclick="function(event){event.target.style.backgroundColor = 'red'}"></p>

Answer №3

It is recommended to modify the class of elements, such as the body, and apply the styling using CSS. This method offers greater flexibility and durability.

Answer №4

When attempting to modify the text color across the entire page and allowing for any color selection (even though only a limited number of choices are available through classes), using <input type=color> to pick a color may present some challenges if you solely rely on

document.body.style.color = something
. This is unless you have included color: inherit throughout.

For a more comprehensive (albeit slightly cumbersome due to API design) solution, consider altering the rule that dictates color in your stylesheet. A single rule with a broad selector can ensure that all desired elements are affected:

const theRuleIndex = // identifying the correct rule may be challenging
document.styleSheets[0].cssRules[theRuleIndex].style.color = yourColor

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

Ways to locate CSS file path within a web browser

Currently, I am focusing on the theme development aspect of Magento2. After compiling the .less file, I noticed that two css files are generated: styles-l.css styles-m.css Despite trying to inspect the element and view the applied CSS in the browser, i ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

creating circular shapes with canvas functions

Creating a circle in my game seems to be more challenging than I anticipated. While there are numerous tutorials available, none seem to address my specific issue. The problem lies in where and how to draw the circle within my existing code: function start ...

"Place the content at the center of the row using display block in Bootstrap version

Having modified the bootstrap.min.css file in my Bootstrap v4.3.1, I replaced all instances of display:flex; with display:block;. However, after making this change, I noticed that the rows were no longer centered, even when using justify-content-center. T ...

Tips on retrieving an item using jQuery's select2 plugin

How can I retrieve the value (flight_no) from the processResults function in order to populate the airline name with the respective flight number when selected? I've attempted to access the (flight_no) within the processResults function, but I'm ...

Discrepancy in Line Spacing in Internet Explorer 9 when Working with TextAreas

My TEXTAREA requires precise spacing, so I've set the formatting as shown below: TEXTAREA { font-family: Tahoma, Arial; font-size: 8pt; letter-spacing: 0px; line-height: 13px; } The issue arises when typing text into the textarea - the li ...

What is the proper way for the curry function to function effectively?

Here's a function that I came across: function curry(fn) { var args = [].slice.call(arguments, 1); return function() { return fn.call(this, args.concat([].slice.call(arguments))); }; } I always thought this was the correct way fo ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

I am looking to incorporate automatic scrolling functionality into my RSS Feed

I'm in the process of developing an RSS feed for my website. My expertise in JS/jQuery is limited, so any assistance would be greatly appreciated. After utilizing Google's Feed API and creating my own RSS Reader Widget, I realized that it lacked ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

JQuery will only run after the Alert has been triggered in Firefox

I am currently facing an issue with updating the 'like' count in my database using the 'changeRating()' method when a user interacts with local like, Facebook like, or Twitter buttons. Oddly enough, the 'likes' are not being ...

Managing memory and CPU resources in NodeJS while utilizing MongoJS Stream

Currently, I am in the process of parsing a rather large dataset retrieved from MongoDB, consisting of approximately 40,000 documents, each containing a substantial amount of data. The dataset is accessed through the following code snippet: var cursor ...

Having trouble with .animate() function?

Struggling to animate the position of my background image $(function() { $('#nav1').bind('click',function(event){ $('ul.nav').stop().animate({backgroundPosition: 'right top'}, 1000); }); $(function() { ...

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

Deactivate Mongoose connection in Node.js after completing tasks

Here is a mongoose script I have been using to connect to the local database and perform some operations. However, I am facing an issue with disconnecting the connection after use. const mongoose = require('mongoose'); const db = mongoose.connec ...