Posts

Showing posts from September, 2015

Looping & Closure

Image
Here is simple code to dynamically create set of buttons that greet in different languages. document.body.onload = createButtons; function createButtons() { var greetings = [ {lang:'English', msg:'Good Morning !!'}, {lang:'German', msg:'Guten Morgen !!'}, {lang:'French', msg:'Bonjour !!'}, {lang:'Finnish', msg:'Huomenta !!'} ]; document.createElement('h1'); console.log(greetings); for(var i=0;i<greetings.length; i++){ var greet = greetings[i] var input = document.createElement("button"); input.appendChild(document.createTextNode(greet.lang)); input.setAttribute('class','btn btn-default btn-lg'); input.onclick = function(event){ alert(greet.msg); }; document.body.appendChild(input); } } Pretty simple, looping through array of objects and adding buttons with lan...