0

As I googled out the above mentioned issue, I came across some sources saying, the loop finish executing the click thus when clicking on one of the item in the loop only executes the last one. Some sort of javascript closure issue. However I didn't find the solution to my problem.

I'm displaying chats on a page dynamically. So each chat should bind the click event on the dropdown element within it. Each time the dropdown icon is clicked, dropdown should display.

Now when I click on other chats they don't display the dropdown but only the last chat does.

How to solve this?

HTML

<div class="btn-group ckit-btn-group t-lg-mt--lg t-lg-mr--lg" role="group" data-dropdown-wrapper>
    <button type="button" class="btn btn-default-o btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-inner-toggle-header>
             <i class="fa fa-ellipsis-h"></i>
    </button>
    <ul class="dropdown-menu dropdown-menu-right" data-dropdown-header>
             <li><a href="#" data-view-participants>View Participants</a></li>
             <li><a href="#" data-new-participants>Add Participants</a></li>
             <li><a href="javascript:void(0);" data-leave-conversations>Leave Conversation</a></li>
    </ul>
</div>

SCRIPT

$('[data-inner-toggle]').on('click', function(e) {
    console.debug('click');
    $(this).closest('[data-dropdown]').css('display', 'block');

});

Tried this based on online reference to overcome the so-called closure issue.

$('[data-inner-toggle]').on('click', function(e) {
    console.debug('click');

        var oList = $('[data-inner-toggle]');
        var aListItems = $('[data-dropdown]');
        for(var i = 0; i < aListItems.length; i++) {
            var oListItem = aListItems[i];
            // Here I try to use the variable i in a closure:
            oListItem.onclick = function() {
                console.debug(i);
            }
        }
});
112233
  • 2,406
  • 3
  • 38
  • 88
  • Do your dropdowns all have the same values/structure as the code above? – Sina Dec 14 '16 at 03:50
  • 1
    http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example binding click inside of clicks is normally a bad idea and that loop has a closure issue. – epascarello Dec 14 '16 at 03:52
  • if you wrap your JavaScript Event code with `(function(i){ /* Event code here */ })(i)` within your loop, `i` will get scoped off. Of course, the real question is why use vanilla JS if you're already using jQuery? – StackSlave Dec 14 '16 at 03:56
  • @epascarello, I placed the binding function outside of the loop and it seems to work fine. Thanks for pointing it out. – 112233 Dec 14 '16 at 04:07

0 Answers0