How can i make a different counter for each photo in js?

Viewed 73

I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?

var count = 0;

function promptImg() {
  var count1 = document.getElementById(test1)
  var count2 = document.getElementById(test2)
  var count3 = document.getElementById(test3)
}
<div id="flowers">
  <div class="1">
    <img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
  </div>
      
  <div class="2">
    <img id="test2" onclick="promptImg()" src="gerbera.jpg">
  </div>
      
  <div class="3">
    <img id="test3" onclick="promptImg()" src="gipsofila.jpg">
  </div>
</div>
7 Answers

If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.

To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.

const counter = { };

function promptImg(img) {
  counter[img.id] = (counter[img.id] || 0) + 1;
  console.log(JSON.stringify(counter));
}
body div {  
  display: flex;
  flex-direction: row;
  grid-column-gap: 1em;
  align-content: center;
}

.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
  <div class="1">
    <img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
  </div>
  <div class="2">
    <img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
  </div>
  <div class="3">
    <img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
  </div>
</div>

Or store the click as a data attribute using dataset.

const counter = { };

const displayClickFrequency = () =>
  console.log(JSON.stringify([...document.querySelectorAll('img')]
    .reduce((map, img) => ({
      ...map,
      [img.id]: parseInt(img.dataset.clicked, 10) || 0
    }), {})));

function promptImg(img) {
  const previousValue = parseInt(img.dataset.clicked, 10) || 0;
  img.dataset.clicked = previousValue + 1;
  displayClickFrequency();
}
body div {  
  display: flex;
  flex-direction: row;
  grid-column-gap: 1em;
  align-content: center;
}

.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
  <div class="1">
    <img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
  </div>
  <div class="2">
    <img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
  </div>
  <div class="3">
    <img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
  </div>
</div>

To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.

Check out MDN's Event Listener page and see the verbose example in the snippet.

// Identifies some elements;
const
  flowersContainer = document.getElementById("flowers"),
  rosaImg = document.getElementById("rosa-img"),
  gerberaImg = document.getElementById("gerbera-img"),
  gipsofilaImg = document.getElementById("gipsofila-img"),
  countersContainer = document.getElementById("counters");

// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
//    for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);

// Defines `handleImageClicks`
function handleImageClicks(event){

  // Listeners can access events, which have targets
  const clickedThing = event.target;

  // Calls `incrementCount` for the selected flower
  if(clickedThing == rosaImg){ incrementCount("rosa"); }
  else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
  else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}

// Defines `incrementCount`
function incrementCount(flowerName){
  const
    // `.getElementsByClassName` returns a list of elements
    // (even though there will be only one element in the list)
    listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
    myMatchingElement = listOfMatchingElements[0], // First element from list
    currentString = myMatchingElement.innerHTML, // HTML values are strings
    currentCount = parseInt(currentString), // Converts to number
    newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
  myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
  <div><span id="rosa-img">Picture of rosa</span></div>
  <div><span id="gerbera-img">Picture of gerbera</span></div>
  <div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
  <div>User clicks on rosa: <span class="rosa"></span></div>
  <div>User clicks on gerbera: <span class="gerbera"></span></div>
  <div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>

You can do it by using an event listener and checking the id of its target element:

document.addEventListener("click", function(element) {
   if (element.target.id === "test1") {
      //do something
   }
});

If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.

You can test it yourself by using the snippet below and clicking the images. Hope this helped.

var images = document.querySelectorAll(".shared-class");

for (i = 0; i < images.length; i++) {
  images[i].addEventListener("click", function() {
  console.log(this)
  })
}
<div>

<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />

</div>

You possibly wat to delegate your clicks to the container - in your case the flowers div

window.addEventListener("load", function() { // on page load
  document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
    const tgt = e.target;
    if (tgt.tagName === "IMG") {
      console.log(tgt.id);
    }
  })
})
img { width: 200px; }
<div id="flowers">
  <div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
  <div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
  <div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>

You can do that with one of there two options:

function promptImg() {
 console.log(event.target);
}


[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
  img.addEventListener("click", () => {
    console.log(event.target)
  })
})
img {
  width: 100px;
  height: 100px;
}
<div class="flowers-with-onclick">
  <img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
  <img onclick="promptImg()" src="gerbera.jpg">
  <img onclick="promptImg()" src="gipsofila.jpg">
 </div>
 
 
 <div class="flowers-with-eventlistener">
  <img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
  <img src="gerbera.jpg">
  <img src="gipsofila.jpg">
 </div>

In your promptImg function if you use jquery, and you should, inside it add

var idClick=$(this).attr("id");

console.log("This link was clicked"+idClick);

and then you can easily IF it

Related