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

};
0

3 Answers 3

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"));
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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;.
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)

2 Comments

I've tried doing that but every button i click returns in the log "undefined".
this answer is wrong EDIT: This answer keeps changing
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;
    };
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.