0

I am creating a website and I have 3 images with border-radius 50% (circled) and they have all a white border. But I need when I click at for example first one it takes a green border. and then if I click on the second image the first one deselects the green border and gets its default border and the second one now gets the green border...

img { border-radius: 50%; border-color: white; }
<img src="."> <img src="."> <img src=".">

1
  • 1
    What have you tried so far? Commented Sep 18, 2021 at 17:29

2 Answers 2

1

A CSS-only solution would be to use checkboxes. Then change the style for the selected checkbox with: input:checked + label img { border: syntax green; }

img { border-radius: 50%; border: 5px solid white; } input { display: none; } input:checked + label img { border: 5px solid green; } /* for styling purpose only */ body { background-color: grey; }
<input type="radio" id="image-1" name="image" value="huey"> <label for="image-1"> <img src="https://via.placeholder.com/100.jpg"> </label> <input type="radio" id="image-2" name="image" value="huey"> <label for="image-2"> <img src="https://via.placeholder.com/100.jpg"> </label> <input type="radio" id="image-3" name="image" value="huey"> <label for="image-3"> <img src="https://via.placeholder.com/100.jpg"> </label>

Sign up to request clarification or add additional context in comments.

Comments

1

Wrap the images in a container element and attach a listener to it so you can use event delegation to catch the click events from the images as they "bubble up" the DOM (rather than adding listeners to all the images), and use a class.

When an image is clicked remove the "green" class from all the images, and add it to the image that was clicked.

const container = document.querySelector('#container'); const images = container.querySelectorAll('img'); container.addEventListener('click', handleClick, false); function handleClick(e) { if (e.target.nodeName === 'IMG') { images.forEach(image => image.classList.remove('green')); e.target.classList.add('green'); } }
img { border: 5px solid white; } .green { border: 5px solid green; }
<div id="container"> <img src="https://dummyimage.com/100x100/000/fff" /> <img src="https://dummyimage.com/100x100/555/fff" /> <img src="https://dummyimage.com/100x100/aaa/fff" /> </div>

2 Comments

this can also apply the class to the container itself and as such apply a border to it. To prevent that I would use img.green as the selector in the CSS. This should prevent the class from doing anything on the container.
Good spot. Thanks. @tacoshy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.