Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
How to sort images on click using vanilla JavaScript

I have a table of 8 images that I need to sort alphabetically when I click on any of the images. The image that has been clicked goes to the first position in the first row of the table. The next position in the first row will be the image whose name is alphabetically right after the name of the first one and so on for the other images. The images are stored in an array called 'flowers'.

Here is what I have so far:

      // Sort Images
  let imgClick = document.getElementsByTagName('img');
  for (var i = 0; i < imgClick.length; i++){
  imgClick.addEventListener("click", flowers.sort((a, b) => (a.name > b.name ? 1 : -1)))
};

The images don't get sorted when I click them.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This snippet will sort a list of already existing images in place. The images need to be in a common parent container (div#pics). By clicking on any of the images this one will be placed at the first position.

let imgs = [...document.querySelectorAll('#pics img')].sort((a,b)=>a.name.localeCompare(b.name));
    div=document.querySelector("div");
div.onclick=ev=>{
  if(ev.target.tagName!=="IMG") return;
  let i=imgs.indexOf(ev.target);
  imgs.slice(i).concat(imgs.slice(0,i)).forEach(img=>div.appendChild(img))
}
img {margin:8px}
<div id="pics">
<img src="pic1" name="c" alt="c"><img src="pic1" name="b" alt="b"><img src="pic1" name="a" alt="a"><img src="pic1" name="d" alt="d">
</div>

about 4 years ago · Juan Pablo Isaza Report

0

I hope this will give you an idea of how to implement that.

const container = document.getElementById("flowers");
const flowers = [
  "rose",
  "peruvian lily",
  "chrysanthemum",
  "orchid",
  "tulip",
  "carnation",
  "hyacinth"
 ].sort();
 
 
function PlaceFlowers(flowers) {
  container.innerHTML = "";
  
   for(let flower of flowers) {
    container.innerHTML += `<button id="${flower}" onClick='sortFlowers(event)'>${flower}</button>`;
 }
}

PlaceFlowers(flowers);
 
function sortFlowers(event) {
  const el = event.target.id;
  const indOfEl = flowers.indexOf(el);
  PlaceFlowers([...flowers.slice(indOfEl), ...flowers.slice(0, indOfEl)]);
}
<div id="flowers"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!