3
How to recover the position of a button on the page HTML using Javascript?
The main idea is to add a eventListener on all buttons that have been created on HTML, and when I click the chosen button, it performs the function placed on it. So far it is working normally. The problem is that in the function it fails to recover the position of the clicked button and consequently it does not correctly recover the name of the button to perform the desired comparison to then perform the desired code.
In the code I tried to do, it always returns the first position of the collection of button elements. Soon, it enters only the first if. The desired is to enter inside the if that matches the name of the button.
var buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener("click", message);
}
function message(){
for(var i = 0; i < buttons.length; i++){
if(buttons[i].name == "green"){
alert("GREEN");
break;
}else if(buttons[i].name == "blue"){
alert("BLUE");
break;
}else if(buttons[i].name == "yellow"){
alert("YELLOW");
break;
}
}
}
*{
padding: 0;
margin: 0;
border: 0;
}
.clearfix:after{
content: ' ';
display: block;
clear: both;
}
h1{
font-family: 'ostrich-sans', sans-serif;
border: 1px solid #ccc;
text-align: center;
}
.container{
border: 1px solid red;
min-height: 300px;
}
button{
width: 100%;
height: 90px;
background-color: #222;
color: #ccc;
font-family: 'ostrich-sans', sans-serif;
font-size: 25px;
text-transform: uppercase;
margin-bottom: 10px;
transition: background 1s;
outline: none;
}
button:hover{
background-color: #555;
}
<div class="container clearfix">
<h1>---</h1>
<div class="box-color">
<div class="choose-color">
<button name="green"> Green </button>
<button name="blue"> Blue </button>
<button name="yellow"> Yellow </button>
</div>
</div>
</div>
My answer was helpful?
– Sergio
Of course it was! Thank you for helping me quickly! I just didn’t understand very well why you used this as a solution. It is to reference the positioning of the element?
– Wesley Redfield
When you have an event receiver like this
buttons[i].addEventListener("click", message);
he will call the functionmessage
passing the clicked element asthis
. And thename
is a property of the element from therethis.name
.– Sergio