3
\$\begingroup\$
$(document).on('dblclick', '#li', function () {
 oriVal = $(this).text();
 $(this).text("");
 input = $("<input type='text'>");
 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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 10, 2013 at 11:00
\$\endgroup\$
2

1 Answer 1

2
\$\begingroup\$

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

  1. Scope your variables.
  2. Change your code to target all li instead of one element with the id li.
  3. Use this when events are triggered to make sure you have the correct element.
  4. Remove the added elements instead of hiding them.
  5. Remember to call on using the smallest possible parent container. Possibly a <ul> or <ol>?
  6. Use short circuiting where appropriate.
  7. 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("");
 $("<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.
});

Here's the JSFiddle.

answered Dec 11, 2013 at 15:08
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.