I have one problem with my function in jQuery. First I will explain what I am trying to do.
I have two elements inside a div, the p element and input element. The element p is visible, and the input element stay hidden. When the user clicks in the p element, the input element will appear (show and focus) and the p element will disappear (hide). When the input field appears, if the user types something and presses enter, a new li element will be added.
This is my current code:
function createFolder() {
// Should be a clickable element
$('#create p').click(function() {
// Hide the p element
$(this).hide();
// Show and focus the createFolder (input field)
$('#createFolder').show().focus();
// If press a key inside input field
$('#createFolder').keypress(function(event) {
// If this key is "enter"
if (event.keyCode == 13) {
// Add a new li element inside menu
$('#menu').append('<li class="expandable"><a href="#">' + $('#createFolder').val() + '</a></li>');
}
});
// Focus out the input field
$('#createFolder').focusout(function() {
// Hide the input field element
$(this).hide();
});
});
}
https://i.stack.imgur.com/LmCG6.png
But I have a problem, when I click in p element or focus out (3 clicks for example), when I type something and press enter, three li elements are added to my menu. It’s like a loop, it counts my clicks and focus out and when I type something, it adds that number of elements. Someone can help me with this? And if is possible, teach me why this happens?
When you call this code:
you’re adding a new event handler for the
keypressevent to that element. The important point is adding, jQuery doesn’t overwrite existing event handlers – every single time you call that piece of code a new event handler is added to the element.And, since that code is within the
clickevent handler for your<p>element, every time you click on that element you’re getting an additional handler for thekeypressevent. If you click three times you have three event handlers, each of which will fire when you press a key.The easiest solution is so simply move that code to bind the
keypressevent handler outside of theclickevent handler for the<p>element.