Tips for customizing CSS hover effects using HTML and jQuery scripts

Just a heads up before I ask my question - the code I'm about to share is sourced from this video on YouTube, so all credit goes to the creator.

JS

$(".product-colors span").click(function(){
        $(".product-colors span").removeClass("active");
        $(this).addClass("active");
        $("body").css("background",$(this).attr("data-color"));
        $(".product-price").css("color",$(this).attr("data-color"));
        $(".product-button").css("color",$(this).attr("data-color"));
        $(".product-pic").css("background-image",$(this).attr("data-pic"));
    });
    

HTML

<!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="style.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
      </head>
      <body>
        <div class="product-card">
          <h1>Title</h1>
          <p>Thing<p>
          <div class="product-pic"></div>
          <div class="product-colors">
            <span class="blue active" data-color="#7ed6df" data-pic="url(1.png)"></span>
            <span class="green" data-color="#badc58" data-pic="url(2.png)"></span>
            <span class="yellow" data-color="#f9ca24" data-pic="url(3.png)"></span>
            <span class="rose" data-color="#ff7979" data-pic="url(4.png)"></span>
          </div>
          <div class="product-info">
            <div class="product-price">1.000.000$ </div>
            <a href="#" class="product-button">BUY</a>
          </div>
        </div>
      </body>
    </html>

$(".product-colors span").click(function() {
        $(".product-colors span").removeClass("active");
        $(this).addClass("active");
        $("body").css("background", $(this).attr("data-color"));
        $(".product-price").css("color", $(this).attr("data-color"));
        $(".product-button").css("color", $(this).attr("data-color"));
        $(".product-pic").css("background-image", $(this).attr("data-pic"));
    });
<!DOCTYPE html>
        <html lang="en" dir="ltr">

        <head>
          <meta charset="utf-8">
          <title></title>
          <link rel="stylesheet" href="style.css">
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>

        <body>
          <div class="product-card">
            <h1>Title</h1>
            <p>Thing
              <p>
                <div class="product-pic"></div>
                <div class="product-colors">
                  <span class="blue active" data-color="#7ed6df" data-pic="url(1.png)"></span>
                  <span class="green" data-color="#badc58" data-pic="url(2.png)"></span>
                  <span class="yellow" data-color="#f9ca24" data-pic="url(3.png)"></span>
                  <span class="rose" data-color="#ff7979" data-pic="url(4.png)"></span>
                </div>
                <div class="product-info">
                  <div class="product-price">1.000.000$ </div>
                  <a href="#" class="product-button">BUY</a>
                </div>
          </div>
        </body>

        </html>

I'm looking to change the hover effect of the "product-button" when clicked and change its background, but being new to HTML/CSS, I'm unsure how to do it. Upon researching, I've learned that jQuery is considered outdated - can JavaScript be used instead? Any help would be appreciated. Thank you!

Answer №1

One effective approach is to utilize the active class to highlight the active color.

By employing jQuery's hover() function, we can specify event handlers for both mouseenter and mouseleave events.

Upon triggering the mouseenter event, the color of the current .product-card is set to the active color, while the mouseleave event restores the original color.

This method seamlessly accommodates scenarios with multiple products on a single page, as demonstrated in the example provided below.

Although some may consider jQuery somewhat outdated, it continues to receive regular updates. One of its key advantages lies in abstracting away the need to account for variations in browser implementations. Nevertheless, modern browsers adhere more closely to web standards today, minimizing the distinct benefits of jQuery unless catering to older browsers like Internet Explorer. Despite this, many users still appreciate the succinct syntax offered by jQuery, which remains grounds for its ongoing use. Moreover, since jQuery builds upon JavaScript, any task achievable through jQuery can also be accomplished using plain JavaScript.

$(".product-colors span").click(function() {
  $(".product-colors span").removeClass("active");
  $(this).addClass("active");
});

