Home > OS >  find image name on click
find image name on click

Time:06-27

I'm trying to do simple thing but not sure how , I have couple images in html I want to click on them and console log on JavaScript the image name.

I would like to put all the images under 1 div so it will be easy to apply some css on them later ,

something like this

<div id="images" onclick="clickImageTest()">
  <img name ="a" src="./notes/a.png">
  <img name ="b" src="./notes/b.png">
  <img name ="c" src="./notes/c.png">
  <img name ="d" src="./notes/d.png">
</div>

the JS function will be :

function clickImageTest(){
  console.log(selectScaleOption);
}

but how do i do the getElement thing? to get each image name

var selectScaleOption = document.getElementsBy*****("images").xxx;

CodePudding user response:

You can loop through your images, and click on each one of them and add it to the other div

const images = document.querySelectorAll('#images img')
const container = document.getElementById('container')

images.forEach(el => el.addEventListener('click', () => {
  console.log(el.name)
  container.innerHTML  = `<img src="${el.src}" alt="${el.alt}" name="${el.name}" />`
}))
img {
  border: 2px solid red;
  padding: 5px;
}

#images {
  display: flex;
  margin-bottom: 20px
}
<div id="images">
  <img name="a" alt="a" src="./notes/a.png" />
  <img name="b" alt="b" src="./notes/b.png" />
  <img name="c" alt="c" src="./notes/c.png" />
  <img name="d" alt="d" src="./notes/d.png" />
</div>

<div id="container"></div>


And to keep with your current code - event delegation - you can do like this:

const images = document.getElementById('images')
const container = document.getElementById('container')

images.addEventListener('click', e => {
  const el = e.target
  console.log(el.name)
  container.innerHTML  = `<img src="${el.src}" alt="${el.alt}" name="${el.name}" />`
})
img {
  border: 2px solid red;
  padding: 5px;
}

#images {
  display: flex;
  margin-bottom: 20px
}
<div id="images">
  <img name="a" alt="a" src="./notes/a.png" />
  <img name="b" alt="b" src="./notes/b.png" />
  <img name="c" alt="c" src="./notes/c.png" />
  <img name="d" alt="d" src="./notes/d.png" />
</div>

<div id="container"></div>

CodePudding user response:

This is called event delegation (having a listener on a common parent instead of adding it to each sibling).It is a very powerful feature especially when you have an unknown number of dynamically created nodes. Having a single listener is much more performant for memory allocation.

You use the event parameter that is sent to the click listener, and there is the event.target property that will give you a reference to the node that triggered the click.

Hope this helps!

  • Related