Retrieve position or name of a button with javascript

3

How do I retrieve the position of a button on the HTML page using Javascript ?

The main idea is to add an eventListener to all the buttons that were created in HTML , and when I click the button chosen, it performs the function in it. So far it's working normally. The problem is that in the function it can not retrieve the position of the clicked button and consequently it does not correctly retrieve the button name to perform the desired comparison to execute the desired code.

In the code I tried to do, it always returns the first position in the button elements collection. Therefore, it only enters the first if . You want to enter it into the if that corresponds to the button name.

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>
    
asked by anonymous 12.05.2015 / 21:13

1 answer

3

I think you want to use this.name within this callback and not go through button again because it always gives GREEN . In other words, the way you are doing in any part of the code is used the element that was clicked.

Code hint:

function message() {
    var name = this.name;
    if (name == "green") {
        alert("GREEN");
    } else if (name == "blue") {
        alert("BLUE");
    } else if (name == "yellow") {
        alert("YELLOW");
    }
}

jsFiddle: link

    
12.05.2015 / 21:19