0

How to add javascript function to all div, which are generated dynamically. In _data_grid.html, div bucket is generated dynamically with id forloop.counter0. I want to add common javascript function. Like Show and hide the some portion of div.
All division are different and Want JavaScript function work separatel. How I will do that.

_data_grid.html

   <section id="grid_content">
      {% for row in rows%}
        <div class="bucket" id="bucket{{forloop.counter0}}">
            {{ row.render }}
        </div>
        {% empty %}                             
            {{ table.get_empty_message }}
            {% endfor %}
    </section>

All division will work separately. Please see the following figure, If I click on hidecontent on 1st div then It will hide 1st div on other will hide, If I click on 2nd div then It will hide the 2nd div, no other div will hide.

enter image description here

geeks
  • 1,710
  • 7
  • 37
  • 68

1 Answers1

1

In your javascript later, bind with a delegate.

$(document).ready(function(){
    $('#grid_content').on('click', '.bucket', function(){
        ...whatever logic you need...
    });
});

This will then function on any div with a class of 'bucket' inside the grid_content section.

There seems to be some confusion as to what this will do. The statement is made that if an action is taken on div1 it should only affect div1, and same for div2 and div3.

That is how events work. If you click on div1, it will generate a click event and bubble up to the parent #grid_content. With the delegate above, it will check...is this a click event? yep! Was it created by an element with class bucket? Yep! Then I need to apply this function against it.

At that point, using $(this) inside the function will allow you to reference the individual dom elements of the div that was clicked.

Taplar
  • 24,246
  • 4
  • 18
  • 33