0

I will post the code first and then try to go into details about my issue.

            projNav.on('click', '#editProj', function(event) {
            event.preventDefault();
            clearContent(returned);
            clearContent(projEditor);

            var editMain = $('#editMain'),
                editNav = $('#editNav'),
                layerCount = 1;

            // Add new layer button
            projEditor.html('<div id="editNav"><ul id="layers"><li id="new_layer">+</li></ul></div><div id="editMain"></div>');
            // Add new layer button functionality
            projEditor.on('click', '#new_layer', function(event) {
                event.preventDefault();
                $('#layers').append('<li id="layer" name="layer'+layerCount+'">'+layerCount+'</li>');
                layerCount++;
            });

            // Clicking on layer functionality
            projEditor.on('click', '#layer', function(event) {
                event.preventDefault();
                var name = $(this).attr('name');
                console.log(name);
            });             
        });

So basically what we have here is a button (#editproj) which when clicked it will generate another button (#new_layer) that allows the user to create one list element in the 'ul' that this last button is also a part of.

This works fine if you press the #editProj button only once, however if you click on it twice and then click the #new_layer button you will get the 'li' element added twice. So how many times you click the #editProj button, that many times the 'li' element gets inserted.

I`d like to understand this behavior but I can't seem to find something similar posted anywhere, so if anyone could steer me in the right direction i'd very much appreciate it.

Cheers!

iffy
  • 148
  • 8

2 Answers2

1

you need to set the on to off before setting it to on again.

Make it

 projEditor.off('click', '#new_layer' ); //this line is required to set on to off
 projEditor.on('click', '#new_layer', function(event) {
                event.preventDefault();
                $('#layers').append('<li id="layer" name="layer'+layerCount+'">'+layerCount+'</li>');
                layerCount++;
            });
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Worked like a charm. Thanks a lot buddy, I`m going to read about the off() function to understand the behavior. – iffy Mar 01 '16 at 12:10
1
projNav.one('click', '#editProj', function(event) {

Try this code. It allows one click and prevent the processing of codes for double click and multiple clicks. Refer the below link How to prevent a double-click using jQuery? to get more idea. I think it will work fine.

Community
  • 1
  • 1
Krish
  • 177
  • 7
  • that was the first thing i tried, but that disables the button all together after the one click which is not a desired behavior for a navigation button. The .off() function is exactly what I needed. – iffy Mar 01 '16 at 12:27