customized hover effect based on the image's specific characteristics

I need to change the background color of a set of images based on which image is hovered over. For example, when I hover over the 5th image, the first 5 images' background color should change. Similarly, when hovering over the 4th image, the background color of the first 4 images should change, and so on for the remaining images. How can I achieve this using CSS?

$(document).ready(function(){
  $("#images img").click(function(){
    var va = $(this).attr("name");
    if(va=='5'){
        $('.two,.three,.four,.one,.five').addClass('active');
    }else if(va=='4'){
        $('.two,.three,.four,.one').addClass('active');
        $('.five').removeClass('active');
    }else if(va=='3'){
        $('.two,.three,.one').addClass('active');
        $('.four,.five').removeClass('active');
    }else if(va=='2'){
        $('.two,.one').addClass('active');
        $('.three,.four,.five').removeClass('active');
    }else if(va=='1'){
        $('.one').addClass('active');
        $('.two,.three,.four,.five').removeClass('active');
    }
    $("#result_value").text(va);
});
$("#images img").mouseover(function(){
    var va = $(this).attr("name");
    if(va=='5'){
        $('.two,.three,.four,.one,.five').addClass('active');
    }else if(va=='4'){
        $('.two,.three,.four,.one').addClass('active');
        $('.five').removeClass('active');
    }else if(va=='3'){
        $('.two,.three,.one').addClass('active');
        $('.four,.five').removeClass('active');
    }else if(va=='2'){
        $('.two,.one').addClass('active');
        $('.three,.four,.five').removeClass('active');
    }else if(va=='1'){
        $('.one').addClass('active');
        $('.two,.three,.four,.five').removeClass('active');
    }
    });
    $("#images img").mouseleave(function(){
        $('.one,.two,.three,.four,.five').removeClass('active');
     });
   });
   <style>
     .clr:hover{
      background-color:#FFD700;
     }

     .active{
  background-color:#FFD700;
     }
   </style>
   </head>

   <body>
    <div class="images" id="images">
     <form name="imagediv" id="imagediv" method="post">
      <img src="star1.png" class="one" alt="Number 1" name="1" width="42" height="42">
      <img src="star2.png" class="two" alt="Number 1" name="2" width="42" height="42">
      <img src="star3.png" class="three" alt="Number 1" name="3" width="42" height="42">
      <img src="star4.png" class="four" alt="Number 1" name="4" width="42" height="42">
      <img src="star5.png" class="five" alt="Number 1" name="5" width="42" height="42">

     </form>
    </div>
     <div class="result_value" id="result_value" ></div>
    </body>

I have implemented logic for both clicking and hovering over the images. However, while the added class should not be removed after click, it should be removed after mouseout during hover. Currently, the class is not being removed upon mouseout, despite applying a mouseout event listener. This seems to affect the functionality for both click and hover actions.

Answer №1

If you want to simplify the process, you can utilize the functions nextAll() and prevAll(). Remember to remove the mouseout event when handling the click event.

