Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettier way to write this script (Hide span on click, show input)

Tags:

html

jquery

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?

like image 270
rac Avatar asked Jan 31 '14 10:01

rac


3 Answers

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/

like image 119
undefined Avatar answered Sep 28 '22 15:09

undefined


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.

like image 29
Hans Roerdinkholder Avatar answered Sep 28 '22 15:09

Hans Roerdinkholder


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();
    });
like image 35
techfoobar Avatar answered Sep 28 '22 16:09

techfoobar