Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Element With EventListener Dynamically in JavaScript

Hi I am struck with this problem.

I need to create a table with Onclicklisteners dynamically. so i prefered this way.

function create_weekmenu(json)
  {
      var column_list=json.week_list;
      var menu_table=document.getElementById("weekmenu");
      var row=document.createElement('tr');
      for(var i=0;i<column_list.length;i++)
      {
        var cell=document.createElement('th');
        var span_ele=document.createElement('span');
        if(span_ele.addEventListener)
        {
          span_ele.addEventListener('click', toggletable(column_list[i]),true);    
        } 
        else if(span_ele.attachEvent)
        { // IE < 9 :(
          span_ele.attachEvent('onclick', toggletable(column_list[i]));
        }
        span_ele.appendChild(document.createTextNode(column_list[i]))
        cell.appendChild(span_ele);
        row.appendChild(cell);
     }
     menu_table.appendChild(row);
  }

The Resultant element Structure I am getting is

<table id="weekmenu">
  <tr>
    <th>
       <span>week_one</span>
    </th>
    <th>
      <span>week_two</span>
    </th>
 </tr>
</table>

But i need a Element Structure like this,

    <table id="weekmenu">
       <tr>
         <th>
              <span onclick="toggle(week_one)'>week_one</span>
         </th>
         <th>
              <span onclick="toggle(week_two)'>week_two</span>
         </th>
      </tr>
    </table>

Further to notice: I could see that the onclick listener is triggering while creating the element. but its not binding with the element permanently.

What would be the solution.

I prefered to construct DOM structure using appendChild() than by .innerHTML or document.write().

like image 355
sam Avatar asked Jan 12 '14 10:01

sam


People also ask

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

How do I create a dynamic DOM element?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

How do you dynamically assign an event listener to a button using JavaScript?

This is a lot simpler than you think, in our function that will create our new element, we need to attach the event handler, and function we want to assign to it, this can be done like so: // Create the new element var li = document. createElement('li'); li. className = 'dynamic-link'; // Class name li.

Can you add an EventListener to a function?

The method addEventListener() works by adding a function, or an object that implements EventListener , to the list of event listeners for the specified event type on the EventTarget on which it's called.


1 Answers

The problem is that you're calling the toggleTable function when you attach it. That's why it's being triggered when you create the element.

span_ele.addEventListener('click', toggletable(column_list[i]),true);

To avoid that it should be:

span_ele.addEventListener('click', toggletable, true);

But obviously that doesn't pass in the column to toggle so it's not ideal.

I would use something like:

function create_weekmenu(json)
  {
      var column_list=json.week_list;
      var menu_table=document.getElementById("weekmenu");
      var row=document.createElement('tr');
      for(var i=0;i<column_list.length;i++)
      {
        var cell=document.createElement('th');
        var span_ele=document.createElement('span');
        if(span_ele.addEventListener)
        {
          span_ele.addEventListener('click', function(col) {
            return function() {
              toggletable(col);
            }
          }(column_list[i]),true);
        } 
        else if(span_ele.attachEvent)
        { // IE < 9 :(
          span_ele.attachEvent('onclick', function(col) {
            return function() {
              toggletable(col);
            }
          }(column_list[i]));
        }
        span_ele.appendChild(document.createTextNode(column_list[i]))
        cell.appendChild(span_ele);
        row.appendChild(cell);
     }
     menu_table.appendChild(row);
  }

You need to make sure you attach a function to the event handler, not the result of a function.

like image 198
scf1001 Avatar answered Sep 24 '22 03:09

scf1001