Home > Enterprise >  Element click event removed after adding new element with AJAX
Element click event removed after adding new element with AJAX

Time:01-29

I am trying to make a gallery app with dynamically loaded images with python flask framework and vanilla JS. Also, I made a full image viewer, so when you click on an image, it opens in a larger scale.

When I open the page for the first time, all works fine. But when load new images, the event, that triggers full viewer is removed on all images in gallery.

What's the reason?

Here is code.

Python. Sending list of images url:

@app.route('/loadmore', methods=['GET'])
def load_more():
    return jsonify(get_images(5))

JS. XMLHttpRequest to get images url's:

function loadMore() {
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      addImages(xhr.responseText);
    }
  };

  xhr.open("GET", "/loadmore", true);
  xhr.send();
}

JS. Adding new images to HTML:

function addImages(paths) {
  let images = document.getElementById("images");
  paths = JSON.parse(paths);
  paths.forEach((path) => {
    images.innerHTML  = `<img  src="static/images/${path}">`;
  });
}

Before loading new images

Before loading new images

After loading new images

After loading new images

CodePudding user response:

One of the solutions: add event listener every time, when load new images.

add new images to HTML

function addImages(paths) {
  let images_grid = document.getElementById("images");
  paths = JSON.parse(paths);
  paths.forEach((path) => {
    images_grid.innerHTML  = `<img  src="static/images/${path}">`;
  });

  addClickEvent();
}

add event listener

function addClickEvent() {
  const images = document.querySelectorAll(".grid-image");
  images.forEach((el) => {
    el.addEventListener("click", (e) => {
      full_viewer.children[0].setAttribute("src", e.target.getAttribute("src"));
      full_viewer.classList.toggle("hidden");
    });
  });
}

CodePudding user response:

you can add event on every img tag .

function full_image_viewer(){}

function addImages(paths) {
  let images = document.getElementById("images");
  paths = JSON.parse(paths);
  paths.forEach((path) => {
  const img = document.createElement('img')
  img.className = 'grid-image';
  img.src = `static/images/${path}`;
  img.addEventListener('click',full_image_viewer )
  images.insertAdjacentElement('beforeend',img)
  });
}

  • Related