Encircling the most recently selected image with a border

I have successfully made some <img> elements act like <input type="radio"> buttons and now I want to visually indicate the user's selection by adding a border around the chosen image.

My challenge is that there are multiple rows of images, and I need the user to be able to click on an image in one row, have it stay highlighted, then click on an image in another row without losing the highlight on the previous selection.

.product-info .option img:active
{
    border:1px solid #d9d1d5;
}

Here is an example code snippet:

.images img:active {
    border:3px solid #000;
}
<div class="images">
    <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
</div>

Answer №1

My approach involves avoiding the use of JavaScript and instead mimicking radio-button functionality using HTML and CSS. The concept is to create a radio-button-like behavior with images by utilizing radio buttons and labels...

HTML

<div class="images">
    <input type="radio" name="test" value="1" id="test1">
    <label for="test1">
        <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    </label>
    <input type="radio" name="test" value="2" id="test2">
    <label for="test2">
        <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    </label>
    <input type="radio" name="test" value="3" id="test3">
    <label for="test3">
        <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    </label>
    <input type="radio" name="test" value="4" id="test4">
    <label for="test4">
        <img src="https://cdn.tutsplus.com/net/uploads/legacy/958_placeholders/placehold.gif">
    </label>
</div>

CSS

input[type="radio"] {display:none;}
input[type="radio"]:checked+label img {border:3px solid #000;}

Check out the fiddle

Explanation

By utilizing the default behavior of labels to interact with radio buttons, I use CSS selectors to style the adjacent label when its associated radio button is checked. This approach also allows for easy form submission of radio button values...

Answer №2

Essentially

To implement this functionality, simply listen for the click event on qualifying elements, remove the 'selected' class from all elements, and add it to the clicked one.

$('.radioImg').on('click', function() {
  $('.radioImg').removeClass('selected')
  $(this).addClass('selected');
});
.radioImg.selected {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />
<img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />
<img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />

However, for a more scalable approach

If you have multiple sets of similar elements, you can group them within a parent container, refine the selector to target these groups, and utilize the 'siblings' method to toggle the 'selected' class among adjacent items. This allows for a more adaptable and reusable solution.

$('div .radioImg').on('click', function() {
  $(this).addClass('selected').siblings().removeClass('selected');
});
.radioImg.selected {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />
  <img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />
  <img class='radioImg' src='https://www.gravatar.com/avatar/f62f93c13e2aad52fa08a693ce13da48?s=32&d=identicon&r=PG&f=1' />
</div>

Answer №3

One way to utilize jquery is by checking for images with a specific class. Here's an example:

$("img").on("click", function() {
  //remove the imgClicked class from all images
  $("img").removeClass("imgClicked");
  //add the class to the clicked image element
  $(this).addClass("imgClicked");
});
.imgClicked {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placeholdit.imgix.net/~text?txtsize=19&txt=20%C3%9720&w=20&h=20" />
<img src="https://placeholdit.imgix.net/~text?txtsize=19&txt=20%C3%9720&w=20&h=20" />
<img src="https://placeholdit.imgix.net/~text?txtsize=19&txt=20%C3%9720&w=20&h=20" />

Answer №4

It's really straightforward! You don't even need to add extra CSS.

$('.radioImg').on('click', function() {
  $('.radioImg').css("border","none")
  $(this).css("border","1px solid blue")
});

Answer №5

Learn How to Transform Images into Radio Buttons with this easy guide:

Step 1: HTML..

<label class="radioImageLabel"><input type="radio" name="options" /><img src="abc.jpg" />Option Text </label>

Step 2: CSS..

label.radioImageLabel > input{
display:none;
}

label.radioImageLabel > input:checked + img{
border :1px solid blue;
}

 label.radioImageLabel > input + img{
 cursor:pointer;
 /* Add any additional styling for the image*/
}

label.radioImageLabel > input + img:hover{
cursor:pointer;
 /* Add styling for image on hover*/
}

label.radioImageLabel > input:disabled + img{
cursor: not-allowed;
 /* Add styling for disabled image*/
}

I hope this solution provides clarity on transforming images into radio buttons.

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

Event listener is failing to execute the functions

Even though the inline onmouseover="verdadero()" function is properly set up Upon further inspection, it appears that while the event listener is added to the box element, the function is not being triggered when hovering over it, and console.lo ...

How can one utilize a second drop-down list in asp.net to alter the selected index and visibility of a drop-down list?

I am working on an asp.net application that includes a drop down list with the following structure: <asp:DropDownList runat="server" ID="ddlChanges" CssClass="selectstyle" onchange="javascript:ddlChangesChanged();"> <asp:ListItem Text="-- Select ...

Issues with Firebase-admin preventing writing to the database are occurring without any error messages being displayed

Issues with Firebase admin writing to the database. The database is instantiated as follows: var db = admin.database(); A reference to the desired table is then set up: var systemsRef = db.ref("systems/"); A function is created to check if a 'sys ...

Experiencing difficulties with retrieving form data in req.body using Express and node.js

I am facing an issue while trying to create a registration form for new users with profile picture upload. Despite adding body-parser middleware, the form data is not passing correctly to the route and I cannot identify the reason behind it. Error: D:&bso ...

Change the div attribute when clicking on a corresponding link

For the full code, please visit: https://plnkr.co/edit/6TTLVcsXLV7C1qXSMQV0?p=preview Here is an angular ui bootstrap accordion with nested panels: <uib-accordion close-others="oneAtATime"> <div ng-repeat="sub in subdivisions"> < ...

Update the Bootstrap CSS styling of a button element following a user's click action

I am currently working with Bootstrap and facing an issue where I am trying to change the button color, but after clicking it and moving the mouse away, the color reverts back to blue. Here is the color I initially selected: https://i.sstatic.net/DCMq5.p ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

The issue of MUI components overlapping arises during window resizing

I am currently working on a chat component that includes both the chat display and message input fields. function Chat() { const chatBoxStyles = { bgcolor: "red", height: "70vh", mt: "1rem" }; const messageIn ...

Techniques for finding the total value of a JSON array

After retrieving values from a database, I am using them in JSON/javascript as an array. For example, see https://i.sstatic.net/nLzk9.png The issue arises when trying to calculate the sum of the array elements. I attempted to solve it with this code: v ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

Differentiating between ng-show and ng-if in AngularJS

ng-if and ng-show appear to function in a similar manner. <img src="spinner.gif" ng-if="showSpinner"> <img src="spinner.gif" ng-show="showSpinner"> Are there any distinctions between the two? Is there an impact on performance? How can one d ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

Is there a way to restore a previous version of package-lock.json?

Currently, I am facing the challenge of adjusting a JS/node project that includes a package.json but lacks a committed package-lock.json file. Additionally, the original package-lock.json from the author is not available as newer versions have been develop ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

What is the process for including echo HTML field in the WooCommerce order view?

I have successfully added HTML input fields within functions.php. However, these echoed fields are not displaying in WooCommerce orders after placing an order. I am looking for a way to include the values and labels of these fields in the orders view wit ...

Challenges encountered with Material-UI elements

Attempting to implement the http://www.material-ui.com/#/components/drawer (Docked Example) component from Material-UI in conjunction with ReactJS. An error is encountered with the "=" sign in this line: handleToggle = () => this.setState({open: !this ...

Tips for downsizing a large image to fit into a smaller area

I am working on a page layout that features a small circular navigation element. However, I am facing an issue with fitting a large picture within the boundaries of this small circle without it overflowing and causing alignment problems. Does anyone have ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...

What is the most effective way to retrieve the count of users who have logged in within the past three months by utilizing Jquery

I am seeking to retrieve the count of users who have logged in the last three months utilizing a JSON API and Jquery. This is my current progress: $.getJSON('users.json', function(data) { var numberOfUserLogged = 0; var d1 = ...

Incorporate content from HTML into various sections

Is there a way to dynamically extract the h4 headers and the first sentence from each section of this HTML, and then add them to a new div? function summarize() { let headings = document.getElementsByTagName("h4"); // Get all H4 elements let newsText = do ...