Designing a clickable element that alters the colors of various components on a page

I've been working on a button that changes the color combinations of elements on a page when clicked.

The goal is to have the colors change in specific pairings. For example, when the body is 'red' and the main titles are 'yellow', the alternate titles and border lines should be 'red' (matching the body color), and the alternate background should be 'yellow' (matching the main titles).

Unfortunately, I'm facing some issues with this setup. The colors seem to be changing randomly instead of following a set order, and I'm having trouble altering the 'border-bottom' color.

// Main title color change

var colors = ["yellow", "red", "blue"];
var colorIndex = 0;
  
function changeText() {
    var col = document.getElementsByClassName("textcolor");
    if (colorIndex >= colors.length) {
      colorIndex = 0;
    }
for(var i = 0; i < col.length; i++){
    col[i].style.color = colors[colorIndex];
    }
    colorIndex++;
    }

// Body background color change
  
var colors = ["red", "blue", "yellow"];
var colorIndex = 0;

function changeBackground() {
var col = document.getElementsByClassName("bodycolor");
if (colorIndex >= colors.length) {
  colorIndex = 0;
    }
for(var i = 0; i < col.length; i++){
    col[i].style.backgroundColor = colors[colorIndex];
    }
    colorIndex++;
    }

   
// Alternate title and border color change

var colors = ["red", "blue", "yellow"];
var colorIndex = 0;
  
function changeTextAlt() {
    var col = document.getElementsByClassName("alt-textcolor");
    if (colorIndex >= colors.length) {
      colorIndex = 0;
    }
for(var i = 0; i < col.length; i++){
    col[i].style.color = colors[colorIndex];
    }
    colorIndex++;
    }

// Alternate background color change
  
var colors = ["yellow", "red", "blue"];
var colorIndex = 0;

function changeBackgroundAlt() {
    var col = document.getElementsByClassName("alt-backgroundcolor");
    if (colorIndex >= colors.length) {
      colorIndex = 0;
    }
for(var i = 0; i < col.length; i++){
    col[i].style.backgroundColor = colors[colorIndex];
    }
    colorIndex++;
    }
body{
    font-size: 18px;
    line-height: 1.66667;
    font-family: 'Open Sans',Arial,sans-serif;
    box-sizing: border-box;
    width: 100%;
    min-height: 100%;
    background-color: #fff;
    }
 

.textcolor{
    color: #000;
}

.bodycolor{
    background-color: #fff;
}

.alt-textcolor{
    color: #fff;
    border-bottom: 1px solid #fff;
}

.alt-backgroundcolor{
    width: 100%;
    height: 200px;
    background-color: #000;
}
<body class='bodycolor'>

<button type="button" onclick="changeBackground();changeText();changeTextAlt();changeBackgroundAlt();">Click me</button>

<p class='textcolor'>This is a title</p>

<div class='alt-backgroundcolor'>

<p class='alt-textcolor'>This is an alternate title 1</p>
        <p class='alt-textcolor'>This is an alternate title 2</p>
            <p class='alt-textcolor'>This is an alternate title 3</p>
                <p class='alt-textcolor'>This is an alternate title 4</p>
                     </div>

                         <div class='bodycolor'>

                            <p class='textcolor'>This is another title</p>

                                </div>

                                    </body>

Answer №1

Give this a try instead: Check out the JSFiddle example here

const colors = ["yellow", "red", "blue"];
let colorIndex = 0;

function changeColor() {
    let col = document.getElementsByClassName("textcolor");
    let altCol = document.getElementsByClassName('alt-textcolor');

    if (colorIndex >= colors.length) {
      colorIndex = 0;
    }

    for(let i = 0; i < col.length; i++){
    col[i].style.color = colors[colorIndex];
    col[i].style.color = colors[colorIndex+1];
    }
    colorIndex++;
    }

function changeAltColor() {
    let col = document.getElementById("bodycolor");
    let altCol = document.getElementById('alt-backgroundcolor');

    if (colorIndex >= colors.length) {
      colorIndex = 0;
    }

    col.style.backgroundColor = colors[colorIndex+1];
    altCol.style.backgroundColor = colors[colorIndex];
    colorIndex++;
    }

Since you are only changing two colors at a time, there is no need for 4 separate functions.

If you have unique elements like div with distinct purposes, using the id attribute rather than class can make code writing simpler.

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

