Reputation: 1
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
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:
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:
Converting a NodeList to an Array: http://www.jstips.co/en/javascript/converting-a-node-list-to-an-array/
Event Listeners: https://developer.mozilla.org/en-US/docs/Web/API/EventListener
Bubbling: What is event bubbling and capturing?
Upvotes: 1
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