1

I have a piece of code that is executed when the page is fully loaded. The function then gathers all the button elements on my HTML page. From here I loop through getting each button's title attribute and then assign an onclick event to the button that is equal to a function that writes to the console.log with the title.

I have tried various ways of doing this but it is not working. Here is the JavaScript code that I'm working with. Currently all it does is loop through calling the function and logging the tile to the console.log, but this is not supposed to happen. Each time I click the button it should call the function with its title and log that.

window.onload = myPageIsReady;

function myPageIsReady(){

    var myList = document.getElementsByTagName("button");
    var myTitle = [];


    for(var i = 0; i < myList.length; i++){ 
        myTitle[i] = myList[i].getAttribute("title");       
        myList[i].onclick = getMyTitle(myTitle[i]);
    };

    function getMyTitle(myTitle){
        console.log(myTitle);
    };

};
Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

3

call me crazy but...

var myList = document.getElementsByTagName("button");


for(var i = 0; i < myList.length; i++){ 
    myList[i].onclick = function(){
        console.log(this.getAttribute("title"));
    }
};
Nick Avi
  • 1,231
  • 2
  • 7
  • 6
  • That would work, but it is not a good practice as you are always creating an anonymous function for every iteration even though the function does always the same things. – Amberlamps Jun 02 '14 at 21:01
  • @undefined: Well, for this case you could just write `myList[i].onclick = getMyTitle;` and get the value within `getMyTitle()` via `this.getAttribute('title')`. But if it was an arbitrary, calculated value, one could argue to append it to the object and reference via `this` as well: `myList[i].arbValue = i*i;`. – Amberlamps Jun 02 '14 at 21:09
1

You have to set it to an anonymous function:

myList[i].onclick = (function() {
  var currentI = i;
  return function() { 
      getMyTitle(myTitle[currentI]);
  }
})();

(taken from here)

Community
  • 1
  • 1
Andrew
  • 4,953
  • 15
  • 40
  • 58
0

You need to use:

window.onload = myPageIsReady;

instead of

window.onload = myPageIsReady();

The following is my solution, it creates one function getMyTitle and assigns it to onclick. Here is an example link of the code: http://jsfiddle.net/3Xg3s/6/

window.onload = myPageIsReady;

function getMyTitle() {
    alert(this.title)
};

function myPageIsReady() {
    var myList = document.getElementsByTagName("button");
    for (var i = 0; i < myList.length; i++) {
        myList[i].onclick = getMyTitle;
    };
};
g2guo
  • 26
  • 3