Unexpected outcome observed with straightforward MongoDB MapReduce task

For the past few hours, I've been struggling with a seemingly simple issue. I have a collection of documents that all have the same structure: { "_id": "736722976", "value": { "tag_cloud": { "0": { "0": "FIFA World Cup 2014 ...

The border color remains unchanged

I have designed a div with a border image on the right side and I want to add a colored border on the left side. However, when I change the color, it doesn't appear. How can I resolve this issue? Check out my FIDDLE for reference. CSS: div{ heig ...

Enhancing the Angular UI Bootstrap Accordion: Customizing the header with a new class

I currently have a functional accordion implemented as shown below <accordion-group is-open="open.first"> <accordion-heading> My Title </accordion-heading> </accordion-group> The "Accordion-heading" direc ...

React Native encountered a build error because the development server returned a response error code of 500

I'm currently working on a new project using React Native, but my knowledge of it is limited. I have followed all the necessary setups correctly, yet I am facing issues building from the emulator. Can anyone provide assistance with this error message: ...

Adding information into multiple tables from a single table

I am looking to streamline the process of displaying tables with identical entries on multiple HTML pages. Is there a way to create the table in one place and then call it into other pages? Could it be done like this: <table id="table1"> <th ...

Ways to activate the onclick function of a div element with JavaScript

I am trying to trigger the onclick event of my div using a click event in javascript. However, I am only able to trigger the onclick event using jquery. Here is the code snippet: html += '<div id="add_redirect" class="row pl_filter_v ...

Adjusting PDF height dynamically in React Native with the 'react-native-html-to-pdf' library - A step-by-step guide

I am currently working on generating a PDF document in react-native. My goal is to have a single page with dynamically increasing height as the content expands. options = { width: 675, height: ????, html: `<div id=" ...

Display fewer search results initially and have the option to view more when hovering

I am working with a PHP function that generates a ul element. <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> I am looking to display the list in a li ...

Using JQuery to emphasize selected radio button area

Can someone help me modify the code to highlight the checked radio button by adding or removing a class from the <span class " ui-message ui-state-highlight"> element? Below is the HTML and JS code: $(document).ready(function(){ $('# ...

CSS creates gaps between each of the internal elements inside the HTML document

I'm looking to create a 4px space between all internal components within my HTML, regardless of direction (top, bottom, left, or right). I have attempted to achieve this by using an external CSS file with the following code: body { padding: 2p ...

Display two columns side by side using Bootstrap on all screen sizes

I'm attempting to have two column divisions appear on the same line. Take a look at my code: <div class="col-md-12"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"> Left Division </div> ...

Tips for splitting a word in the uib-typeahead menu

I have successfully implemented a uib-typeahead dropdown in my AngularJS application where I display two attributes. The API is called based on the first name, and the response contains an object with both first name and last name. However, currently, they ...

AngularJS allows for the population of a JSON array from user input using the ng-model directive

I'm currently working on a form where I need to send the data to the backend in JSON format. The challenge I'm facing is that some of the form fields should be used to populate an array. Here's an abridged version of the form (using a Jade ...

Looking to place a global filter outside the primeNG table component?

I am currently utilizing primeNG in my project and I have a need to incorporate a global filter. The challenge I am facing is that I must add this filter in a different component. These two components are deeply nested within other components. My approach ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

Ways to change the border color of Bootstrap cards

While working on my webpage, I utilized bootstrap cards to maintain a clean and organized layout. By default, bootstrap cards are white in color. Unlike the navbar, where you can easily set color options like navbar-dark, changing the color of the cards re ...

How can I implement JavaScript validations specifically for elements that are currently visible on an HTML page when utilizing jQuery's .hide() and .show() functions?

Below is a snippet of my jQuery code. $("#firstBankDetail").hide(); $("#secondBankDetail").hide(); $("#thirdBankDetail").hide(); $("#fourthBankDetail").hide(); $("#noOfBankDetails").change(function(){ var value = $(this).val(); if(value == 0) { ...

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

The comparison between asynchronous and synchronous observables

Is there a way to determine if an Observable producer is synchronous or asynchronous? Here is an example of a synchronous Observable: Observable.of([1, 2, 3]) Another example showing asynchronous behavior using ngrx Store (see here): this.store.take(1) ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...