Employing CSS selectors directly in the style attribute

I have created a stylish button using some fancy CSS techniques.

Below is the CSS code for the button, including hover and click events:

.button {
    display: inline-block;
    width: 200px;
    height: 200px;
    padding: 15px;
    border-radius: 25px;
    background:linear-gradient(to bottom, hsla(36, 100%, 60%, 1) 5%, hsla(36, 100%, 40%, 1) 100%);
    border:2px solid hsla(36, 100%, 30%, 1);
    box-shadow:inset 0px 2px 2px 0px white;
    position: relative;
    left: 0px;
    top: 0px;
    text-shadow:0px 1px 0px hsla(36, 100%, 30%, 1);
    margin: 25px;
}

.button:hover {
    background:linear-gradient(to bottom, hsla(36, 100%, 65%, 1) 5%, hsla(36, 100%, 45%, 1) 100%);
}

.button:active {
    background:linear-gradient(to bottom, hsla(36, 100%, 40%, 1) 5%, hsla(36, 100%, 60%, 1) 100%);
}

To create multiple variations of this button efficiently in the future, I am exploring the idea of adding a custom attribute called buttonColor. This attribute will be read by JavaScript to dynamically adjust the colors of the button. Each button will have at least three colors; two for the gradient and one for the drop shadow and border.

<div class="button" id="testButton" buttonColor="ff8c00">
    <p class="buttonHeader">foo</p>
    <p class="buttonBody">foo2</p>
</div>

Here's where I need help with the JavaScript logic:

function hexToRgb(hex) { 
    // Omitted code for brevity
    return [r, g, b];
}
function rgbToHsl(r, g, b) { 
    // Omitted code for brevity
    return [h, s, l]
}

var buttons = document.body.getElementsByClassName('button');

for (var i = 0; i < buttons.length; i++) {
    var rgb = hexToRgb(buttons[i].getAttribute("buttoncolor"));
    var hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
    // Need assistance here
}

I can update the button style easily, but I'm struggling with modifying its appearance during :hover and :active states.

Answer №1

use data attributes! try something like this:

<div class="button" id="testButton" data-button-color="ff8c00">
    <p class="buttonHeader">foo</p>
    <p class="buttonBody">foo2</p>
</div>

js

function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });
 
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function rgbToHsl(r, g, b){
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    }else{
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max){
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return [h, s, l];
}

 


var buttons = document.body.getElementsByClassName('button'); //Gets all elements with button class

for (var i = 0; i < buttons.length; i++) {
    var rgb = hexToRgb(buttons[i].data("button-color")),
        hsl = rgbToHsl(rgb.r, rgb.g, rgb.b),
        rules = [];
    rules[i][0] = hsl;
    
    hsl[2] = 100 - hsl[2]; // make second color
    rules[i][1] = hsl;
    var len = rules.length;
    for(;len--;) {
        buttons[i].style = 
            "background: linear-gradient(to bottom, hsla(36, 100%, "+rules[i][0]+"%, 1) 5%, hsla(36, 100%, "+rules[i][1]+"%, 1) 100%);"; // put rules on el
    }
}

edit

Rewrite this text to be unique.

let's say you made a rules array

var rules = [...]; // ['float: left', 'cursor: pointer']

or object

var rules = {
    'hover': [...], // rules...
    'active': [...]
};

in your code above. You could then insert them with the following:

var sheet = (function() {
    var style = document.createElement("style");
    style.appendChild(document.createTextNode(""));
    document.head.appendChild(style);
    return style.sheet;
})();

function addCSSRule(sheet, selector, rules, index) {
    if("insertRule" in sheet) {
        sheet.insertRule(selector + "{" + rules + "}", index);
    }
    else if("addRule" in sheet) {
        sheet.addRule(selector, rules, index);
    }
}

// ['float: left', 'cursor: pointer']
addCSSRules(document.styleSheets[0], ".button:hover", rules.join(';'));

or

// { 'hover': ['float: left'], 'active': ['cursor: pointer']};
addCSSRules(document.styleSheets[0], ".button:hover", rules.hover.join(';'));
addCSSRules(document.styleSheets[0], ".button:active", rules.active.join(';'));

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

How to eliminate cell borders in a Vaadin table

I recently set up a table in Eclipse using Vaadin for assistance. After some trial and error, I successfully removed the borders of the table with the following line of code: tblResetButton.addStyleName(Reindeer.TABLE_BORDERLESS) ; However, there is sti ...

Get the file by clicking the link and then automatically scroll down to the bottom div

When a user clicks on a link, I want them to be able to download a file (using the href attribute) and also automatically scroll down the page to a specific form. Currently, my code only allows for one of these actions to happen at a time. I cannot seem t ...

Steps for creating a one-sided container in CSS

