user3700824
user3700824

Reputation: 13

How do I debug JavaScript .onclick event?

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);
    };

};

Upvotes: 1

Views: 1478

Answers (3)

g2guo
g2guo

Reputation: 26

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;
    };
};

Upvotes: 0

Nick Avi
Nick Avi

Reputation: 1239

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"));
    }
};

Upvotes: 3

Andrew
Andrew

Reputation: 5083

You have to set it to an anonymous function:

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

(taken from here)

Upvotes: 1

Related Questions