Images that are automatically generated cannot be interacted with by clicking on them

I currently have 4 images loaded onto my website. Whenever I click on one of the images, it becomes highlighted as desired using the following code:

JavaScript Function 1 :

var ImageSelector = function() {
  var imgs = null;
  var selImg = null;

  return {
     addImages: function(container) {
        imgs = container.getElementsByTagName("img");
        for(var i = 0, len = imgs.length; i < len; i++) {
           var img = imgs[i];
           img.className = "normal";
           img.onclick = function()  {
              if(selImg)   {
                 selImg.className = "normal";
              }
              this.className = "highlighted";
              selImg = this;
              urlSet(this.src);
           };
        }
     }
  };
}();

JavaScript Function 2:

var div = document.getElementById("menu");
ImageSelector.addImages(div);

CSS Styling :

   .normal {
      border:none;
   }
   .highlighted {
     border:8px solid #19A3FF;
   }

Additionally, I've implemented a jQuery script that fetches and displays all images from a specific folder. Here is the code snippet:

var dir = "images/";
var fileextension = ".jpg";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location, "").replace("http://example.com/", "");
            $(".menu").append($("<img src=" + dir + filename + " width=300 height=300>"));
        });
    }
});

The corresponding HTML content is as follows:

    <div>
        <div id="menu" class = "menu">
</div></div>

After integrating the jQuery function, the images are successfully displayed but unfortunately they are not clickable anymore. How can I go about ensuring they remain clickable? Any suggestions would be greatly appreciated. Thank you.

Answer №1

Mohit Arora - make sure to invoke your ImageSelector function within the success event after appending the image, or consider utilizing event delegation.

Here's why: you're setting the .onclick function before the images have finished loading. Since ajax calls are asynchronous, they may execute after your code. To ensure that any actions are properly linked to components loaded via ajax, always handle it in the success event.

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

The compatibility of Datatables responsive feature with ajax calls appears to be limited

I recently started using the datatables plugin and have encountered an issue with responsive tables. While I successfully implemented a responsive table and an AJAX call on a previous page, I am facing difficulties with it on a new page for unknown reasons ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

Programmatically adjusting the color of mask images - Creative image theming

Is it possible to alter the color of an image hosted on a different website? Here is a link to an example image: Is there a technique to overlay a specific color on the image and only modify certain colors, such as changing or adding a layer of light gre ...

How can I implement user account functionality with only JavaScript in an Angular frontend and Node.js/Express server?

Many resources I've come across utilize php or a similar language. With an Angular frontend and Node/express server code in place, but no backend yet, I'm uncertain about how to approach user sign-up. ...

Testing jQuery AJAX request with echo on jsFiddle

I'm encountering an issue where the code is displaying 'undefined' instead of appending the response data in HTML format. Can anyone shed some light on what might be causing this? JavaScript: $(function() { $('.document').on ...

Having trouble retrieving cell values from a table using tr and td tags in C# Selenium is causing issues

I'm facing an issue where my code is unable to retrieve the cell value and instead throws an exception stating: "no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div[2]/table/tr[1]/td[0]}" Below is the HTML ma ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...

Retrieving stored information from the browser when making a jQuery AJAX request

I've got this AJAX call written in jQuery that continuously receives JSON responses from the controller and displays them on the screen by setting values (Code to set values is not included below). $(function() { $(".master_status").hide(); setIn ...

Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace th ...

Endless loading on NodeJS server local host

My NodeJS setup is serving files, but the page seems to be stuck loading. Here's a snippet from my index.js file: const express = require("express"); const path = require("path"); const http = require("http"); const socke ...

Controls that shift a DIV in either direction

I've been working on making a div scroll left or right with either a mouseover effect or click, but I can't seem to figure out what's going wrong. My initial attempt was straightforward: <body> <div id="innerscroll"></div> ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Access information from JSON file

Looking to extract data from an external JSON file and store it in a JavaScript array for manipulation? Here is a snippet of the JSON file for reference: "Country":[ { "Country_Name":"India", "Country_Details":[ { ...

Ways to efficiently group and aggregate data in JavaScript, inspired by LINQ techniques

I'm feeling overwhelmed by this. Could you lend a hand? Consider the following .NET classes: Teacher: public class Teacher { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } publ ...

I am experiencing difficulties with the React-router useHistory function

Currently working on a project involving react and nodejs. Utilizing window.location.href to redirect to another page upon successful login, however, attempting to use useHistory for redirection without updating is yielding an error message: Error Uncaugh ...

The attempt to test the AngularJS application using the Jasmine plugin was unsuccessful

I'm currently in the process of learning how to write test cases for my angularJS application. As a beginner, I'm searching for some sample examples of working demos. I came across an example online that uses the Jasmine plugin to test an angular ...

Explore Silverlights assortment using JavaScript

I have embedded a Silverlight class into my page, and in App.xaml.cs this component is registered to allow calls to Silverlight methods from JavaScript, which is functioning correctly. However, I now want to access not just methods, but collections. For e ...

Attempting to retrieve an image from a specified div ID within Android Studio

I find myself at a loss for where to even begin with this issue, so I've been stumbling through it. While I've come across some similar posts, I haven't had any success in making them work. My goal is to utilize the div id to retrieve a spe ...

"Implement a smooth scrolling animation on the page to automatically move a div element upward and lock

I am attempting to create a unique animation for a header div that involves moving it to the top of the screen when the user scrolls down. Once the header div reaches the top, I want it to stay fixed in that position. As the header div moves upwards, it wi ...