I've created a container class with the following CSS: .container { margin: 0 auto; width: min(90%, 70.5rem); } This setup centers the content on the page within the container, which is great for organization. However, I'm looking to creat ...

I created a new game where I can select two images to display, but for some reason, it is only showing one

My rock paper scissors game functions well, except for one issue. I programmed it to display both the player's choice and the bot's choice along with an outcome message (win, tie, or lose). However, I encountered a problem where only the player&a ...

How can you connect a CSS file from a CSS directory in WordPress?

Completely new to wordpress theme development here! I am attempting to incorporate the style.css file located in the CSS folder within my root directory. Can someone guide me on how to do this? I'm eager to get an answer as soon as possible. ...

Unexpected rendering occurs when using a CSS double transition

In my React application, I am working on implementing smooth page transitions for a more visually appealing user experience. While using simple fade-in/fade-out transitions, I have noticed that transitions between pages with similar content are not as smoo ...

What is the best way to begin IMA HTML5 SDK ads with sound off?

One challenge I encountered was getting autoplay video to work on iOS 10 using HTML5. To achieve this, I utilized the following code: <video autoplay loop muted playsinline controls> <source src="http://distribution.bbb3d.renderfarming.net/vi ...

Toggle the visibility of elements (such as a form) with a click of a link - Utilize ajax to

I'm attempting to use jQuery to toggle the visibility of a form. This functionality is triggered by clicking on a specific link... The goal is to hide all links with data-action="edit" and only display the form that follows the clicked link, as there ...

What is the reasoning behind the repetitive use of @media (max-width: 767px) in the Twitter Bootstrap

Why is the media query @media (max-width: 767px) repeated in the bootstrap-responsive.css file? To find out, you can view the file by visiting ...

Why is a div nested inside an overflow: hidden; div not expanding to the full width of its content?

.container { white-space: nowrap; overflow: hidden; } .inner { width: 100%; } .list-item { display: 'inline-block', boxSizing: 'border-box', border: '3px solid black' } import React, { Component } from 're ...

Issue encountered while attempting to replace POST method with PUT (Method Not Allowed)

I'm facing a problem with the "Method Not Allowed" issue when I try to use PUT instead of POST to update information on my blog. I have already added method override for koa. Here is the HTML: <div class="create-message content"> &l ...

What is the reasoning behind these parameters being utilized?

When I apply the class "container" to a div, it causes an issue with the width of the div. The properties are taken from _grid.cscc. I need the width to be 100%. https://i.sstatic.net/KGgXA.jpg https://i.sstatic.net/6tSgW.png This problem occurs every ...

I am having trouble retrieving the information stored in an Array of Objects. Specifically, I am having difficulty accessing and iterating through each object using a for

Is there a way to extract data from an API individually and retrieve data from an Array? let {Array}=jsonData fetch("https://apis.ccbp.in/city-bikes?bike_name" + search, options) .then(function(response){ return response.json(); }) .then(funct ...

Comparing CSS rules: the faster option between specifying multiple IDs or not

Recently, I have been heavily involved in working with Concrete5. It has come to my attention that the default theme contains numerous CSS rules that are defined in this manner: #page #central #sidebar p{line-height:24px} Considering that "sidebar" is an ...

In Bootstrap 3, you can toggle individual collapsible items without affecting others by only closing the specific

I am facing an issue with my Bootstrap collapsible elements. I came across an answer that includes the necessary javascript to close only the collapsible items in my table, while leaving other collapsible items on the page (in the menu) unaffected. These i ...

Preserve the information within

Recently, I encountered an issue with a file that generates HTML and adds it to a PHP string using a buffer. Here's the code snippet: <?php ob_start(); ?> <table> <tr> <td>Content</td> </tr> ...

Delete a portion of the text on the button

Is there a way in HTML/JS/JQuery or CSS to search for a specific button in the document and remove/hide only the text of the button without affecting the icon? @Html.ActionLink("Edit", "Edit", new { id = -1 }, new { @class = "btn-edit" }) | ...

When the HTML and PHP code keeps running, the JavaScript text on the page updates itself

I was experimenting with threading in different languages like Java, PHP, and JavaScript. I am aware that JavaScript is single-threaded and PHP lacks robust threading capabilities. Below is the code snippet I have been working on: <body> <p id= ...

How can I remove the div container every time the submit button is clicked?

I am currently working on a form that is capturing values as shown below. <form role="form" id="calculate"> <div class="form-group"> <select class="form-control" id="paper"> < ...

Displaying the outcome of an HTML form submission on the current page

Within the navigation bar, I have included the following form code: <form id="form"> <p> <label for="textarea"></label> <textarea name="textarea" id="textarea" cols="100" rows="5"> ...