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.
CodePudding user response:
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>
CodePudding user response:
This snippet will sort a list of already existing images in place. The images need to be in a common parent container (div#pics
).
let imgs = [...document.querySelectorAll('#pics img')],
div=document.querySelector("div");
document.querySelector("button").onclick=()=>{
imgs.sort((a,b)=>a.name.localeCompare(b.name));
imgs.forEach(img=>div.appendChild(img))
}
<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>
<button>sort</button>