Goal: I am creating an Image Grid where users can select images. When an image is clicked, its border color should change from white to blue, and the image URL should be stored in a selectedImages
variable. Clicking the same image again should remove the blue border and the URL from selectedImages
. The user should only be able to select a maximum of two images, otherwise, a notification is shown. Only the clicked image should have a blue border, not all images.
Problem: The border color in my Image Grid is being applied to all images instead of only the selected image. When an image is clicked, it should have a blue border, and its URL should be stored in a selectedImages
variable. Clicking the same image again should remove the border and the URL from the variable, but currently, the blue border is applied to all images in the grid.
Steps:
- Initialized variables
selectedImages
,selectedImagesColor
andmaxSelections
. - Set the Image Grid data source to
{{ editedPhotoURL.value }}
. - Set the Image Grid source to
{{ item }}
. - Set the border color to
{{selectedImages.value.includes(editedPhotoURL.value[i]) ? 'blue' : 'transparent' }}
. - Added a click event to update
selectedImages
.
Details:
- Event Hander On Click: function handleImageClick(index) {
let currentSelections = [...selectedImages.value]; // Copy current selected URLs
let currentColors = [...selectedImagesColor.value]; // Copy current colors
const selectionIndex = currentSelections.indexOf(editedPhotoURL.value[index]);
if (selectionIndex > -1) {
// Image is already selected, remove it
currentSelections.splice(selectionIndex, 1);
currentColors.splice(selectionIndex, 1);
} else {
// Image is not selected, add it
if (currentSelections.length < maxSelections.value) { // Check if less than 2 images are selected
currentSelections.push(editedPhotoURL.value[index]);
currentColors.push('blue'); // Add 'blue' for new selection
} else {
utils.showNotification({title: 'Please select only two photos '});
}
}
selectedImages.setValue(currentSelections);
selectedImagesColor.setValue(currentColors);
}
handleImageClick(i)
2. ImageGrid1 Border: {{ selectedImages.value.includes(editedPhotoURL.value[i]) ? 'blue' : 'transparent' }}
Video Screen Share: https://www.loom.com/share/32710ce869e34583b4802828371a3c3f?sid=93677661-f516-4fab-89b2-6174ac6bbbe9