$(document).ready(function () {
    var index;
    $("#images img").click(function () {
        var va = $(this).attr("name");
        $(this).addClass("active").prevAll().addClass("active");
        $(this).nextAll("img").removeClass('active');
        index = $("#images img").index(this);
        $("#result_value").text(va);       
    });
    $("#images img").mouseover(function () {
        var va = $(this).attr("name");
 $(this).addClass("active").prevAll("img").addClass('active');
        $(this).nextAll("img").removeClass('active');

    });
    $("#images img").mouseout(function () {
        $("#images img").removeClass('active');
        if(index) {
              $("#images img").eq(index).addClass("active").prevAll("img").addClass("active');
             $("#images img").eq(index+1).removeClass("active");

        }
    });
});

Check out the demo here

Answer №2

Here is a solution that works:

<img src="star1.png" class="s1" alt="Number 1" data-name="1" width="42" height="42">
<img src="star2.png" class="s2" alt="Number 1" data-name="2" width="42" height="42">
<img src="star3.png" class="s3" alt="Number 1" data-name="3" width="42" height="42">
<img src="star4.png" class="s4" alt="Number 1" data-name="4" width="42" height="42">
<img src="star5.png" class="s5" alt="Number 1" data-name="5" width="42" height="42">


$("#images img").click(function(){
    var va = $(this).attr("data-name");
    $(this).prevAll().addClass("active");
    $("#result_value").text(va);
});

$("#images img").mouseover(function(){
    var va = $(this).attr("data-name");
    $(this).addClass("active").prevAll("img").addClass('active');
    $(this).nextAll("img").removeClass('active');
});

$("#images img").mouseleave(function(){
    var va = 1 * $("#result_value").text();

    if(va > 0) {
        $('.s' + va).addClass('active').prevAll("img").addClass('active');        
        $('.s' + va).nextAll().removeClass('active');
    }
    else {
        $("#images img").removeClass('active');
    }
});

Try switching all class names to "s1, s2, ..." instead of "one, two...". It makes it easier to generate those class names programmatically as needed. Also, avoid using the name attribute for elements other than form inputs. Consider using HTML5 and the data- attributes instead.

Check out the fiddle here.

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

Transfer password securely through an ajax call

Is it secure to send a password through an Ajax request? I have a login box that makes an Ajax request to check the login credentials and receive a JSON Object with any errors. Would it be better to use form redirection instead? [EDIT] Storing the encry ...

The responsive class seems to be malfunctioning within the Laravel 5.3 framework

I have a project that involves Laravel and Vue.js. In my Laravel project, I am importing Bootstrap CSS using the following line: // Bootstrap @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; This import is done in the app.scss file. ...

Creating a stripped box shadow with just HTML and CSS - a simple guide

Hey there! I'm trying to create a navbar button with a cool stripped box shadow effect when hovered, similar to what you see in this image link. I attempted to achieve this using CSS box-shadow and linear gradient, but unfortunately it didn't qui ...

Identify the key in an array of objects that corresponds to the highest volume value, and return both the key and its

I am working with an array of objects that include a baseAsset key and Volume for each object, with the volume value varying between objects. My goal is to find the object with the highest volume value based on a match with the baseAsset ...

What steps can I take to ensure my website is optimized for a seamless viewing experience on all mobile devices

Could you please check out the link on your smartphone and let me know if it looks a bit off to you? I have centered everything and the website looks fine on desktop, but on my iPhone 5S, it doesn't seem to display properly. Is there a way to make it ...

Using Express.js to send a response while simultaneously executing a background task

When working with Express.js, I have a need to execute a task after sending a response. My main goal is to minimize the response time and send back the response immediately without waiting for the task results to be returned to the client. The task itself ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

Font consistency varies between different operating systems or machines

I have been experiencing a strange issue with the "Populaire" font that I am using. On my laptop, the font appears perfectly without any distortion on all browsers. However, when viewed on other systems (not all, but some), it becomes distorted across all ...

Is there a way to integrate a d3 force directive graph for use with AngularJS?

I have successfully created a D3 force directive graph using plain JavaScript. If you want to see the working D3 graph, click on this link. Now my goal is to fetch data from a service and display the graph in AngularJS. I am wondering how I can turn this ...

Problems with JQuery Ajax Json Response

Provided Form Section: <script type="text/javascript" src="js/aboneol.js"></script> <h4>Subscribe</h4> <div class="newsletter"> <span id="aboneolerror">< ...

What is the best way to upload a file in Node.js using Express and Multer?

When attempting to send a file from the front end to my node js server, I encountered an issue with receiving the file on the back end. Here is the code snippet: <form id="file-upload-form" class="uploader" action="/uploa ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

upgrading from Internet Explorer 8 to Internet Explorer 9

Similar Topic: Transitioning from IE8 to IE9 Are there any recommendations for transitioning from IE8 to IE9 in order to operate an application smoothly? What factors should be taken into account for CSS, HTML, and JavaScript prior to the migration? ...

Best practices for effectively dismantling a Paper.js Scope

In my web project, I am utilizing multiple Paper.js canvases by creating a new scope for each of them. Due to the AJAX-driven nature of the site, I need to get rid of unnecessary instances when switching between subpages. Unfortunately, there is no built-i ...

bash: The command "nodemon" could not be located

My experience with nodemon has been smooth for the past few months. However, today I encountered an error that I couldn't resolve. Despite uninstalling and reinstalling nodemon, as well as force installing it, I still received the same error message w ...

Having trouble simulating JavaScript Math.random in Jest?

Math.random() seems to always return random values instead of the mocked ones. script.test.js jest.spyOn(global.Math, "random").mockReturnValue(0.123456789); const html = fs.readFileSync(path.resolve(__dirname, "./script.html"), " ...

External UI library for AngularJS

Exploring the realm of animations using Angular and Masonry (UI library) has been quite a journey. I've encountered an issue where animating an element located outside the ng-view works perfectly fine, but the same animation doesn't seem to work ...

Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below var str=offer?; var names = [channelId, channelId, offerType, offerType, Language]; var values =[647, 763, international, programming, English]; Both arrays are the same size. I want to creat ...

Is there a way for me to display the comment count as text directly on the comment bubble image?

In this example on jsfiddle, I am attempting to display the number of comments (12 in this case) as text over the comment bubble image: http://jsfiddle.net/c337Z/ HTML: <ul id="top"> <li><a href="/comments"><div id="commentlink" ...

Combining various arbitrary values, like :has in Tailwind, can be achieved by following these steps

I'm facing an issue where I need to hide an element if it has children. In regular CSS, this is achieved with the following code: &:not(:has(*)){ display: none } However, when trying to implement this in Tailwind, I'm struggling to figure ...