JavaScript/Dicas
JavaScript Rotinas Diversas
[editar | editar código-fonte]Retirados do Editor de JavaScript "1st JavaScript Editor"
Browser code name
<script language='JavaScript' type='text/JavaScript'>
//Made by 1st JavaScript Editor
//http://www.yaldex.com
document.write('<p align=\'center\'><B>'+navigator.appCodeName+'</B></P>');
</script>
Browser language
document.write("<p align='center'><b>");
if (document.all){document.write(navigator.browserLanguage);}
else{document.write(navigator.language)}
document.write("</b></p>");
Browser Name
document.write('<p align=\'center\'><B>'+navigator.appName+'</B><P>');
Browser versão
document.write('<p align=\'center\'><B>'+navigator.appVersion+'</B></P>');
Color Depth
function twentieth() {return (screen.colorDepth);}document.write('<b>Your screen is currently using ' +
twentieth() + 'bit colour.</b>');
Screen Resolução
var fifteenth=0; var sixteenth=0;
if (self.screen) { sixteenth = screen.width;fifteenth = screen.height}
else if (self.java) { var jkit = java.awt.Toolkit.getDefaultToolkit();
var scrsize = jkit.getScreenSize();sixteenth = scrsize.width;fifteenth = scrsize.height; }
document.writeln('<p align=\'center\'>');
if (sixteenth > 0 && fifteenth > 0) {document.writeln('Screen Resolution: ',sixteenth,' x ',fifteenth); }
else {document.writeln('Your screen resolution cannot be determined');}
document.writeln('</p>');
Adicionar aos favoritos
<a href="javascript:window.external.AddFavorite(document.location,'');">Add to Favorites!</a>
Botões coloridos
<head>
<style type="text/css">
.initial2{
font-weight:bold;
background-color:red;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
</style>
<script type="text/javascript">
var fifteenth="";
function sixteenth(seventeenth, nineteenth){var twentieth=window.event? event.srcElement: seventeenth.target;
if (twentieth.tagName=="INPUT"&&twentieth.type=="button")twentieth.style.backgroundColor=nineteenth;}
function third2(fourth2){
if (fifteenth=="")window.location=fourth2;
else if (fifteenth=="_new")window.open(fourth2);
else parent[fifteenth].location=fourth2;}
</script>
<title></title>
</head>
<body>
<form onMouseover="sixteenth(event, 'yellow')" onMouseout="sixteenth(event, 'red')">
<input type="button" value="Get More Products!" class="initial2" onClick="third2('http://yaldex.com')">
</form>
</body>
Link para e-mail
<a href ='mailto:support@yaldex.com?subject=enter subject here &cc=another@youremail.com'>Email Me!</a>
Tornar sua Página Inicial
<a href="#" onClick="this.style.behavior='url(#default#homepage)';
this.setHomePage(document.location);">Click here to make this page your starting page.</a>
Link Descrição on MouseOver
function fifteenth(sixteenth, seventeenth) {var eighteenth,nineteenth,twentieth;
if(!seventeenth) seventeenth=document;
if((eighteenth=sixteenth.indexOf('?'))>0&&parent.frames.length) {
seventeenth=parent.frames[sixteenth.substring(eighteenth+1)].document;
sixteenth=sixteenth.substring(0,eighteenth);
}
if(!(twentieth=seventeenth[sixteenth])&&seventeenth.all) twentieth=seventeenth.all[sixteenth];
for (nineteenth=0;!twentieth&&nineteenth<seventeenth.forms.length;nineteenth++)
twentieth=seventeenth.forms[nineteenth][sixteenth];
for(nineteenth=0;!twentieth&&seventeenth.layers&&nineteenth<seventeenth.layers.length;
nineteenth++) twentieth=fifteenth(sixteenth,seventeenth.layers[nineteenth].document);
if(!twentieth && seventeenth.getElementById) twentieth=seventeenth.getElementById(sixteenth);
return twentieth;}
function first2(second2,twentieth,third2,fourth2) { var fifth2 = fifteenth(second2);
if (fifth2 && (third2.indexOf('style.')==-1 || fifth2.style)){
if (fourth2 == true || fourth2 == false)eval('fifth2.'+third2+'='+fourth2);
else eval("fifth2."+third2+"='"+fourth2+"'");}}
Botão Imprimir
<form>
<input type=button value='Imprimir' onClick='javascript:window.print()'>
</form>
Reload Página
<a href='JavaScript:window.location.reload()'>Click to Reload!</a>
Relógio com Barras Coloridas
<head>
<style type='text/css'>
TH {text-align:right};SPAN {vertical-align:bottom};
</style>
<script language='JavaScript'>
var fifteenth = new Date();var sixteenth = 6;var seventeenth = 3;
function eighteenth() {
with(document.all) {
nineteenth.style.setExpression('width','fifteenth.getHours() * sixteenth * seventeenth','jscript');
twentieth.setExpression('innerHTML','fifteenth.getHours()','jscript');
first2.style.setExpression('width','fifteenth.getMinutes() * sixteenth','jscript');
second2.setExpression('innerHTML','fifteenth.getMinutes()','jscript');
third2.style.setExpression('width','fifteenth.getSeconds() * sixteenth','jscript');
fourth2.setExpression('innerHTML','fifteenth.getSeconds()','jscript')
}
fifth2();
}
function fifth2() {
fifteenth = new Date();
document.recalc();
setTimeout('fifth2()',1000);
}
window.onload=eighteenth;
</script>
<title></title>
</head>
<body>
<TABLE BORDER=0><TR> <TH>Hours:</TH> <TD>
<SPAN ID='nineteenth' STYLE='background-color:red'></SPAN>
<SPAN ID='twentieth'></SPAN></TD></TR><TR>
<TH>Minutes:</TH> <TD>
<SPAN ID='first2' STYLE='background-color:yellow'></SPAN>
<SPAN ID='second2'></SPAN></TD></TR><TR>
<TH>Seconds:</TH> <TD>
<SPAN ID='third2' STYLE='background-color:#00FF40'></SPAN>
<SPAN ID='fourth2'></SPAN></TD></TR></TABLE>
</body>
Data Atual
var data=new Date();
var ano=data.getFullYear();
var dia=data.getDay();
var mes=data.getMonth()+1;
if (mes<10)mes='0'+mes;var hoje=data.getDate();
if (hoje<10)hoje='0'+hoje;
document.write('<code>'+hoje+'/'+mes+'/'+ano+'</code>');
Calendário do ano
function fifteenth(sixteenth) {document.write('<TD ALIGN=center WIDTH=36>'+sixteenth+'</TD>');
}function seventeenth(eighteenth,nineteenth) {
if ((twentieth == eighteenth) && (first2 == nineteenth))document.write('<FONT COLOR=\'#FF000f\'>');
}function second2(third2) {this.length=third2;
for (var fourth2 = 1;
fourth2 <= third2; fourth2++)this[fourth2] = 0;
return this;
}function fifth2(sixth2,fifteenth3,nineteenth) {eighteenth=1;
document.write('<center><TABLE BORDER=3 CELLSPACING=3 CELLPADDING=%3><TR>');
document.write('<TD COLSPAN=7 ALIGN=center><B>'+sixth2+' '+sixteenth3+'</B><TR>');
fifteenth('Sun');
fifteenth('Mon');
fifteenth('Tue');
fifteenth('Wed');
fifteenth('Thu');
fifteenth('Fri');
fifteenth('Sat');
document.write('</TR><TR>');
for (var fourth2=1;
fourth2<seventeenth3;
fourth2++) {document.write('<TD>');
}for (var fourth2=seventeenth3;
fourth2<8;
fourth2++) {document.write('<TD ALIGN=center>');
seventeenth(eighteenth,nineteenth);
document.write(eighteenth+"</TD><FONT COLOR='#000000'>");
eighteenth++;
}document.write('<TR>');
while (eighteenth <= fifteenth3) {for (var fourth2=1;
fourth2<=7 && eighteenth<=fifteenth3;
fourth2++) {document.write('<TD ALIGN=center>');
seventeenth(eighteenth,nineteenth);
document.write(eighteenth+"</TD><FONT COLOR='#000000'>");
eighteenth++;
}document.write('</TR><TR>');
}document.write('</TR></TABLE></center><BR>');
seventeenth3 = fourth2;
}eighteenth3=new second2(12);
eighteenth3[1]='January';
eighteenth3[2]='February';
eighteenth3[3]='March';
eighteenth3[4]='April';
eighteenth3[5]='May';
eighteenth3[6]='June';
eighteenth3[7]='July';
eighteenth3[8]='August';
eighteenth3[9]='September';
eighteenth3[10]='October';
eighteenth3[11]='November';
eighteenth3[12]='December';
nineteenth3 = new second2(12);
nineteenth3[1]=31;
nineteenth3[2]=28;
nineteenth3[3]=31;
nineteenth3[4]=30;
nineteenth3[5]=31;
nineteenth3[6]=30;
nineteenth3[7]=31;
nineteenth3[8]=31;
nineteenth3[9]=30;
nineteenth3[10]=31;
nineteenth3[11]=30;
nineteenth3[12]=31;
twentieth3 = new Date();
twentieth = twentieth3.getDate();
first2 = twentieth3.getMonth()+1;
sixteenth3 = twentieth3.getFullYear();
first4 = new Date('January 1, 19'+sixteenth3);
seventeenth3 = first4.getDay()+1;
if (seventeenth3 == 1){ seventeenth3 = 8;
}for (var second4 = 1;
second4<=12;
second4++){fifth2(eighteenth3[second4],nineteenth3[second4],second4);
}
Habilitar Botão Submit
<script>
var second2;
function fifteenth(sixteenth){
second2=sixteenth;
if (document.all||document.getElementById){
for (seventeenth=0;
seventeenth<second2.form.length;seventeenth++){
var eighteenth=second2.form.elements[seventeenth];
if(eighteenth.type.toLowerCase()=="submit")eighteenth.disabled=!second2.checked;
}
}
}
function first2(sixteenth){if (!document.all&&!document.getElementById){
if (window.second2&&second2.checked)return true;
else{
alert("Please accept terms to submit form");return false;
}
}
}
</script>
<title></title>
</head>
<body>
<form name="agrform" onSubmit="return first2(this)">Remainder of your form here<br>
<input name="agrcheck" type="checkbox" onClick="fifteenth(this)"><b>I agree to these terms</b><br>
<input type="Submit" value="Submit" disabled>
</form>
<script>
document.forms.agrform.agrcheck.checked=false;
</script>
Desabilitar Enter
<script language="javascript" type="text/javascript">
function fifteenth (sixteenth, event) {
var seventeenth = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (seventeenth == 13) { var eighteenth;
for (eighteenth = 0; eighteenth < sixteenth.form.elements.length; eighteenth++)
if (sixteenth == sixteenth.form.elements[eighteenth])
break;
eighteenth = (eighteenth + 1) % sixteenth.form.elements.length;
sixteenth.form.elements[eighteenth].focus();
return false;
}
else
return true;
}
</script>
<title></title>
</head>
<body>
<form>
<input type="text" onkeypress="return fifteenth(this, event)"><br>
<input type="text" onkeypress="return fifteenth(this, event)"><br>
<textarea>Here is some text</textarea>
</form>
</body>
Background Color
<form method="POST" name="background">
<input type="button" value="green" onclick="document.bgColor='green'">
<input type="button" value="blue" onclick="document.bgColor='blue'">
<input type="button" value="orange" onclick="document.bgColor='orange'">
<input type="button" value="gray" onclick="document.bgColor='gray'">
<input type="button" value="red" onclick="document.bgColor='red'">
<input type="button" value="yellow" onclick="document.bgColor='yellow'">
<input type="button" value="black" onclick="document.bgColor='black'">
<input type="button" value="white" onclick="document.bgColor='white'">
</form>
Acesso aos Drives
<form action='file:///a|/'>
<input type='submit' value='A:\ drive'>
</form><p>
<form action='file:///c|/'>
<input type='submit' value='C:\ drive'>
</form><p>
<form action='file:///d|/'>
<input type='submit' value='D:\ drive'>
</form><p>
Última modificação
document.write('Última Modificação ' + document.lastModified);
Detectar Clique com botão Direito
var tenth='';
function ninth() {
if (document.all) {
(tenth);
alert("Enter Your Text Here");
return false;
}
}
function twelfth(e) {
if (document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(tenth);return false;}}}
if (document.layers) {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=twelfth;}
else{document.onmouseup=twelfth;document.oncontextmenu=ninth;}
document.oncontextmenu=new Function('alert("Clicou com o botão direito"); return false')
</script>
OnLoad - evento que ocorre ao abrir uma página
OnUnload - evento que ocorre ao fechar uma página
OnResize - evento que ocorre ao alterar o tamanho (redimensionar) de uma página
Maximizar ao Abrir
window.moveTo(0,0);
if (document.all) {top.window.resizeTo(screen.availWidth,screen.availHeight);}
else if (document.layers||document.getElementById) {
if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
top.window.outerHeight = screen.availHeight;
top.window.outerWidth = screen.availWidth;}}
Validando Formulários com JavaScript
É muito importante a validação de dados entrados pelos usuários com JavaScript, pois torna-se útil aos usuários no caso de erro, quando não perdem os dados que digitaram. Dependendo de como foi elaborado, a página nem é submetida e todos os dados são preservador, precisando apenas corrigir o campo errado e submeter novamente.
Também temos de lembrar de validar os mesmos dados em PHP (se for essa a nossa linguagem do lado do servidor), pois o JavaScript pode estar desativado no navegador do usuário.
Veja uma boa coleção de funções para validação de formulários pelo JavaScript do site:
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateUsername(theForm.username);
reason += validatePassword(theForm.pwd);
reason += validateEmail(theForm.email);
reason += validatePhone(theForm.phone);
reason += validateEmpty(theForm.from);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "The required field has not been filled in.\n"
} else {
fld.style.background = 'White';
}
return error;
}
function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = 'Yellow';
error = "The username is the wrong length.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validatePassword(fld) {
var error = "";
var illegalChars = /[\W_]/; // allow only letters and numbers
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a password.\n";
} else if ((fld.value.length < 7) || (fld.value.length > 15)) {
error = "The password is the wrong length. \n";
fld.style.background = 'Yellow';
} else if (illegalChars.test(fld.value)) {
error = "The password contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
error = "The password must contain at least one numeral.\n";
fld.style.background = 'Yellow';
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {
var error="";
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = 'Yellow';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Yellow';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. Make sure you included an area code.\n";
fld.style.background = 'Yellow';
}
return error;
}
<html>
<head>
<title>WebCheatSheet - JavaScript Tutorial</title>
</head>
<body>
<h1>WebCheatSheet - JavaScript Tutorial</h1>
<form name="demo" onsubmit="return validateFormOnSubmit(this)" action="test.htm">
<table summary="Demonstration form">
<tbody>
<tr>
<td><label for="username">Your user name:</label></td>
<td><input name="username" size="35" maxlength="50" type="text"></td>
</tr>
<tr>
<td><label for="pwd">Your password</label></td>
<td><input name="pwd" size="35" maxlength="25" type="password"></td>
</tr>
<tr>
<td><label for="email">Your email:</label></td>
<td><input name="email" size="35" maxlength="30" type="text"></td>
</tr>
<tr>
<td><label for="phone">Your telephone number:</label></td>
<td><input name="phone" size="35" maxlength="25" type="text"></td>
</tr>
<tr>
<td>
<label for="from">Where are you :</label></td>
<td><input name="from" size="35" maxlength="50" type="text"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Outro site muito bom
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(zip, "Please enter a valid zip code")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function isEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return true;
}
return false;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>CA</option>
<option>TX</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>