Learn how to dynamically change an image when a list item is clicked using only CSS!

When I click on an object, I want to change the image to a different one. The code is organized as follows:

HTML :

<div class="games-platform-item pt-item">
                    <ul class="games-sub-menu clearfix"> 

                            <li class="tab1 current">
                            <img src="../images/abc11.jpg"/ class="topimgG1" ">
                            <span>Editor's Choice</span>
                            </li>

                        <li class="tab2">
                        <img src="../images/abc2.jpg"/ class="topimgG2" ">
                        <span>Slots</span>
                        </li> 

                        <li class="tab3">
                        <img src="../images/abc3.jpg"/ class="topimgG3" ">
                        <span>Table Games</span>
                        </li>

                        <li class="tab4">
                        <img src="../images/abc4.jpg"/ class="topimgG4" ">
                        <span>Jackpot Rewards</span>
                        </li>

                        <li class="tab5">
                        <img src="../images/abc5.jpg"/ class="topimgG5" ">
                        <span>Mini Games</span>
                        </li>    

                        <li class="tab6">
                        <img src="../images/abc6.jpg"/ class="topimgG6" ">  
                        <span>Video Poker</span>
                        </li>    

                        <li class="tab7">
                        <img src="../images/abc7.jpg"/ class="topimgG7" ">
                        <span>All Games</span>
                        </li>     

                        <li class="tab8 games-pt-search" style="display:none;"><span>Search Results</span></li>
                    </ul>

What I am trying to achieve is:

I want the image to change to a colored version when clicked, without using excessive JS or jquery. Can this be achieved using CSS, such as with the .current method?

I need some creative ideas for this.

CSS :

Answer №1

Here's the main concept. It can be greatly enhanced by implementing CSS sprites, which will also eliminate any delay in loading the clicked image. For more information on CSS Sprites, check out: https://css-tricks.com/css-sprites/

I didn't use sprites here because it's difficult to simulate them using placeholder images like I did for the image.

Let's dive into the code. I'll explain what it does and highlight key features afterwards.

/*Hide the Radio Button*/
.games-sub-menu input[type=radio] {
  display: none
}

/*Set a box for the label, this is what is clicked on*/
.games-sub-menu label {
  display: block;
  width: 150px;
  height: 100px;
}

/*Set Images...this would work better with sprites*/
.games-sub-menu label.topimgG1 {
  background-image: url("http://placehold.it/150x100/FF0000/FFFFFF/?text=Image1");
}
.games-sub-menu input[type=radio]:checked + label.topimgG1 {
  background-image: url("http://placehold.it/150x100/?text=Image1");
}
.games-sub-menu label.topimgG2 {
  background-image: url("http://placehold.it/150x100/00FF00/FFFFFF/?text=Image2");
}
.games-sub-menu input[type=radio]:checked + label.topimgG2 {
  background-image: url("http://placehold.it/150x100/?text=Image2");
}
<div class="games-platform-item pt-item">
  <ul class="games-sub-menu clearfix">
    <li class="tab1 current">
      <input type="radio" name="imgSwap" id="rdoImg1">
      <label class="topimgG1" for="rdoImg1"></label>
      <span>Featured Edit</span>
    </li>
    <li class="tab2 current">
      <input type="radio" name="imgSwap" id="rdoImg2">
      <label class="topimgG2" for="rdoImg2"></label>
      <span>Featured Edit</span>
    </li>
  </ul>
</div>

Essentially, the hidden radio button maintains the image state. We then utilize the checked CSS selector along with the adjacent sibling selector + to alter the label's background image. Important Note: the checkbox must precede the label immediately. You could use the general sibling selector, but the checkbox still needs to come before the label.

If the choices aren't mutually exclusive, you can replace radio with checkbox.

A similar outcome can be achieved using links to an ID on the page and leveraging the :target selector. However, this may cause a page jump.

Check out some of my other answers that employ similar concepts:

  • How to edit this nav to make it a click nav instead of a hover nav?
  • All css accordion divs open by default (no jquery)

Answer №2

Easy method using JQuery.

Here is a quick example:

$(function() {
 $('.topimgG1').click(function(){
   // Reset all images to default
   resetAll();
   // Change clicked image to another image
   $(".topimgG1").attr('src',"../img/<another image>");
   return false;
 });
});

function resetAll()
{
 var arrofIDS= ["topimgG1", "topimgG2", "topimgG3"];

 for (i = 0; i < arrofIDS.length; i++) { 
     $("."+arrofIDS[i]).attr('src',"../img/<default img>");
  }
}

Answer №3

.class:active{background-image: url(image.jpg);}

Utilize the active class to temporarily change your image when clicked.

Answer №4

To store an alternative image source, you can follow this method:

