Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors disappear when hovering over the button.

Here is the code:

$('.btn').hover( function() {
    var $hover = $('.btn').attr('data-hover');
    $(this).css( "background", $hover );
}, function() {
    var $color = $('.btn').attr('data-color');
    $(this).css( "background", $color );
});

HTML:

<button class="btn wpb_btn-small" style="background:#00aff0;" data-color="#00aff0" data-hover="#0cbbfc">Button</button>

Answer №1

$('.btn').hover( function() {
    var $hover = $(this).attr('data-hover');   // <-- modify this line to target the current .btn
    $(this).css({ "background-color" : $hover });  // slight adjustment
}, function() {
    var $color = $(this).attr('data-color');  // adjust this line in the same way
    $(this).css({ "background-color" : $color });  // make a slight modification here
});

$('.btn') will bring back an array - in case there are multiple items on the page , use $(this)

both should be "background-color" or "background" , ensure you apply the recent changes where I unified them

you can even be more creative and collapse it all into one line

$(this).css({ "background-color" : $(this).attr('data-hover') });

Answer №2

To enhance user experience, consider utilizing the mouseenter and mouseleave events:

Examine the mouseenter event here

HTML Code Sample

 <button class="btn wpb_btn-small" style="background:#00aff0;" data-color="#00aff0" data-hover="#0cbbfc">Button</button>

JavaScript Code Sample

$(function() {
    $('.btn').mouseenter(function() {
        var bg = $(this).attr('data-hover');
        $(this).css( "background", bg );
    });

    $('.btn').mouseleave(function() {
        var bg = $(this).attr('data-color');
        $(this).css( "background", bg );
    });
});

View Live Demo

UPDATE: Consider using the Hover event for improved functionality. (Check out the highly rated answer for more details :<)

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

Retrieve and showcase JSON data with the help of jQuery

I'm trying to display a specific variable (Date) from a JSON file, but it doesn't seem to be working. Can anyone help me figure out what I'm doing wrong? <script type="text/javascript"> $(document).ready(function() { $. ...

Clearing Arrays in React Native Using useState

I'm struggling with the following code which aims to create an animated polyline for a map. I came across some examples online, but they were using outdated methods and didn't include useEffect or useState. I can't seem to clear the polylin ...

What is the best way to align the 5th and 6th list items to the left using CSS?

I am experimenting with Bootstrap to create a customized navbar. I am encountering difficulties in aligning the login and logout buttons to the right. Is there a way to achieve this? I have included my HTML and CSS code below: HTML code: <body> &l ...

Tips for enhancing the responsiveness of a calendar table in Bootstrap 5.2

Hello there! I need some help with adding rounded borders to tables using Bootstrap. Can anyone assist me with this? I'd be truly grateful for any guidance on this matter. Unfortunately, Stack Overflow is not allowing me to post my question, so I&apos ...

Rails database is not properly embedding into Javascript when using as_json.to_json method. (results in "&quot" characters)

I have scoured nearly every SO past question without success. Within my main.html.erb file, I am mixing html/erb/javascript. (I understand it's not ideal, but I'm still grappling with asset pipelines and this is just a small project.) My goal i ...

steps for repairing a scoreboard

Is there a way to make my scoreboard increase by +1 point instead of +10? In my JavaScript code, I used intervals as it was the only solution that worked: let scoreInterval = setInterval(updateScore); let score = 0; function updateScore() { var poin ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

Show the WooCommerce checkout shipping fields and eliminate the "Choose a different delivery address?" checkbox

Is there a method to eliminate the checkbox labeled "Ship to a different address?" on the woocommerce checkout page while still displaying the shipping fields? I have attempted the following: add_filter( 'woocommerce_cart_needs_shipping_address', ...

Utilizing Angular RXJS to generate an array consisting of three different observable streams

I am trying to use three different streams to create an array of each one. For example: [homePage, mainNavigation, loan_originators] However, currently only mainNavigation is being returned. const homePage = this.flamelinkService.getData('homePage ...

Attempting to design a customized tooltip for an SVG element embedded within the HTML code

Recently, I've delved into Js with the goal of creating an interactive pronunciation guide using inline svg. If you're curious to see what I've done so far, check it out here. My current focus is on incorporating basic styled tooltips that ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

Implementing multiple dropdown menus with Material UI in a navigation bar

I am currently working on designing a navigation bar that consists of multiple material UI dropdown menus. However, I have encountered an issue that has proven to be quite challenging for me to resolve. Whenever I click on a navigation bar item, all the dr ...

Creating a platform that allows users to build custom themes on a website using ASP.NET/C# programming language

I'm looking for a sophisticated approach to designing an ASP.NET website where users can easily create personalized themes for their sites using a user-friendly interface. Can ASP.NET themes assist with this? Should the interface enable users to gener ...

Conceal/Inactivate element when scrolling, and once scrolling comes to a halt, reveal it once more

I have been working on creating a div tag to overlay an embed tag and added some javascript to prevent users from right-clicking to download the pdf inside the embed tag (even though it may seem unnecessary, it was requested by my customer). Here is the ma ...

How can I find the hexadecimal color value from this jQuery plugin?

Hey everyone, I've been using this awesome jQuery plugin for a color picker. However, I'm curious about where the hex value of the chosen color is stored when the user selects it. I need to process it and save it to the database. Thanks! If you& ...

The functionality of Croppie is currently not functioning within a jQuery Fancybox popup modal

For my project's image cropping and scaling requirements, I had initially used Jquery Croppie in a popup modal. To display the image in the popup, I utilized fancybox. However, I now face the challenge of integrating the crop and scale functionality w ...

Separate the express node js into a pair

I'm attempting to divide a code into two parts using express. Here is how I approached it: app.js var express = require('express'); var app = express(); var stud = require('./grades'); var port = process.env.PORT || 3000; stud. ...

What is the best way to create a sequential number pattern of 1, 2, 3, 4 in Mongoose?

Is there a way to create a similar pattern without coding experience? I'm not familiar with coding, so looking for guidance. Here is the code snippet in question: array = 1,2,3,4,5 const note = new notedModel ({ _id: array, note: args[1] ...

Is there a way to automatically start a YouTube video using JavaScript?

Is it possible to automatically play a YouTube embedded video after a visitor has been on the site for a certain amount of time, without affecting view count? I am looking for a JavaScript solution that can accomplish this without having to modify the em ...

Utilizing jQuery in your webpack configuration for optimal performance

I encountered some issues while trying to test a simple project that involves using a jQuery function with webpack. The errors occurred during the bundling process and are as follows: ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot ...