Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes to them, such as a CSS border style when they are clicked.

Below is the HTML/jQuery code:

HTML

<div class="demo-gallery">
  <ul id="lightgallery" class="list-unstyled grid">
    <?php foreach ( $media_items as $item ): ?>
      <li>
         <img class="img-responsive" id="lazy" data-src="<?php echo $item->image_path_sd; ?>">
      </li>
    <?php endforeach; ?>
  </ul>
</div>

Jquery

var picture = document.querySelectorAll('#lazy');
$(picture).each(function () {
    $(document).on('click', /*???*/, function () {
        if ($(/*???*/).data('clicked', true)) {
            $(/*???*/).css("border", "none");
            $(/*???*/).data('clicked', false);
        } else {
            $(/*???*/).css("border", "4px solid #00CE6F");
            $(/*???*/).data('clicked', true);
            console.log($(/*???*/).data());
        }
    });
});

I believe that I need to determine the correct placement for the ??? comments, however, I might be approaching this issue incorrectly.

When I use console.log(picture), it returns an array of all the photos. By console.logging(picture[2]), it displays the third image. This is the behavior I desire, but how do I implement these attributes for each photo individually?

In essence, I aim for users to click on photos they wish to select, highlighting them with a bordered outline to indicate their current selection status.

Answer ā„–1

Utilizing jQuery eliminates the necessity of document functions. Instead, you can retrieve a list of items by targeting elements that share a common attribute (e.g., class name).

The beauty of jQuery lies in the .each(function(){ }) method, which passes the element itself as an argument - accessible via this. Employing $(pictures).each() enables access to individual elements within the set.

Rather than attaching a click listener to the entire document, it's more efficient to apply it directly to each img element.

To display a border, define the style in the CSS file and utilize the

$().toggleClass(/* class name */)
function.

var pictures = $('.lazy');

$(pictures).each(function () {
    $(this).on('click', function () {
    
        if ($(this).data('clicked') == true) {
            $(this).data('clicked', false);
        } else {
            $(this).data('clicked', true);
        }

        $(this).toggleClass('selected');
        
        $(pictures).each(function(index){
          console.log('img #' + index + ': ' + $(this).data("clicked"))
        })
    });
});
.lazy {
padding: 10px;
display: inline;
background-color: red;
margin: 10px;
}

.selected {
  border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">
<img class="lazy" src="#">

Simplified

A condensed version of the previous code block provided by other responses:

$('.lazy').on('click',function(){
  $(this).toggleClass('selected');
  })
.lazy {
  background-color: red;
  padding: 10px;
  box-sizing: border-box;
}

.selected {
  border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="lazy" src="#">
    <img class="lazy" src="#">
    <img class="lazy" src="#">
    <img class="lazy" src="#">
    <img class="lazy" src="#">

Upon submission, simply use $('.lazy.selected') to select all the items marked as selected.

Answer ā„–2

It's important to avoid using the same id selector for multiple tags within an HTML document. Instead, opt for the ".lazy" class selector.

Here is an example:

CSS:

.selected-image{
    border:1px solid #000;
}

jQuery:

$(".lazy").click(function(){
    const img = $(this)
    if(img.hasClass("selected-image")){
        img.removeClass("selected-image")
    }
    else{
        $(this).addClass("selected-image")
    }
})

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

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

Navigate post Ajax call

When I make an unauthenticated GET request using AJAX, my server is supposed to redirect my application. However, when I receive the redirect (a 303 with /login.html as the location), the response tab in the Firebug console shows me the full HTML of the lo ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

Is it possible to turn a <span> element into a clickable hyperlink?

Can a span be turned into a clickable link? I have successfully made a span with only a background image (using the Gilder/Levin image replacement technique) into a clickable link. This seems to work well on my desktop in Chrome, Opera, and IE 11. Is thi ...

Guide to obtaining the current upload progress percentage using jQuery and Node.js

I am currently working on uploading a file using jquery, ajax, express, and nodejs. I am looking for a way to display the progress of the upload process. Perhaps there is a plugin or another method that can help with this. I do not need direct answers po ...

Embedding PHP code within HTML causing functionality issues

I'm attempting to include PHP within CSS, but the outcome is not what I expected. Instead of displaying the desired results, it's showing me the variable names and an echo statement: <!doctype html> <?php require_once("mysqlconnect.php" ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Tips for handling transparent areas during a hover event

Is there a way to make only the rhombus image respond to hover events? I want to exclude the transparent area, as shown in this picture. <img src='http://s30.postimg.org/xpd6gwla9/1_Copy.jpg' id="first"> #first:hover { -moz-box-shadow ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

Python's website scraping: How can I determine the correct reference points in the html structure?

As a novice in the world of programming, I have mainly worked on simple Python projects. Recently, I embarked on a project to create a web scraper using Python with bs4 to extract success stories from a website. These success stories are neatly organized w ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: Here is my attempt at implementation: import MathJax from 'react-mathjax ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

Harnessing the power of lazysizes with WebP

I've been working on optimizing our site through the Google Lighthouse audit, and it's clear that images are a major focus. Right now, my main goal is to address the issue of 'Deter offscreen images' highlighted in the audit. To tackle ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

What measures does Redux take to ensure race conditions do not occur?

Recently, I delved into Redux and grasped the concept very well. However, there is one particular line in the official documentation that puzzled me: Because all changes are centralized and happen one by one in a strict order, there are no subtle race ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

With NodeJs, Mongoose refrains from storing any data in the database

Recently, I encountered a puzzling issue with my code designed to store superhero names and powers in a database. Despite all the connections functioning correctly, I faced an unexpected challenge. When running mongod, I utilized the --dbpath C:/nodeproje ...

Adjust CardMedia Images to match their content in the new MUI 5 version

Iā€™m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

An issue occurred while the request was being transported or processed, resulting in Error code 10 at Path /wardeninit

Currently, I am attempting to pass an object (specifically the contents of a row from a sheet) to an apps script template. The screenshot displays the actual row. https://i.stack.imgur.com/IzMrn.png The function in my apps script consists of the followin ...