$('.product-button').hover(function(){
  var $this = $(this);
  var hoverColor = $this.closest('.product-card').find('.product-colors .active').data('color');
  $this.css('color', hoverColor)
}, function(){
  $(this).css('color', '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-card">
  <h1>Product 1</h1>
  <p>Thing</p>
  <div class="product-pic"></div>
  <div class="product-colors">
    <span class="blue active" data-color="#7ed6df" data-pic="url(1.png)">1</span>
    <span class="green" data-color="#badc58" data-pic="url(2.png)">2</span>
    <span class="yellow" data-color="#f9ca24" data-pic="url(3.png)">3</span>
    <span class="rose" data-color="#ff7979" data-pic="url(4.png)">4</span>
  </div>
  <div class="product-info">
    <div class="product-price">1.000.000$ </div>
    <a href="#" class="product-button">BUY</a>
  </div>
</div>

<div class="product-card">
  <h1>Product 2</h1>
  <p>Thing</p>
  <div class="product-pic"></div>
  <div class="product-colors">
    <span class="blue active" data-color="#ff0000" data-pic="url(1.png)">Red</span>
    <span class="green" data-color="#00ff00" data-pic="url(2.png)">Green</span>
    <span class="yellow" data-color="#0000ff" data-pic="url(3.png)">Blue</span>
  </div>
  <div class="product-info">
    <div class="product-price">1.000.000$ </div>
    <a href="#" class="product-button">BUY</a>
  </div>
</div>

Answer №2

If you're looking to trigger a function in Javascript/JQuery when your element is hovered over, you can achieve this by utilizing Jquery's .mouseover method, like so :

$(".product-colors span").click(function(){
    $(".product-colors span").removeClass("active");
    $(this).addClass("active");
    $("body").css("background",$(this).attr("data-color"));
    $(".product-price").css("color",$(this).attr("data-color"));
    $(".product-button").css("color",$(this).attr("data-color"));
    $(".product-pic").css("background-image",$(this).attr("data-pic"));
});

$(".product-button").one('click', function(){
    $(this).mouseover(function() {
      $(this).css("background-color","green");
    });
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
  </head>
  <body>
    <div class="product-card">
      <h1>Title</h1>
      <p>Thing<p>
      <div class="product-pic"></div>
      <div class="product-colors">
        <span class="blue active" data-color="#7ed6df" data-pic="url(1.png)"></span>
        <span class="green" data-color="#badc58" data-pic="url(2.png)"></span>
        <span class="yellow" data-color="#f9ca24" data-pic="url(3.png)"></span>
        <span class="rose" data-color="#ff7979" data-pic="url(4.png)"></span>
      </div>
      <div class="product-info">
        <div class="product-price">1.000.000$ </div>
        <a href="#" class="product-button">BUY</a>
      </div>
    </div>
  </body>
</html>

Keep in mind that while CSS pseudo-class :hover can also be used for adding hover effects to an element, you cannot directly manipulate CSS pseudo-classes in Javascript/Jquery. For more insights on this topic, check out this question

Answer №3

Consider this alternative approach:

Implement mouseover(function(){..} and mouseout(function(){..}

$(".product-button").mouseover(function() {
    $(this).css("background","#ffffff");
    $(this).css("color","#00cc00");
});
$(".product-button").mouseout(function() {
    $(this).css("color","#ffffff");
    $(this).css("background","#00cc00");
});

Test it here:

$(".product-button").mouseover(function() {
    $(this).css("background","#ffffff");
    $(this).css("color","#00cc00");
});
$(".product-button").mouseout(function() {
    $(this).css("color","#ffffff");
    $(this).css("background","#00cc00");
});
.product-card{
  box-shadow:3px 2px 10px #555;
  width:450px;
  height:500px;
  padding:30px;
  margin:0 auto;
}
.product-pic img{
  text-align:center;
  max-width:100%;
  height:auto;
}
.product-button{
  border:3px solid #00cc00;
  color:#ffffff;
  text-decoration:none;
  padding:10px 20px;
  display:inline-block;
  width:100px;
  margin-top: 20px;
  border-radius:30px;
  background:#00cc00;
  text-align:center;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8>
    <title></title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
  </head>
  <body>
    <div class="product-card">
      <h1>The Shoes</h1>
      <p>Shoes<p>
      <div class="product-pic"><img src="https://i.sstatic.net/y5acE.png"></div>
      <div class="product-info">
        <div class="product-price">1,000,000$</div>
        <a href="#" class="product-button">BUY</a>
      </div>
    </div>
  </body>
</html>

Check out the interactive circle demo below for changing button colors and body appearance:

$(".product-button").mouseover(function() {    
    var bgcolor = $(".product-colors span.active").css("background-color");
    $(this).css("background-color","#ffffff");
    $(this).css("border-color",bgcolor);
});
$(".product-button").mouseout(function() {
    var bgcolor = $(".product-colors span.active").css("background-color");
    $(this).css("background-color",bgcolor);
    $(this).css("border-color",bgcolor);
});

//to change color of body 
$(".product-colors span").click(function(){
    $(".product-colors span").removeClass("active");
    $(this).addClass("active");
    var bgcolor = $(this).css("background-color");
    $("body").css("background",bgcolor);
    $(".product-button").css("background-color",bgcolor);
    $(".product-button").css("border-color",bgcolor);
});
.product-card{
  box-shadow:3px 2px 10px #555;
  width:450px;
  height:550px;
  padding:30px;
  margin:0 auto;
  background:#fff;
}
.product-pic img{
  text-align:center;
  max-width:100%;
  height:auto;
}
.product-button{
  border:3px solid #7ed6df;
  color:#111;
  text-decoration:none;
  padding:10px 20px;
  display:inline-block;
  width:100px;
  margin-top: 20px;
  border-radius:30px;
  background:#7ed6df;
  text-align:center;
}
.product-colors span{
  width:30px;
  height:30px;
  display:inline-block;
  border-radius:50%;
  margin-bottom:10px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">>
  <head>
    <meta charset="utf-8"%gt;
    <title></title%gt;
    <link rel="stylesheet" href="style.css"%gt;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8">%gt;</script>
  </head>
  <body>
    <div class="product-card&amp;
      <h1>The Shoes&amp;
      <p>Shoes&amp;
      <div class="product-pic&amp;&lt<img src="https://i.sstatic.net/y5acE.png">%gt;&amp;
      <div class="product-colors>
        <span class="blue active" style="background-color:#7ed6df" data-pic="url(1.png)">&.>
        <span class="green" style="background-color:#badc58;" data-pic="url(2.png)>&.>
        <span class="rose" style="background-color:#ff7979" data-pic="url(4.png)>&.>
        <span class="yellow" style="background-color:#f9ca24" data-pic="url(3.png)>&.>
      </div>
      <div class="product-infot
        <div class="product-price">1,000,000$<&./div>
        <a href="#" class="product-button">BUY</a>
      </div>
    </div>
  </body>
</html>%t;

Answer №4

This exercise involves learning how to add a second group and use classes to toggle colors and the active state. Click on the "colors" and hover over the "button" to see the effects.

Inline comments provide descriptions for each part of the code.

$(".product-colors")
  .on('click', 'span.pick', function(event) {
    // allows for multiple groups
    let group = $(event.delegateTarget).closest(".product-card");
    // retrieve class to toggle
    let classChoice = $(this).data("color");
    // deactivate other active elements within the group
    group.find("span.pick").not(this).toggleClass("active", false);
    $(this).toggleClass("active");
    // set color based on click event
    let toggleMe = group.find(".choice, .product-price");
    toggleMe.removeClass('blue yellow green rose');
    toggleMe.toggleClass(classChoice, $(this).is('.active'));
    group.find(".product-pic").css("background-image", $(this).data("pic"));
  });

// select one option as default, can be achieved in different ways
$(".product-colors")
  .each(function() {
    let thisDefault = ".pick." + $(this).data("default");
    $(this).find(thisDefault).trigger('click');
  });

// display current active color on mouse enter
$(".product-button")
  .on('mouseenter', function(event) {
    let group = $(event.delegateTarget).closest(".product-card");
    let activeChoice = group.find(".product-colors").find('.pick.active').data("color");
    $(this).toggleClass(activeChoice);
  })
  .on('mouseleave', function(event) {
    $(this).toggleClass('blue yellow green rose', false);
  });
.green {
  background-color: #badc58;
}

.yellow {
  background-color: #f9ca24;
}

.blue {
  background-color: #7ed6df;
}

.rose {
  background-color: #ff7979;
}

.pick {
  border: solid 1px white;
}

.active {
  border: solid 1px black;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="style.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div class="product-card">
    <h1>Title</h1>
    <p class="choice">Thing
      <p>
        <div class="product-pic"></div>
        <div class="product-colors" data-default="yellow">
          <span class="blue pick" data-color="blue" data-pic="url(1.png)">blue</span>
          <span class="green pick" data-color="green" data-pic="url(2.png)">green</span>
          <span class="yellow pick" data-color="yellow" data-pic="url(3.png)">yellow</span>
          <span class="rose pick" data-color="rose" data-pic="url(4.png)">rose</span>
        </div>
        <div class="product-info">
          <div class="product-price">1.000.000$ </div>
          <a href="#" class="product-button">BUY</a>
        </div>
  </div>
  <div class="product-card">
    <h1>Pick Me</h1>
    <p class="choice">Other Thing
      <p>
        <div class="product-pic"></div>
        <div class="product-colors" data-default="blue">
          <span class="blue pick" data-color="blue" data-pic="url(1.png)">blue</span>
          <span class="green pick" data-color="green" data-pic="url(2.png)">green</span>
          <span class="yellow pick" data-color="yellow" data-pic="url(3.png)">yellow</span>
          <span class="rose pick" data-color="rose" data-pic="url(4.png)">rose</span>
        </div>
        <div class="product-info">
          <div class="product-price">1.000.000$ </div>
          <a href="#" class="product-button">BUY</a>
        </div>
  </div>
</body>

</html>

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

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Customize default progress bar in browsers

One feature of my website allows users to update their personal information, profile image, background image, and more. After clicking the submit button, a loading screen appears with a progress percentage displayed at the bottom left corner of the page (i ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

Is there a way to customize the background color of the active list item class in Bootstrap 4?

Customizing Boostrap Code : <!-- Custom Sidebar --> <div class="bg-light border-right" id="sidebar-wrapper"> <div class="sidebar-heading"><strong><?= __('Admin Panel') ?></strong></div> <div class="li ...

Using Phonegap to connect to MySQL Database

I am exploring the use of PhoneGap (Cordova3) and my goal is to create a screen that instantly pulls data from MySQL when it loads, allowing users to click on the results to navigate to another page with more details. Do I need to implement jQuery for thi ...

Use jQuery to display the first 5 rows of a table

I recently posted a query on show hide jquery table rows for imported xml data regarding how to toggle visibility of specific table rows using jQuery. Now, I am seeking advice on how to make the first 5 elements always visible within the same context. Belo ...

Getting Started with CSS Alignment - A Novice's Guide

Recently, I embarked on my journey to learn HTML and CSS with the ambition of creating a login page. Although I've successfully crafted a basic version, I'm encountering an issue where the input boxes and labels are misaligned, giving off an unpr ...

Utilizing @Model attributes within a jQuery post request to the controller

Just starting out with asp.net / mvc3 / jquery and more. I've got a jquery datepicker set up and functioning to post data via ajax: $(document).ready(function () { $('#ImplementationStart').datepicker({ onSelect: function (date) ...

MaterialUI AppBar is missing a crucial element

I recently dived into the world of Material UI for React and it's been a good experience so far. However, I've noticed a white gap in my header that I can't seem to get rid of. https://i.sstatic.net/zAZJu.png Here is the snippet from my in ...

Automatically select a radio button upon loading the page

Below is the code I am currently using: jQuery('#choice_1_10_3_1').attr('checked','checked'); I need this radio button to be checked automatically when the page loads. Despite no errors being shown in the console, the code i ...

When a button is clicked in (Angular), it will trigger the highlighting of another button as a result of a value being modified in an array. Want to know the

Currently in the process of developing a website with Angular, I've encountered an unusual bug. The issue arises when using an *ngFor div to generate twelve buttons. <div *ngFor = "let color of colors; let i = index" style = "display ...

How to create an HTML hyperlink in CakePHP version 2.2.1 and above?

Is there an easy way to create an HTML link using the HtmlHelper class in CakePHP 2.2.1? Let's say I have a route set up that maps /finest-perfumes-ever-2012 to the Perfumes/Index Controller/Action. I want the generated link to be: somedomain.com/f ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

How to assign a name to a DOM element using jQuery

Currently, I am delving into the world of jQuery and customizing it to suit my needs. While examining the source code of stackoverflow.com by viewing the source code in a browser, I came across the following snippet: StackExchange.ready(function () { ...

What strategies can be implemented by web publishers to block Amazon Affiliate DEEP-LINKS from redirecting to the Amazon App?

Currently, I am utilizing the Amazon-India affiliate program as a way to generate income from my website. The issue arises when a visitor accesses my site using their mobile browser (specifically Google Chrome) and clicks on one of my affiliate links - ins ...

Switch from using a stylesheet to implementing jQuery

In order to achieve real-time replacement, the style changes immediately after a user interaction: $('link#mystyle').attr('disabled', 'disabled'); $('link#mystyle').remove(); if(new_style){ $('head').ap ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Is it feasible to customize the css3 resize feature?

I'm curious - is there a way to customize the CSS3 resize property? div { resize: both; overflow: auto; } Basically, I am looking for a horizontal resize with a vertical bar instead of the default handle. Take a look at the images for reference. ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...