<li class="tab2">
    <img data-alt-src="path/to/alt/img" src="../images/abc2.jpg"/ class="topimgG2" ">
    <span>Slot Machine</span>
</li>

Then, implement a script like the one shown below:

<script>
    $(function() {
       $('.topimgG').click(function(){
            var src = $(this).attr("src");
            var altSrc = $(this).attr("data-alt-src");
            $(this).attr("src", altsrc);
       });
    });
</script>

While there may be other solutions with varying levels of JavaScript code, this approach will undoubtedly fulfill your needs.

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

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...

Execute JavaScript function after the reset button has been clicked

Is there a way to execute a function right after the form elements are reset by the <input type="reset"/> button? ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

Increment by 1 until a specific number is reached instead of displaying all numbers within an array

I have an array of numbers and for each number in the array, a request is sent to an external website using the number as a URL variable. The webpage content is then displayed. Instead of manually listing the numbers (1, 2, 3, 4, 5, 6, 7, 8, 9) in the arr ...

Steps for generating a jQuery script to tally the checkboxes that have been ticked

[2]. In my quest to implement a checkbox functionality using jQuery, I have composed the following code snippet:- <!DOCTYPE html> <html lang="en"> <head> <title>Check Box using jQuery</title> </head> <bo ...

The function .click does not function properly when used with an anchor element within a figure tag

In my JavaScript-loaded figure, there is an image description and two buttons. Sometimes the description contains a link with a fig attribute, like this: <a fig="allow" href="#tt5">[1]</a> If the anchor is not in a figure and has a fig attrib ...

The jQuery.ajax converter function is not being triggered

I'm struggling with jQuery.ajax converters - my converter function isn't triggering. This is the simplified jQuery AJAX code I'm using: $.ajax({ url: "http://myurl/myservice", dataType: "JSONP", cache: false, success: ...

Is it possible to turn off the shadow on just one side?

Is there a way to remove the shadow in the red area below? I have come across similar questions but unsure how to implement those solutions here. Live Demo: http://jsfiddle.net/xFa9M/ CSS:- #list li{ border: 2px solid black; border-top-width: 1px; borde ...

Encountered a JavaScript error while using Internet Explorer

My web and Jquery plugins are working flawlessly on various browsers such as Firefox, Chrome, Safari (Windows & OSX), and Android. However, they encounter issues with Windows and Internet Explorer as some JavaScript fails to load. It's frustrating tha ...

How to use Python Selenium to locate the parent element

Here is a snippet of my HTML code: <li> <div class="level1"> <div id="li_hw2" class="toggle open" </div> <ul style="" mw="220"> <li> <div class ="l ...

I am puzzled as to why the frames in my code are failing to display

I'm attempting to create a simple two-frame menu and content system, but I've been struggling to display the frames properly. Here's the snippet of code that I'm working with. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http: ...

Tips for resolving highlighted font awesome Facebook icon issue

Looking to create a circle around a fontawesome social media link. The circle works for most icons, but the Facebook icon is causing issues. The highlight circle does not fit correctly with the Facebook icon. How can this be resolved? .social-media span ...

What is the most effective way to extract data from HTML that contains mathematical notations and convert it into plain text format?

Using BeautifulSoup to extract text from HTML can be a bit tricky, especially when dealing with math tags. Below is the HTML code snippet that uses math tags to display text: <p> <span class="aps-inline-formula"> <math display="inline" x ...

Choose the element that is trapped within the div

I've hit a roadblock with this issue that I just can't seem to figure out. I was working on a practice project creating a Netflix-like webpage, and the select element in the footer containing languages is stuck and won't budge. Here's m ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

Utilize the circliful jQuery plugin within an Angular project

I am currently working on incorporating the jQuery plugin "circliful" into my Angular application. In order to make the circliful graph function properly, I need to define data attributes like: <div id="chart" data-text="30%" data-percent="30">< ...

jQueryUI Dialog box failure

Below is the jQuery code snippet: <script> $(document).ready(function() { $('.class112').click(function() { var msg = $(this).attr('id'); $('#'+msg).dialog({ autoOpen:f ...

What is the most efficient method for including a complete date and time in a URL in asp.net mvc?

I am working with a complete datetime object that I want to include as a parameter in a URL. What is the most effective method to ensure it is fully converted to a C# DateTime object without losing any precision? ...

What is the best way to populate a JSP session with a jQuery value?

Here is the code I need help with: <form name="f"> <input class="btn" type="button" onclick="submitForm()" value="OK" id="submitButton" name="submitButton"/> <input type="text" id="browser_version" name="browser_version" /> <br /> ...

The Bootstrap collapse functionality is malfunctioning

Bootstrap is not my strong suit. I'm struggling with getting the collapse effect to work properly. Can anyone provide some guidance? Here is the link to the bootstrap I am using: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/boo ...