Milos Nikolic Milos Nikolic - 9 months ago 27
Javascript Question

Return button id on click - JavaScript

I am making a program that is supposed to make a column of buttons on load.
After that, on click, it should make new column of buttons and display id of the button that is clicked.

It works fine when it is supposed to make new column of buttons, but it displays id of every button in the column. It even returns me ids of the next column. Ids of the first button columns are displayed on load.

Can someone help me to make it display just the id of the button that is clicked.
Here is the code:

<html> <head>
.addItem {
width: 80px;
float: left;} </style>
var lev = 0; var levmax=5;var some;

function addBu(){

function repeat(){
var bo = document.getElementById("kod");
var di = document.createElement('DIV');
for (var i=0; i<4; i++){
var bu= document.createElement('BUTTON');
var te = document.createTextNode('Text');
var te1 = document.createTextNode(lev.toString());
var br = document.createElement('BR');*10+i).toString();
bu.addEventListener("click", repeat);
bu.addEventListener("click" , reply_clickk(some));
bo.insertBefore(di, bo.childNodes[0]);

function reply_clickk(clicked_id){

<body id="kod" onload="addBu()">


The problem is you call the event handler and attach its return value to the click event instead of the function.

bu.addEventListener("click" , reply_clickk(some));  

you probably rather want something like this

bu.addEventListener("click" , function(e){reply_clickk(});

In addition your some variable is global; change it to var some to be scoped to your function repeat

var some=(lev*10+i).toString();  

See the JSFiddle