How to use jQuery toggleClass with single selection - for left and right click events

I have a situation where I need to toggle the selection and de-selection of images within a div. Only one image should be selected at a time, or none at all. I tried using the following code:

function handleImageSelection(img) {
    $("#" + img.id).toggleClass("image_selected");
    $('#snapshotsRpt > img').click(function (e) {
        e.preventDefault;
        $('.image_selected').removeClass('image_selected');
        $(this).addClass('image_selected');
    });
};

However, I noticed that at least one image remains selected at the end, which is not what I want. I want to be able to de-select an image by clicking on it again while still maintaining single select functionality.

The HTML code looks like this:

htmlBody+='<div id="snapshotsRpt">';

if (imgArray && imgArray.length>0){
for (var i=0;i<imgArray.length;i++){
htmlBody+='<img id="'+'Img'+i+'" src="'+imgArray[i].src+'" style="cursor: pointer; height:75%; width: 75%; display: block; margin: 10px; text-align: center;" class="" onclick="handleImageSelection(this);" oncontextmenu="rightClickMenu(this);"></img>';  
}   
} 

htmlBody+='</div><div id="noScreenshot"></div>';

I'm fairly new to jQuery and would appreciate any help with resolving this issue!

Answer №1

If you're looking to optimize performance, consider implementing event delegation in your code:

function loadImages() {
  var htmlBody = '',
    imgArray = [];
  for (var i = 0; i < 10; i++) {
    imgArray.push({
      src: '//placehold.it/100?text=' + (i + 1)
    })
  }

  htmlBody += '<div id="snapshotsRpt">';

  if (imgArray && imgArray.length > 0) {
    for (var i = 0; i < imgArray.length; i++) {
      htmlBody += '<img id="' + 'Img' + i + '" src="' + imgArray[i].src + '" style="cursor: pointer; height:75%; width: 75%; display: block; margin: 10px; text-align: center;" class="" oncontextmenu="rightClickMenu(this);"></img>';
    }
  }

  htmlBody += '</div><div id="noScreenshot"></div>';
  $('body').append(htmlBody);
}

//on dom ready
$(document).on('click', '#snapshotsRpt img', function() {
  console.log('a')
  $('#snapshotsRpt img.htmlView_img_select_toggle').not(this).removeClass('htmlView_img_select_toggle');
  $(this).toggleClass('htmlView_img_select_toggle');
});
.htmlView_img_select_toggle {
  border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="loadImages()">Load</button>

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

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

Card columns with dropdown extending into adjacent column

Encountering a strange problem with the card-columns layout in Bootstrap when using dropdown menus within the cards. The issue arises when the dropdown-menu divs of the lower cards bleed into the next column, despite appearing in the correct position. Thi ...

Is it time to use JQuery post-DocumentReady?

After all the $(document).ready scripts have run, is there a way to register an event that will be executed? I have code that must run after the entire page, including jQuery scripts, has finished loading. Is this achievable? I have to register this in a ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

Div inside is being cutoff by a div with 100% height

I am currently working on a website that has full height and width. I have a fixed panel on the left side and a scrollable main content area on the right side. However, in the main content area, the last div is getting cut off for some reason. I have chec ...

Error occurs when loading AngularJS based on browser version

We have an angularJS application that needs to be compatible with IE8 as well as modern browsers. Due to the lack of support for IE8 in AngularJS 1.3+, our goal is to determine if the browser is IE8 and load either angularJS 1.2.27 or 1.3.14 accordingly. ...

Do any iOS web browsers via CSS support OpenType font characteristics?

OpenType features are supported by the current version of desktop Chrome using CSS. 1) According to my testing, OpenType features are not supported by Safari or Chrome on iOS 5. Is this accurate? (I have confirmed that the -webkit-font-feature-settings CS ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

Quickest method to locate an item within a deeply nested array or object

I am presented with an array of objects, each containing a property that is also an array: const boards = [ { id: 1, name: 'Lorem ipsum', tasks: [ { id: 42, ... }, { id: 65, ... }, { id: 24, ... }, ], }, { ...

Setting the default in jQuery and Rails when the document is ready

Currently, I have a set of anchor tags that serve as a filter. I am utilizing jQuery to find the relevant data tag so that when a name is clicked, it will display all the work done by a developer from a list of completed items. To add a touch of elegance, ...

In Less.js, an action will be taken if the @color equals a specific value

Imagine I have a variable: @title: blue; I want to know if there is a way to use the iscolor function to perform an action if the value is blue. For instance, if @title = blue, import a @mixin into a class named "mytitle". I'm having difficulty gras ...

What could be the reason behind the unexpected outcome of process.argv[3] when its value is set to '*'?

My calculator app is very straightforward: if (process.argv[3]==='+') console.log(parseInt(process.argv[2]) + parseInt(process.argv[4])); if (process.argv[3]==='-') console.log(parseInt(process.argv[2]) - parseInt(process.argv[4])); i ...

Error encountered: Required closing JSX tag for <CCol> was missing

Encountered a strange bug in vscode...while developing an app with react.js. Initially, the tags are displaying correctly in the code file. However, upon saving, the code format changes causing errors during runtime. For instance, here is an example of the ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

How to accomplish multiple tasks at once using jQuery

I'm struggling to find a good way to achieve the following: First, I need to smoothly fade out an image. Next, I must change the image source. Finally, I want to fade the new image back in. The challenge is that the fading out and fading in should h ...

Which database is best suited for making authenticated cross-domain JSON calls?

I have a vision to develop a userscript that can decrypt encrypted text depending on the user who created the text. To achieve this, I am looking to implement a database within the browser to store and retrieve decryption keys. Imagine if Twitter user A w ...

What is the best way to target children elements within individual instances of a specific class?

Below is a snippet of the code I am working with. <div class="row"> <div class="column"> </div> <div class="column"> </div> </div> <div class="row"> <div class="column"> </div&g ...

Using ejs express with node.js to showcase the output of mysql queries

Having trouble with querying my mysql database and displaying the results as a table using express and ejs. Here's the code in my app.js file: var express = require('express'); var app = express(); var bodyParser = require('body-parse ...

Error encountered while attempting to load image through multiple window.print() functions

I am having an issue with printing a receipt containing an image in a for loop when using the code below. The image does not load when multiple prints are done using the for loop (It works fine for a single print), but if I remove the image reference, it ...

Managing the overflow of flex-boxes

I'm currently working on setting up a profiles section on my website featuring 4 profile boxes: https://i.sstatic.net/lWrPA.png While the layout looks good on larger screens, I am facing issues with how the boxes wrap on smaller screen sizes. Right ...