Shingirai Sibakwe
Shingirai Sibakwe

Reputation: 1

Check both element clicked and its number

window.onload = function() {
    var elementts = document.getElementsByClassName('cells');
    for(var i = 0; i < elementts.length; i++) {
        var show_clicked = elementts[i];
        if( show_clicked.onclick==true && show_clicked.length==0){
            alert("1");
        }else if( show_clicked.onclick==true && show_clicked.length==1){
            alert("2");
        }else if( show_clicked.onclick==true && show_clicked.length==2){
            alert('3');
        }else{

        }
    }
}

I am trying to check both element clicked and its number javascript. How do you do that?

Upvotes: 0

Views: 48

Answers (2)

JayJamesJay
JayJamesJay

Reputation: 623

You can check if element has been clicked by attaching eventListener to it. For example:

element.addEventListener('click', myFunction);

This code willl fire "myFunction" every click on "element".

In your situation you have a list of elements. You want to determinate which element of the list has been just clicked.

One of the ways you can do it is:

  1. Select list of elements and assign it to variable (as you did)
  2. Convert this list to array
  3. Attach an eventListener to parent element of the list and using bubbling check which of the child element is clicked
  4. If one of the elements stored in array is clicked, fire the function (in the example below - logs to console index of clicked element in array)

It is not the best solution but I hope it shows the general concept of how to solve this problem. And here is the example implementation:

var parentElement = document.getElementById('parentElement')
var elements = document.getElementsByClassName('elements');
var elementsArr = Array.apply(null, elements);

parentElement.addEventListener('click', function(event) {
  if (elementsArr.indexOf(event.target > -1)) {
    console.log(elementsArr.indexOf(event.target));
  }
}, true);

Helpful articles:

Upvotes: 1

Murat Tz
Murat Tz

Reputation: 1

I think window.onload doesn't help you. You need kind of event listener. Just for a simple solution you may try to give consequential id number to your elements which you consider. And you may use below:

window.onclick= function(event){alert(event.target.id);}

This gives you clicked element's id number.

Upvotes: 0

Related Questions