Tuesday, July 20, 2010

Using Keyboard Shortcuts On You Web Application With jQuery

Here's the basic code:

$(function(){
  $('body').keydown(function(e){
      e.preventDefault();
      if(e.keyCode==13){ // enter
        // action
      }
  });
});
Note: You may use it for a specifc element instead of 'body', for example an input.

At the end of the post you'll find how to do this with "CTRL+Key" actions.

But what are the keycode's? And where do I find them?

Right Here:
Key Pressed Key Code
backspace8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

Using "CTRL + Key" Actions

var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17)
isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
 //run code for CTRL+S return false;
 } 
});

Atalhos de Teclado com jQuery

O código Básico:

$(function(){
  $('body').keydown(function(e){
      e.preventDefault();
      if(e.keyCode==13){ // enter
        // ação
      }
  });
});
OBS: Você pode usar para um elemento específico ao invés do 'body', um input, por exemplo.

No final do post você vai ver como fazer o mesmo para atalhos "CTRL+TECLA".

Mas o que é um keyCode? E onde os encontro?

Aqui:
Tecla (key) Código (Key Code)
backspace8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
; 186
= 187
, 188
- 189
. 190
/ 191
grave accent 192
open bracket 219
back slash 220
close braket 221
' 222

Atalhos "CTRL + Key"

var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17)
isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
 // executa código para CTRL+S return false;
 } 
});

Monday, July 19, 2010

MySql - Updating Duplicated Entries Made Easy

Our example table
CREATE  TABLE IF NOT EXISTS `mydb`.`Counter` (
  `idCounter` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(30) NULL ,
  `hits` INT NULL ,
  PRIMARY KEY (`idCounter`)
);

Our SQL code
INSERT INTO Counter (idCounter,name, hits) VALUES (1,'myBlog',1) 
ON DUPLICATE KEY UPDATE hits=hits+1

As simple as that

CSS3 Cross-Browser

.box_round {
     -moz-border-radius: 12px; /* FF1+ */
  -webkit-border-radius: 12px; /* Saf3+, Chrome */
          border-radius: 12px; /* Opera 10.5, IE 9 */
}

.box_shadow {
     -moz-box-shadow: 0px 0px 4px #ffffff; /* FF3.5+ */
  -webkit-box-shadow: 0px 0px 4px #ffffff; /* Saf3.0+, Chrome */
          box-shadow: 0px 0px 4px #ffffff; /* Opera 10.5, IE 9.0 */
}

.box_gradient {
  background-image: -moz-linear-gradient(top, #444444, #999999); /* FF3.6 */
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #444444),color-stop(1, #999999)); /* Saf4+, Chrome */
            filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#444444', EndColorStr='#999999'); /* IE6,IE7 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#444444', EndColorStr='#999999')"; /* IE8 */
}

.box_rgba {
  background-color: #B4B490;
  background-color: rgba(180, 180, 144, 0.6);  /* FF3+, Saf3+, Opera 10.10+, Chrome */
            filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#99B4B490',EndColorStr='#99B4B490'); /* IE6,IE7 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#99B4B490',EndColorStr='#99B4B490')"; /* IE8 */
}

.box_rotate {
     -moz-transform: rotate(7.5deg);  /* FF3.5+ */
       -o-transform: rotate(7.5deg);  /* Opera 10.5 */
  -webkit-transform: rotate(7.5deg);  /* Saf3.1+, Chrome */
             filter:  progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', 
                     M11=0.9914448613738104, M12=-0.13052619222005157, M21=0.13052619222005157, M22=0.9914448613738104); /* IE6,IE7 */
         -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', 
                     M11=0.9914448613738104, M12=-0.13052619222005157, M21=0.13052619222005157, M22=0.9914448613738104)"; /* IE8 */
               zoom: 1;
}
  
.box_transition {
     -moz-transition: all 0.3s ease-out;  /* FF3.7+ */
       -o-transition: all 0.3s ease-out;  /* Opera 10.5 */
  -webkit-transition: all 0.3s ease-out;  /* Saf3.2+, Chrome */
} 

