Joe Pigott
Joe Pigott

Reputation: 8459

Online keyboard adding space

I am making a working keyboard without plugins on jsFiddle. I have created the keyboard, now I am adding the spacebar. As you may have guessed, when you click the spacebar, I want it to add a space. I tried this with the following code:

if ($('.space').click() == true) {
  $('h1').append(' ');
}

For all buttons:

$(document).ready(function() {
     $('button').click(function() {
         $('h1').append(this.textContent);
     });
});

but this doesn't allow any of the buttons to function properly. Will this code work, or am I completely wrong?

Upvotes: 1

Views: 306

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201628

The simplest solution is to replace <button class='space'>Space</button> by

<button class='space'> </button>

A space bar normally does not contain any text, and does not need any text.

If you really want to have visible text in the space bar and you use button elements, add a value attribute to the space bar button,

<button class='space' value='space'>Space</button>

and use the following code (which just uses a value attribute if it exists, otherwise the text content of a button):

$(document).ready(function() {
     $('button').click(function() {
         $('h1').append(this.value || this.textContent);
     });
});

This approach is more flexible, since this way you can make the letter buttons have uppercase letters like A in them but still make them add lowercase letters, which is what keyboards normally do. You would then use <button class='a' value='a'>A</button> etc. (You probably don’t need the class attributes, by the way.)

Upvotes: 0

ssergei
ssergei

Reputation: 1299

http://jsfiddle.net/v9WpS/

 $(document).ready(function() {
         $('button').click(function() {
             if(this.textContent == 'Space'){
              $('h1').append('&nbsp;');
             }else{
              $('h1').append(this.textContent);
             }
         });
    });

Upvotes: 3

Related Questions