I have a menu that looks like this:
I want to make it possible that when the user clicks on +
the <li>
element that it's located inside becomes like an editable input form, where a new menu item name can be created and saved (by entering the name and clicking Enter).
The code of the current item is
<li id="addNewContext" class="menu-item-divided"><a href="javascript:">+</a></li>
Is there a snippet of code I could use to make that field editable that could save the name entered into an array, which I can then use to repopulate the menu?
Thanks!
HTML5 allows for a ContentEditable attribute to be added to any HTML element. Assign a function to the onclick event for the list item, and make it set the ContentEditable attribute to true.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_Editable
var list = document.querySelector('ul');
var editList = document.querySelector('.edit-list');
editList.onclick = function() {
//or you can use list.setAttribute("contentEditable", true);
list.contentEditable = true;
}
<ul>
<li>list item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li><span class="edit-list">+</span>
</li>
</ul>
JSFiddle as well: http://jsfiddle.net/b8m35wwk/1/
I want to make it possible that when the user clicks on + the
<li>
element that it's located inside becomes like an editable input form, where a new menu item name can be created and saved (by entering the name and clicking Enter).
This sample also remove +
sign on click:
$('#addNewContext')
// on click, make content editable.
.click(function() {
$(this).html("").attr('contenteditable', 'true');
})
// on hit enter,
.keyup(function(e) {
if (e.keyCode == 13) {
var val = $(this).text();
$(this)
// create a new li item
.before("<li>" + val + "</li>")
// set plus sign again
.html("+")
// make contenteditable to false, when clicked the process start again.
.attr('contenteditable', 'false');
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>not edit me</li>
<li>not edit me</li>
<li>not edit me</li>
<li>not edit me</li>
<li id="addNewContext" class="menu-item-divided">+</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With