I have this code:
$('body').on('click', 'span.note', function (event) {
$(this).hide();
$(".addnote").show();
});
$('body').on('focusout', '.addnote', function (event) {
if ($(this).val() == "") {
$(this).hide();
$("span.note").show();
}
});
And this is my HTML:
<span class="note">test</span>
<input class="addnote" type="text" style="display:none;">
What it does is: on click it hides the span and displays the input field and when leaving the input field empty and on focusout
it returns the span.
It works but I'm pretty sure there is a prettier way to write this. Can anyone assist me and point out what I could improve. Thanks.
EDIT: Also, i noticed when clicking the text the Input shows but i have to click it again to be able to write, any way to fix so with 1 click it displays the field and the visitor can type in the field?
If the elements are siblings you can also pass an object to the .on()
method:
$('body').on({
click: function() {
$(this).filter('span').hide().next().show();
},
blur: function() {
this.value == '' && $(this).hide().prev().show();
}
}, 'span.note, .addnote');
http://jsfiddle.net/27kYh/
To let the user type immediatly, you only need to set focus to the input element after showing it:
$(".addnote").show().focus();
In my opinion, there's not that much improving that could be done on this piece of code. By itself, it's not badly written. The only thing is, this won't work if you add multiple such controls on the same page, because your selectors aren't specific enough.
You could change:
if ($(this).val() == "") {
to
if (!$(this).val()) {
if you prefer.
Not sure if its prettier, but you can make it a little shorter, if your HTML structure is as in your question.
$('body')
.on('click', 'span.note', function () {
$(this).hide().next('.addnote').show();
})
.on('focusout', '.addnote', function () {
if(!this.value) $(this).hide().prev('.note').show();
});
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