HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Double click to edit and add new value to li

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
editclicknewvaluedoubleandadd

Problem

$(document).on('dblclick', '#li', function () {
    oriVal = $(this).text();
    $(this).text("");
    input = $("");
    input.appendTo('#li').focus();

});

$(document).on('focusout', 'input', function () {
    if (input.val() != "") {
        newInput = input.val();
        $(this).hide();
        $('#li').text(newInput);
    } else {
        $('#li').text(oriVal);
    }

});


So far, I still can't do OOP in jQuery. Can you improve the above code?

Solution

I wasn't sure how to answer this, so I went with what your code does...

  • Scope your variables.



  • Change your code to target all li instead of one element with the id li.



  • Use this when events are triggered to make sure you have the correct element.



  • Remove the added elements instead of hiding them.



  • Remember to call on using the smallest possible parent container. Possibly a ` or ?



  • Use short circuiting where appropriate.



  • Use jQuery.parent()` to get the appended elements parent.



Putting all those change together:

var oriVal;
$("#parentUL").on('dblclick', 'li', function () {
    oriVal = $(this).text();
    $(this).text("");
    $("").appendTo(this).focus();
});
$("#parentUL").on('focusout', 'li > input', function () {
    var $this = $(this);
    $this.parent().text($this.val() || oriVal); // Use current or original val.
    $this.remove();                      // Don't just hide, remove the element.
});


Here's the JSFiddle.

Code Snippets

var oriVal;
$("#parentUL").on('dblclick', 'li', function () {
    oriVal = $(this).text();
    $(this).text("");
    $("<input type='text'>").appendTo(this).focus();
});
$("#parentUL").on('focusout', 'li > input', function () {
    var $this = $(this);
    $this.parent().text($this.val() || oriVal); // Use current or original val.
    $this.remove();                      // Don't just hide, remove the element.
});

Context

StackExchange Code Review Q#32520, answer score: 2

Revisions (0)

No revisions yet.