|
home / js
(navigation links)
|
Don't be a know-it-all; be a learn-it-all
|
Coses en JavaScript, CSS i SSI
Assignació i comparació
Hem de diferenciar
var a = 1 ; // assignacio
if ( a == 2 ) { // compara el contingut dels operands
if ( a === b ) { // compara si els operands son iguals i del mateix tipus
Pica aqui per canviar el mode clar / fosc
Aquest element es el que canvia de mode clar/fosc
JS : Alert and Confirm
JS : vols veure la teva adreça IP ?
JavaScript clock's ...
JS2
or
JS3
JS : drop down menu
[font]
JS : vols fer càlculs en Euros ?
JS : escriure a la Status Line
A veure que surt a la Status Line quan passis el cursor per sobre el Link ...
Anar a Yahoo !
JS : a "live" clock
JS : links sense subratllat
Is this "link" underlined ?
I guess NO !
How did I do it ?
JS : rotulador groc
A veure com pots aconseguir de tenir
aquest texte subratllat
si no es mitjançant JavaScript.
JS : detecció del navigador client
Tested Browsers
| Amaya |
Not installed (W 95/NT, Unix) |
|
| Arena |
Not installed (X11/unix) |
|
| BroadPage |
Not installed. W95/98/NT/2000/ME/XP. Requires IE4 or later. |
|
| Dillo |
Not installed |
Fast
and
graphical.
Here's a
comment in
Linuzgazette
|
| Enigma |
Not installed |
|
| Express |
Not installed |
Works in X with GNOME installed |
| Galeon |
Not installed |
|
| gzilla |
Not installed |
|
| Konqueror |
Not installed |
|
| links |
Not installed |
Text-only |
| lynx |
No, not scfy'd.
Let's wait for
PIX
. |
|
|
Mosaic by NCSA. |
Not installed |
|
| Mozilla |
Not installed |
|
| Netscape |
Yes, 4.73 |
|
| MS IE |
Yes, 5.0 |
|
| Opera |
Yes, 5.0 under RH 6.2 |
No mostra el símbol de Euro ( € ),
but 6.01 does. |
| Skipstone |
Not installed |
|
| w3m |
Not installed |
Free-form cursor
control
|
Aquí hi ha una
comparació
I una llista
llarga.
Aquí hi ha una
guia.
ls meus
CSS
El CSS es un modus d'especificar el estil d'una pàgina.
Si mires el HEAD d'aquesta pàgina,
veuràs la manera de fer que els links no estiguin subratllats.
I el fitxer "sagstyle.css" fa que els H1 surtin en vermell
i el SPAN sigui "big blue" ...
SSI
SSI are a feature of some Web servers.
webreference
The syntax for a server side include directive is:
<!--#command parameter="argument" -->
Each directive requires a parameter and each parameter takes an argument.
There are six server include commands :
- include The include command allows you to include an external file in an HTML page.
En aquesta mateixa pàgina hi ha un exemple.
- echo
- config
- exec
- flastmod
- fsize
Exemples :
| Today is
| (echo var DATE_LOCAL)
|
|
| Date last update
| (amb FLASTMOD)
|
|
| Date last update
| (echo var LAST_MODIFIED)
|
|
| IP address
| (echo var REMOTE_ADDR)
|
|
|
Avui és
i ara son les
|
Aquest fitxer té bytes.
|
SSI : exec
exec ls -Ral
-R = list directories recursively
-a = do not hide entries starting with "."
-l = use long listing format
|
|
See DiskUse.shtml
|
exec du -sk
|
|
|
Espai total de disk que ocupo, en Kbytes.
Max is 20 MB [Estiu 2004] !
|
exec uname -a
|
|
Proves
- Floquets - uns floquets en molla segueixen el cursor
- CometClk - un rellotge segueix el cursor
- NEU - cauen floquets de neu o fulles d'arbre
- WAR - comptador dinamic
Some concepts
jQuery fundamentals,
JS basics
Objects
An object is a container of properties, where a property has a name and a value.
Object literals
Object literals provide a very convenient notation for creating new object values.
An object literal is a pair of curly braces surrouding zero or more name/value pairs.
var empty_object = {} ;
var stooge = {
"first-name" : "Jerome",
"last-name" : "Howard"
} ;
Retrieval
Values can be retrieved from an object by wrapping a string expression in a [] suffix.
If the string is a constant, and if it a lega JavaScript name and not a reserved word,
then the . notation can be used instead.
stooge["first-name"] // "Joe"
flight.departure.IATA // "SYD"
Reference
Objects are passed around by reference. They are never copied.
var x = stooge;
x.nickname = 'Curly';
var nick = stooge.nickname;
// nick is 'Curly' because x and stooge are references to the same object
Enumeration
Enumerating
Framework
JavaScript wont be used on its own : a framework is required.
We shall use jQuery !
Parameter passing
Per referencia
The Good Parts, pg 22, d'en Douglas Crockford, alias "el Deu de JS"
Objects are passed around by reference.
They are never copied
var x = stooge;
x.nickname = 'Curly';
var nick = stooge.nickname;
// nick is 'Curly' because x and stooge are references to the same object
Another:
function setName(obj) {
obj.name = "Enric";
}
var person = new Object();
setName(person);
alert(person.name); // "Enric"
Per valor
c:\sebas\JavaScript\pas-de-parametres> type params.js
function f (b) { b = 5 ; } ;
var a = 7 ;
f(a) ;
console.log( 'A is = (%s).', a ) ;
I el crido :
c:\sebas\JavaScript\pas-de-parametres> node params.js
A is = (7).
Tenim:
function setName(obj) {
obj.name = "Enric";
obj = new Object(); // compte amb el "new" !
obj.name = "Sebastiá";
}
var person = new Object();
setName(person);
alert(person.name); // "Enric"
// si es pases per referencia: alert(person.name) sería "Sebastiá"
More concepts
Difference between "id" and "class"
When will we use "id" and when shall we use "class" ?
<li><a href="#" id="clkHelp">ajuda</a></li>
<li><a href="#" class="clkInici">Inici</a></li>
Quite clear:
$( "#clkHelp" ).click( function() {
$( ".clkInici" ).click( function() {
click events
First method
HTML :
<div id="myDiv">Some Content</div>
jQuery :
$('#myDiv').click(function(){
//Some code
});
Second method
HTML
<div id="myDiv" onClick="divFunction()">Some Content</div>
JavaScript function call
function divFunction(){
//Some code
}
url
"for" loop versus "forEach"
Loop :
for ( var i = 0 ; i < json_llista_de_la_compra.length ; i++ ) {
var my_id = json_llista_de_la_compra[i].numid ;
var my_txt = json_llista_de_la_compra[i].producte ;
} ; // for
ForEach :
json_llista_de_la_compra.forEach( function (obj, index) {
var my_id = obj.numid ;
var my_txt = obj.producte ;
console.log( ">>> idx " + index, ", id " + my_id + ", txt " + my_txt ) ;
}) ; // for each
Hiding/unhiding a link
With jquery in the head
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
With this HTML
<a href="#" id="clkHelp">ajuda</a>
<a href="#" id="clkAdmin">do admin (env.foo)</a>
You can do
$( '#clkAdmin' ).hide() ; // http://api.jquery.com/hide/
$( '#clkAdmin' ).show() ; // http://api.jquery.com/show/
JavaScript date() - creating timestamps
Nice
article :
a date in JavaScript is represented behind the scenes as the number of milliseconds since midnight on January 1st, 1970 (01-01-1970 00:00:00).
High Resolution API.
Ens convé molt crear un parell de funcions:
// noves funcións yyyyymmdd i hhmmss de Date()
Date.prototype.yyyymmdd = function () {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '/' + (mm[1]?mm:"0"+mm[0]) + '/' + (dd[1]?dd:"0"+dd[0]);
} ; // yyyymmd
Date.prototype.hhmmss = function () {
function fixTime(i) {
return (i < 10) ? "0" + i : i ;
} ; // fixTime()
var today = new Date(),
hh = fixTime( today.getHours() ),
mm = fixTime( today.getMinutes() ),
ss = fixTime( today.getSeconds() ) ;
var myHHMMSS = hh + ':' + mm + ':' + ss ;
return myHHMMSS ;
} ; // hhmmss
Ara podem fer servir
var szAra = '<center>[' + (new Date).yyyymmdd() +','+ (new Date).hhmmss() + ']</center>' ;
$( "#my_date" ).html( szAra ) ; // show actual date
Una altra implementació:
var mytoday = new Date() ;
var dd = mytoday.getDate() ;
var mm = mytoday.getMonth() + 1 ; // January is 0!
var yyyy = mytoday.getFullYear() ;
if ( dd < 10 ) {
dd='0'+dd
}
if ( mm < 10 ) {
mm='0'+mm
}
sztoday = mm + '/' + dd + '/' + yyyy ;
$( '#ocupacio_1_dia>thead>tr>th:nth-child(1)' )
.css( 'color', '#000000')
.append( sztoday ) ;
Compta amb la diferencia:
var ara = Date.now() ; // returns the number of milliseconds from 01 January, 1970 of the current time in UTC.
undefined
ara
1424879960370
Veure
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
Mentre que
var ara = new Date()
undefined
ara
Wed Feb 25 2015 16:58:49 GMT+0100 (Romance Standard Time)
Aqui podem fer servir ".toISOString():"
var ara = new Date()
undefined
var sAra = ara.toISOString()
undefined
ara
Wed Feb 25 2015 17:03:57 GMT+0100 (Romance Standard Time)
sAra
"2015-02-25T16:03:57.033Z"
<script> (best) ubication
Between
</body>
and
</html>
</main>
<footer>© 2013 Lo Pere Productions. All Rights Reserved.</footer>
</body>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='jquery-ui.js'></script>
<script type='text/javascript' src='padates.js'></script>
<script type='text/javascript' src='reservasclient.js'></script>
</html>
Compte : dins un HTML nomes hi pot anar HEADER i BODY {LCM, 20150304}
jQuery DOM Ready event
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.
// A $( document ).ready() block.
$( document ).ready( function() {
console.log( "ready!" ) ;
} ) ;
Experienced developers sometimes use the shorthand $()
// Shorthand for $( document ).ready()
$( function() {
console.log( "ready!" ) ; // do stuff after DOM has loaded
} ) ;
If you want a checkable variable, you can set one in the ready-function:
var documentIsReady = false ;
$( function () { documentIsReady = true ; } ) ;
Complete sample:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
});
$( window ).load(function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<iframe src="http://techcrunch.com"></iframe>
</body>
</html>
learn jQuery
client load timestamp
I want to timestamp the client page load time - see this page source
Se we include in the cliente page, lets say "index.htm" this code :
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="dom_timestamp.js"></script>
</body>
And we generate the timestamp in the file we iclude, dom_timestamp.js :
Date.prototype.yyyymmdd = function () {
var yyyy = this.getFullYear().toString() ;
var mm = (this.getMonth()+1).toString() ; // getMonth() is zero-based
var dd = this.getDate().toString() ;
return yyyy + '/' + (mm[1]?mm:"0"+mm[0]) + '/' + (dd[1]?dd:"0"+dd[0]) ;
} ; // yyyymmd
Date.prototype.hhmmss = function () {
function fixTime(i) {
return (i < 10) ? "0" + i : i;
}
var today = new Date(),
hh = fixTime( today.getHours() ),
mm = fixTime( today.getMinutes() ),
ss = fixTime( today.getSeconds() ) ;
var myHHMMSS = hh + ':' + mm + ':' + ss ;
return myHHMMSS ;
} ; // hhmmss
function genTimeStamp ( arg ) {
var szOut = (new Date).yyyymmdd() + ' - ' + (new Date).hhmmss() ;
return szOut ;
} ; // genTimeStamp()
$( function() {
console.log( '*** (' + genTimeStamp() + ') *** DOM is ready.' ) ;
} ) ; // DOM ready
The client browser can see the time at what the page was loaded using "F12" + "console" ...
JS en un browser, ajudes
- javascript:alert("Hola")
- javascript:alert(document.cookie)
- Chrome + F12
JS debug
Dins un <script> de JavaScript, posem
debugger;
i el Chrome s'aturarà allí.
Llavors, poder fer servir:
- F10 = Over
- F11 = Into
- Shift + F11 = Out of this
console API
Using the console,
Chrome
console.error()
Displays a red icon along with the message text, which is colored red.
Similar to console.log(), includes a stack trace from where the method was called.
console.log() vs console.dir()
console.log() only prints out a toString representation,
whereas console.dir() prints out a navigable tree.
alert() vs console.log()
Since alert could be shown to users, it tends to be literal-minded (just using toString)
so a developer has a lot of control over what's shown to the user.
Unlike alert, console is designed for developers,
and thus tends to try to interpret a call so as to provide information that a developer would find useful:
e.g. "[2, 3, 4]" is a lot more useful to a developer than "[object Object]".
Alert should be the same in every browser;
console's behavior could vary from browser to browser (including not being supported at all, as in IE).
APP on Mobile
Gracias, Álvaro !
We try to build up a simple mobile application, with 4 tabs : home, login, reservations and help.
Login page shall have 2 fields (user and pwd) and a button "login()".
Si no detectamos el "user agent" para generar página distintas para PC, Android o iOS, nos conviene el responsive design,
cuyo CSS adapta la página a las medidas disponibles.
7 questions
- what are two ways you might create an object in JavaScript?
- how would you create an array?
- what is variable hoisting?
- what are the dangers of global variables and how do you protect against it?
- how do you iterate through members in a JavaScript object?
- what is a closure?
- describe your experience unit testing JavaScript
7 questions
Best practices
- use of global variables should be minimized
- use single "var" declaration per scope
- JSLint is your friend
- use strict
- module pattern - designate a single namespace for your app
- development code is for developers :
- prefer clarity over brevity
- log as much as you can
- it's how it works, not how it looks - don't add styling information using JavaScript, do it by manipulating CSS classes
- allow for configuration
- optimize
url
Learn JavaScript
Links a videos de cursos de Java, impartidos por Douglas Crockford en persona,
descubridor del JSON entre otras cosas :
Y si te aburres en vacaciones, aquí un link con hasta 17 horas de videos de clases magistrales sobre JS por los maestros del tema
(principalmente Crockford y Resig):
tutplus
Mikeal Rogers, YouTube {31:37}
Douglas Crockford: The Better Parts - JSConfUY 2014, {1:00:52}
Use
JSLint - The JavaScript Code Quality Tool
{Enric}
Derick Bailey
Wondering why JavaScript's "this" is pointing to that, when you thought it was pointing over there?
Confused by the seemingly arbitrary value of "this" ... if it even has a value?
You're not alone.
JavaScript's context variable is one of the most frustrating and confusing bits of important information that you need to understand.
But don't worry - the rules for managing "this" are easier to understand than most people think.
email courses
Backbone.js with Derick Bailey - April 2013, YouTube {1h 48 min}
Links
- Get DHTML, scripts for the real world.
- More than one JavaScript on a page
- PC emulator
- See dynamic text in a ListBox
- uController board
- Add to favorites
- Coffee Script - a little language that compiles into JavaScript
- DART,
the goal of Dart is "ultimately to replace JavaScript as the lingua franca of web development on the open web platform"
- Dan's tools - lots of interesting tools, as
Color picker, CSS formatter, Online DIFF tool, favicon generator, HTML formatter, JavaScript formatter, JSON formatter, perl formatter, PHP formatter, Python formatter, website speed test
- infinite scroll plugin
Tools
Books
Own links
Last updated JS :
From here