@font-face {
  font-family: 'WebFont';
  src: url('myfont.eot');  /* IE6+ */
  src: local('☺'), 
        url('myfont.woff') format('woff'),  /* FF3.6 */
        url('myfont.ttf') format('truetype');  /* Saf3+,Chrome,FF3.5,Opera10+ */
}

Source: css3please.com/

Sunday, July 18, 2010

Using label as place holder for input

This is what we will create


So.. now that you see it, let's do it!

CSS
div.form{
    margin:4px;
}

div.form div.simple{
    margin:15px 0px;
}

div.form div.simple input{
    background:transparent;
    min-width:400px;
    padding:7px;
    font-size:15px;
    border:1px solid #aaa;
}

div.form label{
    color:#aaa;
    position:absolute;
    margin-left:5px;
}

Html structure
<div class="form">
    <form action="" method="post">
        <div class="simple">
            <label for="nome">Nome</label>
            <input type="text" name="nome" value="" />
        </div>

        <div class="simple">
            <label for="email">Email</label>
            <input type="text" name="email" />
        </div>

        <div class="action">
            <input type="submit" value="Send" />
        </div>
    </form>
</div>

JS for hidding the label after user inserts a value
$('form input').focus(function(){
            $(this).parent().find('label').hide();
        }).blur(function(){
            if($(this).val()==''){
                $(this).parent().find('label').show();
            }
});

And there you go! As simple as that!

Auto Content Refreshing with jQuery

jQuery is one of the most powerful tools in these days for a web developer
It's so good and so simple! Perfect for us!

So let's show you how to use jQuery to create a simple and efficient auto content refresher.

Html:
<html>
    <head>
        <title>Auto Refreshing Data</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

Javascript:
<script type="text/javascript">
    $(function(){
        var refreshTime = 0;
        
        function refresh(){
            $.get('refresh.php',{},function(callback){
                $('#container').html(callback);
                refreshTime = setTimeout(refresh,15000); // we set the loop
            });
        }

        function cancelRefresh(){
            clearTimeout(refreshTime);
        }
        
        refresh(); // call it for the first time
    });
</script>

Now let's explain it.
$.get() is the jQuery function that send the GET request. $.get has 3 param's, firs is the URL, second params and third is callback.
Something like this:
$.get(url, params,function(callback){...});

The url must redirects to your .php (.html, or any other programming language) that will handle your request, return the result.

The setTimeout function creates a kind of loop, recalling that function every 15000 ms.

To cancel the auto refresh simply call the function cancelRefresh();

Note: You may use $.get, $.post or even $.load.

Atualização Automática de Conteúdo com jQuery

jQuery é uma das ferramentas mais poderosas hoje em dia para um desenvolvedor web.
É tão bom e ao mesmo tempo tão simples! Perfeito para nós :D

Então vamos mostrar para você como usar jQuery para criar um simple e eficiente autalizador automático de conteúdo.

Html:
<html>
    <head>
        <title>Conteúdo Automático</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>
        <div id="receptor"></div>
    </body>
</html>

Javascript:
<script type="text/javascript">
    $(function(){
        var tempoAtualizacao = 0;
        
        function atualiza(){
            $.get('refresh.php',{},function(resposta){
                $('#receptor').html(resposta);
                tempoAtualizacao = setTimeout(atualiza,15000); // we set the loop
            });
        }

        function cancelaAtualiza(){
            clearTimeout(tempoAtualizacao);
        }
        
        atualiza(); // chamamos pela primeira vez a atualização
    });
</script>

Agora vamos entender.
$.get() é uma função do jQuery que envia a requisição GET. $.get tem 3 parâmetros, o primeiro é a URL, o segundo são parâmetros a serem passados (se necessário) e o terceiro é a resposta.

Algo assim:
$.get(url, parametros,function(resposta){...});

A url deve redirecionar para seu arquivo .php (.html ou qualquer outra linguagem) que vai administrar a requisição, retornando a resposta.

A função setTimeout cria uma espécie de loop, chamando novamente a nossa função a cada 15000 ms.

Para cancelar a atualização automática basta simplesmente chamar a função cancelaAtualiza();

OBS: Você pode usar $.get, $.post ou até mesmo $.load.