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=".">
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>
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>