{ Wilker-Dev: Blog }
May 17, 2010

Artigos Javascript

Filed under // development  javascript  // 0 Comments
May 12, 2010

Brincando com WebSockets

Brincando ontem com websockets decidi fazer um pequeno experimento.

Basicamente o experimento consiste em ter vários jogadores na tela (são simples quadrados), e quanto alguém se mover, todos os outros jogadores devem ser imediatamente notificados da nova posição, para ter sempre todos sincronizados. Para isso utilizei o Node para criar uma aplicação para ser o servidor de socket e usei o WebSockets no Javascript de front-end.

O resultado pode ser conferido no video abaixo (o quadrado vermelho indica o quadrado sob controle da janela atual):

O código fonte está disponível em: http://github.com/wilkerlucio/ws.squares
May 5, 2010

jQuery MultiSelect

Screen_shot_2010-05-05_at_5

Estava trabalhando num projeto da empresa e precisamos de um input para tags, eu antigamente usada um plugin autocomplete para jquery, mas decidi procurar algo mais legal dessa vez. Depois de dar umas olhadas eu gostei bastante do proprio esquema do Posterous, olhei o fonte e descobri que ele estava usando o Proto!MultiSelect. Muito legal, mas nós estamos utilizando jQuery e não temos intenção de colocar o Prototype junto pra rodar, então eu procurei soluções em outros plugins de jQuery mesmo. Até achar o FCBKComplete, ele até é legal a primeira vista, mas não gostei porque ele perde o foco no cursor quando você seleciona uma opção, e ele não deixa inserir opções que não estejam previamente definidas. Tentei até olhar o fonte para mexer, mas vi rapidamente que não valeria a pena, então decidi por a mão na massa e criar o meu próprio plugin para isso.

Como resultado estou lançando agora o jQuery MultiSelect. Ele tem suporte a autocomplete e adição inline, separador customizado e vários atalhos legais :)
O fonte pode ser encontrado no github, e foi programado usando CoffeeScript. Ta ai mais um plugin para quem quiser ;)
Filed under // development  javascript  jquery  plugin  // 0 Comments
March 28, 2010

Criando scripts greasemonkey com Coffee Script

Dei uma bela estudada hoje sobre o Coffee Script, e fazendo alguns testes eu fiz uma espécie de esqueleto para criação de scripts GreaseMonkey. Segue o snippet que eu criei no TextMate:

O segredo é ter essa função encapsulada dentro de um bloco executável para que o Coffee não coloque variáveis acima dos comentários (que são obrigatórios para o caso do GreaseMonkey). Dessa forma funciona perfeitamente, mas lembrando que o script deve ser compilado com a opção --no-wrap, caso contrário será criado um escopo inicial que ficará acima dos comentários.
Filed under // greasemonkey  javascript  // 0 Comments
March 10, 2010

Harmony - Acesse um ambiente JavaScript e DOM em Ruby

O Harmony, desenvolvido por Martin Aumont, é uma nova DSL Ruby para executar código JavaScript e que usa DOM a partir de aplicativos Ruby. Por que isso é legal? Porque isso possibilita a criação de testes unitários para o Javascript utilizado em suas aplicações em Ruby, ou seja, tudo pode ser testado com um único conjunto de testes!

Falando assim parece que o Harmony é uma biblioteca incrivelmente complexa, mas na verdade ela encapsula outras bibliotecas, como a Johnson, que oferece acesso ao interpretador de Javascript da Mozilla Spidermonkey no Ruby, e env.js, um ambiente DOM recriado em JavaScript.

Veja o "Hello World" do Harmony:

harmony2.png

HolyGrail - O plugin para Rails

Se você está usando Rails, o HolyGrail é o plugin que leva o leva o poder do Harmony às suas aplicações (até o momento só para testes funcionais). Veja alguns exemplos com o HolyGrail:

holygrailtest.png

Biblioteca que parece muito boa, espero começar alguns testes com a mesma em breve :)

Filed under // development  javascript  rails  ruby  test  // 1 Comment
March 10, 2010

gameQuery - jQuery game engine

Vi o site de um projeto que parece bem interessante, o gameQuery.
Os demos são interessantes, vo ver se arrumo um tempo pra fazer alguns testes :)
Filed under // games  javascript  // 0 Comments
March 9, 2010

Baixando musicas do SoundCloud após o limite de download

UPDATE 07/02/12:

Criei uma nova extensão para o Google Chrome que resolve (e foram corrigidos vários erros anteriores). Essa agora é a forma mais fácil de utilizar meu script. Apenas use o Chrome Chrome e instale a seguinte extensão: https://chrome.google.com/webstore/detail/opdommdbfahdoflmobpheimffhbgkfjl?hl=en&gl=BR

ps: a versão no Userscripts também foi atualizada, usuários do Firefox podem continuar usando o Greasemonkey por la (basta atualizar a extensão).

 

Odeio quando esses sites vem com essas frescuras de limites e bloqueios inúteis. Estava eu aqui ouvindo Dj Cremoso e resolvi baixar as musicas, as 3 primeiras foi ok, ai vi que as outras ja haviam sido baixadas mais de 100 vezes, por isso o SoundCloud bloqueava o download.
Bom, mas dava pra ouvir no site, então sabe como é, conteúdo acessivel agente sempre arruma forma melhores ainda de acessar :)

Então criei um belo script GreaseMonkey, se você utiliza essa extensão no Firefox basta acessar o seguinte link: http://userscripts.org/scripts/show/70968
Então instale o script e volte ao SoundCloud, e voi-la! Todas as musicas estão com o botão de download funcionando novamente!

Detalhes técnicos: os botões que vem desabilitados na página são detectados, e partir do mesmo eu pesquiso pelo link do stream do áudio que está em outra parte do código, com isso modifico o botão desativado e faço ele apontar para o stream, dessa forma você pode dar o clique direito e mandar baixar normalmente.

UPDATE 20/12/10

Script atualizado e funcionando novamente :)

Filed under // greasemonkey  javascript  // 68 Comments
October 20, 2008

Porque usar UTF-8 - Codificando/Decodificando

Bom galera, como prometido venho hoje aqui demonstrar como o UTF-8 realmente funciona por debaixo dos panos, e vamos criar uma implementação do mesmo utilizando JavaScript.

Como eu já havia dito antes, o UTF-8 usa uma codificação de tamanho variável, onde cada caractere pode ocupar entre 1 e 4 bytes, para que isso seja possível, existem bits que são usados para verificar isso, vamos ver o primeiro caso:

Eu falei para vocês anteriormente que para os valores ASCII padrão o UTF-8 mantém a compatibilidade, ou seja, não existe nenhum transformação para os caracteres entre 0 e 127, se você olhar o binário disso, vai perceber que isso varia entre:
00000000
01111111

É importante notar que o primeiro bit do byte não é modificado, isso é importante porque ele é flag que indica se vamos precisar de mais bytes no caractere, então, a partir do valor 128 temos que utilizar algum tipo de transformação.

Antes de proseguirmos com os detalhes vamos iniciar nosso script, comecem ele da seguinte forma:


Esse é um simples script que por hora não faz nada :P

Mas ele pega o valor do campo de cima e mostra esse valor codificado no campo de baixo, assim como pega o campo de baixo e joga decoficidado no campo de cima. A partir de agora só iremos trabalhar nos métodos encode e decode do objeto UTF8 que criamos acima.

Voltando ao UTF-8, vamos criar primeiro o codificador, então vamos continuar o entendimento dos bytes.

A partir do momento que o primeiro bit deveria ser usado, então a coisa muda, imaginando um caso simples, o caractere de numero 128, se continuassemos usando a maneira simples de somar bits teriamos a seguinte sequencia de bits:
10000000
Mas para o UTF-8 a sequencia correta seria:
11000010 10000000
Parece complicado, mas não é para tanto, quando passamos dos 128 caracteres iniciais temos alguns "moldes" onde devemos encaixar nossos bits, que no caso são os seguintes (por uso de bytes):
1 byte - 0xxxxxxx
2 bytes - 110xxxxx 10xxxxxx
3 bytes - 1110xxxx 10xxxxxx 10xxxxxx
4 bytes - 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Esses moldes não são ao acaso, e como pode-se ver eles seguem um padrão, esses moldes são importantes para que o precesso de decodificação, notem que a partir dos primeiros bits do primeiro byte é possivel saber exatamente quantos bytes tem o caractere atual.

Para criamos o processo de encoding, o primeiro passo é descobrir quantos bytes serão nescessários para criar nosso caractere no formato UTF-8, para saber isso é só contar os limites a partir do número de bits que podem ser alocados em cada nível. Mas como eu sou muito legal eu já vou disponibilar esses números para você, e são eles: 128, 2048, 65536

Pra quem nunca executou operações bit a bit pode parecer um pouco complicado sair mexendo eles por ai, mas é facil, primeiro mantenha a calculadora do windows aberta (em modo científico, assim você pode converter entre decimal, hexadecimal e binario sempre que precisar, e você vai precisar), então vamos criar a função de encode:


Pra quem não está acostumado com manipulação de bits isso pode parecer coisa de louco, mas é simples, vou ilustrar como funcionam os operadores bit a bit utilizados nas operações:

right shift (>>): esse operador simplesmente move bits a direita, caso o bit ultrapasse o primeiro ele é descartado, exemplos:
00011000 >> 2
resulta em: 00000110
01101110 >> 3
resulta em: 00001101

ou seja, eh simplesmente mover bits a direita (se lembre, tudo isso é forma de representação, tudo são bits, desde numeros a caracteres, vc não vai digitar em formato binário nunca, pelo menos não em javascript)

E binário (&): executa uma operação E entre binários, a idéia é simples, você coloca os bits que são comparados em uma listagem de 1 para 1, caso o valor seja 1 nos 2, o resultádo será 1, caso contrário será 0, exemplos:
  00110111
& 01100010
----------
  00100010

  01111000
& 00111110
----------
  00111000

esse operador é muito usado para mascarar bits, por exemplo, você quer apenas os 4 últimos bits de um dado binário, então você opera um E contendo 00001111 sobre esse binário, dessa forma você terá o resultado com os 4 últimos valores.

OU binário (|): esse é parecido com o anterior, mas com uma diferença básica, esse retorn 1 exceto se os 2 operadores forem 0, exemplo:
  00110101
| 11100001
----------
  11110101

Isso são alguns operadores binários, caso não tenha ficado muito claro podem tirar suas dúvidas comigo por comentários ou e-mail.

Dever de casa: pegue os números utilizados no algoritmo anterior em formato hexadecimal (que comecam com 0x) e veja suas formas em binário (use a calculadora do windows ou similar), e va executando o algoritmo como se fosse o computador, dessa forma você terá um melhor entendimento do algoritmo.

O encode está pronto, agora precisamos pegar os códigos Unicode a partir disso que geramos, então vamos criar o decode:

O processo inverso é exatamente a mesma coisa, é só pegar os bits que você jogou no formato e junta-los novamente. Para descobrir quantos bytes são usados eu utilizei a seguinte idéia:

1 - se for menor que 128, então é padrão ASCII, jogar direto
2 - verificar bit zero dentro do primeiro byte, a partir disso é possível descobrir o número (se baseando nos formatos possíveis).

O único operador novo é o left shift (<<) que simplesmente move os bits para esquerda ;)

Bom galera, termino por aqui, qualquer dúvida entrem em contato comigo por e-mail ou comentários.

Mudarei de assunto no próximo post (assunto indefinido até o momento ;).

See yah!

Você pode conferir abaixo o resultado final:

Filed under // algorithms  javascript  // 0 Comments
October 9, 2008

Novo blog

Ola amigos, essa postagem é apenas na esperança que alguém ainda tenha esse blog marcado em algum lugar (se é que isso é possível), bom, lancei hoje meu novo blog, dessa vez sobre assuntos de desenvolvimento em geral, e iniciei com um post sobre porque devemos utilizar UTF-8.

Como esse blog e generalista terei mais ideias para postar e pretendo postar com mais frequência, quem gostava desse blog deve gostar do novo também ;)

Entao acessem: http://wilker-dev.blogspot.com/

Vlw!

Filed under // development  javascript  // 0 Comments
October 23, 2006

DOM - Básico

E ae galera! Pow, to atrasadão com vocês... mal ae, tava sem tempo no trabalho esses dias, mas hoje vamos voltar aos estudos :)

O que raios é DOM?
DOM é a sigla para Document Object Model (Modelo de Objecto de Documento), ele é uma API para ler e escrever XML (é a padrão da W3C e tem sua implementação na maioria das linguagens atuais). Com o DOM é possivel localizar elementos dentro de um XML, alterar atributos, criar novos elementos e outros recursos.

DOM em JavaScript
No JavaScript particularmente, o DOM é de vital importância, enquanto em outras linguages você usa o DOM para realmente ler, escrever e salvar documentos XML, no JavaScript ele é usado para mudar a página dinâmicamente. Você deve saber que a página web é mostrada na tela após o conteudo HTML (ou XHTML) ser carregado, a grande jogava do DOM no JavaScript é que com ele você muda os atributos do HTML atual, e automaticamente a exibição é atualizada! Se você associar isso ao fato de conseguir alterar também o CSS dos elementos, os efeitos que podem ser gerados estão além do que muita gente pensa quanto a capacidade de sites. Essa arte de mexer com elementos usando DOM no JavaScript é chamada DHTML, quando você ver esse nome na net, não se assuste, DHTML não é uma linguagem, é apenas o uso do JavaScript para mexer com HTML ;)

Começando com DOM
Bom, vamos passar a escrever agora todo o HTML no código, pois como vamos mexer no HTML, não da pra ter apenas código JavaScript (eu me refiro ao usar o esqueleto de código que eu passei no primeiro artigo, e realmente, é possivel fazer DHTML sem ter código HTML prévio, mas vamos deixar isso para depois).

Nosso documento HTML que será usado inicialmente (use ele, o resto iremos colocar somente na tag script):

<html>
<head>
<title> :: JavaScript Developer - Aprendendo DOM :: </title>
<script type="text/javascript">
//o codigo vira aqui
</script>
</head>
<body>
<form id="meuFormulario">
<table>
<tr>
<td valign="top">Linguagens que programa:</td>
<td>
<div id="camposCheck">
<input type="checkbox" name="linguagens[]" /> PHP<br />
<input type="checkbox" name="linguagens[]" /> JavaScript<br />
<input type="checkbox" name="linguagens[]" /> C++<br />
<input type="checkbox" name="linguagens[]" /> Java<br />
<input type="checkbox" name="linguagens[]" /> CSS<br />
</div>
<div id="fastCheckDiv" style="display: none;">
Marcar Todos
Desmarcar Todos
</div>
</td>
</tr>
<tr>
<td></td>
<td><button type="submit">Enviar Formulário</button></td>
</tr>
</table>
</form>
</body>
</html>

Iremos comecar com o mais simples, os formulários, mas antes eu gostaria de expor um conceito muito bem aceito hoje em dia, que é o conceito do JavaScript "não obstrutivo".

JavaScript não obstrutivo
O que seria isso? É simplesmente fazer o uso do JavaScript sem faze-lo obrigatório para visualização, fazendo com que dessa forma, o JavaScript seja apenas um adicional, e não fundamental. E como fazer isso? A primeira coisa a ser feita, é deixar tudo funcionando sem JavaScript, como vocês podem ver, o formulário do código acima não tem nada de JavaScript, mas se clicar-mos no botão de enviar, o formulário vai ser enviado sem nenhum problema, entao ja temos a solução no HTML, e agora iremos apenas incrementar mais interatividade. No JavaScript não obstrutivo nós não colocamos código JavaScript no meio do HTML, no lugar de fazer isso apenas nomeamos elementos com ID, e depois os pegamos usando o DOM!

Voltando ao formulario
OK, nesse formulário iremos incrementar uma função pra marcar e desmarcar todos os checkbox mais facilmente. obs: eu ia fazer uma validação com um campo de nome também, mas isso usuária muito código, e parar um evento de forma não obstrutiva não é tão simples, entao prefiro deixar isso para quando formos falar de eventos em futuros artigos.

Como sempre, primeiro o código, depois explicações ;)

function $(obj) {
return document.getElementById(obj);
}

function marcaBoxes(marcar) {
var boxesContainer = $('camposCheckDiv');
var childs = boxesContainer.childNodes;

for(var i = 0; i < childs.length; i++) {
var node = childs[i];

if(node.nodeType == 1 && node.tagName == "INPUT")
node.checked = marcar;
}
}

window.onload = function() {
var marcaTudoObj = $('marcaTodosLink');
var desmarcaTudoObj = $('desmarcaTodosLink');
var fastCheckObj = $('fastCheckDiv');

marcaTudoObj.onclick = function() {
marcaBoxes(true);
};

desmarcaTudoObj.onclick = function() {
marcaBoxes(false);
};

fastCheckObj.style.display = '';
};

Vamos com calma, esse script tem várias coisas novas, vamos pelo começo:

A função $(obj) -> eu já disse antes que para mexer com os elementos de forma não obstrutiva, devemos colocar ID neles, para pegar isso com o DOM, mas eu ainda não tinha falado como fazer isso. Primeiro de tudo, a variável pré-definida document é o objeto principal do DOM, vamos falar mais sobre ela depois, por enquanto, saibamos que ela tem um método chamado getElementById(), e como claramente o nome diz, esse método serve justamente para pegar a referência para em elemento dentro do HTML atual. O que a função $() faz é apenas servir de atalho para document.getElementById(), porque convenhamos, escrever document.getElementById() o tempo todo é uma me***. Futuramente vamos ver como deixar essa função ainda melhor.

A função marcaBoxes(marcar) -> essa é a função principal para o nosso sistema, é ela que vai lá e marca / desmarca os checkbox, o parêmetro marcar serve para indicar se ela vai marcar ou desmarcar os checkbox. Vamos estuda-la passo a passo:

var boxesContainer = $('camposCheckDiv'); => essa linha pega o elemento DIV que está contendo os nossos checkbox, precisamos de algo que circunde nosso checkbox para poder pega-los de forma dinâmica e eficiente

var childs = boxesContainer.childNodes; => essa é legal, todos os objetos HTML tem uma propriedade chamada childNodes, o childNodes é um array contendo todos as referencias para os elementos dentro do dele. Ou seja, como nossos checkboxes estão dentro de boxesContainer, então entre os childNodes do boxesContainer estão todos os nossos checkboxes que devem ser marcados / desmarcados

for(var i = 0; i < childs.length; i++) { => iniciamos nosso loop pelos childNodes

var node = childs[i]; => colocamos um nó atual numa variável, apenas para ficar mais claro

if(node.nodeType == 1 && node.tagName == "INPUT") => essa linha aqui é importante, primeiro verificamos se o nó é um elemento realmente, os elementos HTML (aqueles entre tags) são representados pelo valor 1, mas existem outros também:

1 - elemento HTML, exemplo: <p>...</p>
2 - atributo, exemplo: align="center"
3 - texto, exemplo: conteudo de alguma coisa
8 - comentário, exemplo: <!-- comentario html -->
9 - document, é o nó principal do XML, exemplo: <html>
10 - definição do documento, exemplo: <!DOCTYPE HTML PUBLIC "-//W3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

pela lista podemos ver que o único em que estamos interessados é o número 1. O segundo item verifica se o nosso elemento é um input (lembre-se, também temos uns <br /> no meio), um detalhe, a propriedade tagName sempre fica em maiúsculo, independende de como vocês a escreveu no HTML.

node.checked = marcar; -> finalmente, após tudo estamos marcado ou desmarcando o checkbox (de acordo com o parâmetro passado), a propriedade checked pertence apenas a radios e checkboxes, ela indica se ele esta ou não marcado, e pode ser usada para definir também (como nós fizemos).

Ufa, terminamos a função principal, vamos a parte do código que faz a nossa mágica da não obstrução:

window.onload = function() {

Colamos o codigo dentro dessa função por um motivo simples, nós vamos mexer com o HTML do site, se tentarmos fazer isso antes do documento ser carregado vai dar erro (pois os elementos ainda não vão existir). Por hora, apenas saiba que window.onload é o evento que dispara quando a página é carregada.

var marcaTudoObj = $('marcaTodosLink');
var desmarcaTudoObj = $('desmarcaTodosLink');
var fastCheckObj = $('fastCheckDiv');

Nessas linhas pegamos as referências para os elementos HTML.

marcaTudoObj.onclick = function() {
marcaBoxes(true);
};

desmarcaTudoObj.onclick = function() {
marcaBoxes(false);
};

Agora colocamos os eventos, estamos dizendo que quando clicar, é para executar a função (que vai logo em seguida). Essa com certeza não é a melhor maneira para colocar eventos nos objetos, mas é a mais simples.

fastCheckObj.style.display = '';

E finalmente, nós fazemos os links ficarem visíveis alterando o css dele (vejam como é simples alterar um css, apenas digita-se .style, depois .propriedade e altera). O motivo de ter deixado os links invisíveis, pensem bem, esses links só funcionam se o JavaScript estiver ativado, então, se o JavaScript estiver desativado eles irão permanecer invisíveis, dessa forma o clinte não vai tentar clicar numa coisa que não faz nada.

Mais explicações
Talvez você tenha entendido, talvez não, mas o DOM usa uma estrutura de árvore para guardar os elementos, se você já estudou e sabe oque é isso, ótimo, se não, pense no windows explorer, quando vemos as pastas à esquerda, aquilo é uma estrutura de árvore, cada "nó" pai pode ter varios "nós" filhos, e assim sucessivamente, do mesmo jeito que uma árvore tem galhos, e galhos sobre galhos... No XML temos o nó principal (no HTML seria a propria tag <html>), e esse nó tem varios filhos (<head> <body>), que pode sua vez tem mais varios... Usando esse pensamentos podemos percorrer o documento do jeito que quizermos. Vou colocar os principais atributos usados:

objeto.childNodes - coleção com os nós filhos
objeto.parentNode - nó pai (o nó em qual ele está agrupado)
objeto.nextSibling - o próximo nó (ainda dentro do mesmo pai)
objeto.previousSibling - nó anterior (dentro do mesmo pai)
objeto.tagName - nome da tag
objeto.nodeName - nome da tag (mesma coisa que o anterior)

Com isso você pode "navegar" a vontade pelo documento a partir de qualquer lugar. Existe uma coisa do DOM chamada XPath, com ele você facilmente localiza nodes no documento, eu sinceramente ainda não estudei o XPath no JavaScript, mas sei que ele existe, qualquer dia desses eu posto só sobre isso ;)

Por hoje ficamos por aqui, no próximo artigo vou falar sobre DHTML, vamos fazer alguns efeitos no site. Como sempre, aquela referência esperta (essa é meio grande XD) dos objetos html em geral:

Generic HTML Element Object (Document Object)
Generic (X)HTML elements have the form described here. This list of properties, methods, and event handlers are common to almost all (X)HTML element objects and are, in fact, the only properties, methods, and event handlers defined for a large number of very basic elements, such as <b>, <i>, and <u>. Each of these objects corresponds to an occurrence of an (X)HTML element on the page. Access to one of these objects is achieved through standard DOM methods like document.getElementById().

Note Some properties do not have a well-defined meaning for particular objects, even though the properties may be defined for them. For example, blurring an <hr> tag is interesting given that it is difficult to focus the object in general Web use.


Properties
accessKey Single character string indicating the hotkey that gives the element focus. (IE4+)

all[] Collection of elements enclosed by the object. (IE4+)

align String specifying the alignment of the element, for example, "left". This property is defined only for display elements such as b, big, cite, and so on. (IE4+)

attributes[] Collection of read-only attributes for the element. (IE5+, MOZ/N6+, DOM1)

begin Sets or retrieves delay before timeline begins playing the element. See MSDN. (IE5.5+, SMIL)

behaviorUrns[] Collection of DHTML Behaviors attached to the node. (IE5+)

canHaveChildren Read-only Boolean value indicating whether the element can have child nodes. (IE5+)

canHaveHTML Read-only Boolean indicating whether the element can enclose HTML markup. (IE5.5+)

childNodes[] Read-only collection of child nodes of the object. (IE5+, MOZ/N6+, DOM1)

children[] Read-only collection of child nodes. This is IE’s pre-DOM equivalent of childNodes[]. (IE4+)

className String holding value of the CSS class(es) the element belongs to. (IE4+, MOZ/N6+, DOM1)

clientHeight Read-only numeric value indicating the height of the element’s content area in pixels. (IE4+)

clientLeft Read-only numeric value indicating the difference between the offsetLeft property and the beginning of the element’s content area, in pixels. (IE4+)

clientTop Read-only numeric value indicating the difference between the offsetTop property and the beginning of the element’s content area, in pixels. (IE4+)

clientWidth Read-only numeric value indicating the width of the element’s content area in pixels. (IE4+)

contentEditable String determining whether the element’s content is editable. Values are "inherit", "true", or "false". A value of "inherit" means that it will inherit the contentEditable property of its parent (this value is the default). This property is useful for making table data cells editable. Elements with disabled set to true are not editable, no matter what value this property has. Corresponds to the contenteditable attribute. (IE5.5+)

currentStyle Read-only reference to the Style object reflecting all styles applied to the element, including global (default) style. (IE5+)

dir String holding the text direction of text enclosed by the element. If set, its value is either "ltr" (left to right) or "rtl" (right to left). (IE5+, MOZ/N6+, DOM1)

disabled Boolean indicating whether the element is disabled (grayed out). (IE4+)

document An undocumented reference to the Document in which the element is contained. (IE4+)

filters[] Collection of Microsoft CSS Filters applied to the element. (IE4+)

firstChild Read-only reference to the first child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)

hasMedia Read-only Boolean indicating whether the element is an HTML+TIME media element. (IE5.5+)

hideFocus Boolean indicating whether the object gives a visible cue when it receives focus. (IE5.5+)

id String holding the unique alphanumeric identifier for the element. Commonly assigned using the id HTML attribute and used as the target for getElementById(). This unique identifier is not only important for scripting, but also for binding of CSS. (IE4+, MOZ/N6+, DOM1)

innerHTML String holding the HTML content enclosed within the element’s tags. (IE4+, MOZ/N6+)

innerText String holding the text enclosed by the element’s tags. This text is not interpreted as HTML, so setting it to a value like "<b>Important</b>" will result in "<b>Important</b>" being displayed, rather than "Important" with boldfaced font. (IE4+)

isContentEditable Read-only Boolean indicating if the user can edit the element’s contents. (IE5.5+)

isDisabled Read-only Boolean indicating if the user can interact with the object. (IE5.5+)

isTextEdit Read-only Boolean indicating if a TextRange object can be created using the object. (IE4+)

lang String holding language code for the content the element encloses. Corresponds to the lang HTML attribute. For a full list of valid values, see RFC 1766 (http://www.ietf.org/rfc/rfc1766.txt?number=1766), which describes language codes and their formats. (IE4+, MOZ/N6+, DOM1)

language String indicating the scripting language in use. (IE4+)

lastChild Read-only reference to the last child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)

localName Read-only string indicating the "local" XML name for the object. (MOZ/N6+)

namespaceURI Read-only string indicating the XML Namespace URI for the object. (MOZ/N6+)

nextSibling Read-only reference to next sibling of the node, for example, if its parent has multiple children. (IE5+, MOZ/N6+, DOM1)

nodeName Read-only string containing name of the node, the name of the tag to which the object corresponds, for example, "H1". (IE5+, MOZ/N6+, DOM1)

nodeType Read-only number holding the DOM defined node type. For example, element nodes have node type 1. A list of the common node types can be found in the following table. (IE5+, MOZ/N6+, DOM1) [tabela 1]

nodeValue String containing value within the node (or null if no value). (IE5+, MOZ/N6+, DOM1)

offsetHeight Read-only numeric value indicating the height of the element in pixels. (IE4+, MOZ/N6+)

offsetLeft Read-only numeric value indicating the pixel offset of the left edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)

offsetParent Read-only reference to the object relative to which the offsetHeight/Width/Left/Top is calculated. (IE4+, MOZ/N6+)

offsetTop Read-only numeric value indicating the pixel offset of the top edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)

offsetWidth Read-only numeric value indicating the width of the element in pixels. (IE4+, MOZ/N6+)

outerHTML String holding the HTML content enclosed within (and including) the element’s tags. (IE4+)

outerText String holding the text enclosed by (and including) the element’s tags. (IE4+)

ownerDocument Read-only reference to the Document in which the element is contained. (IE5+, MOZ/N6+, DOM1)

parentElement Reference to the node’s parent. This is IE’s pre-DOM equivalent of parentNode. (IE4+)

parentNode Read-only reference to the parent of the object (or null if none exists). (IE4+, MOZ/N6+, DOM1)

parentTextEditv Read-only reference to the innermost container element outside of the current object that is capable of creating a TextRange containing the current element. (IE4+)

prefixv Read-only string containing the "prefix" XML name for the object. (MOZ/N6+)

previousSibling Read-only reference to previous sibling of the node, for example, if its parent node has multiple children. (IE5+, MOZ/N6+, DOM1)

readyState Read-only string containing the current state of the object. Values include "uninitialized", "loading", "loaded", "interactive" (not finished loading but able to respond to user actions), and "complete". Objects progress through each of these states until they have completed loading, though some objects may skip some intermediate steps (for example, pass from "uninitialized" directly to "complete"). This property is very useful in determining whether an element has completed loading. However, you should always make sure the object exists in the Document before attempting to read this property (otherwise, a runtime error will be thrown because you would be attempting to read a property of an object not yet defined). Note that an <object>s readyState is given by the integers 0 through 4 (with the same meaning). (IE4+)

recordNumber Read-only numeric value indicating the record number of the data set from which the element was generated. (IE4+)

runtimeStyle Reference to the Style object that reflects the current (runtime) style characteristics of the element. (IE5+)

scopeName Read-only string containing the XML scope for the object. (IE5+)

scrollHeight Numeric read-only value indicating the total height in pixels of the element’s content area, no matter how much is displayed on screen. (IE4+)

scrollLeft Numeric value indicating the distance in pixels from the left edge of the object to the leftmost edge of the object that is currently displayed. (IE4+)

scrollTop Numeric value indicating the distance in pixels from the top edge of the object to the topmost edge that is currently displayed. (IE4+)

scrollWidth Numeric read-only value indicating the total width in pixels of the object’s content area, no matter how much is displayed on screen. (IE4+)

sourceIndex Read-only number indicating the index of the element in the document.all[] collection. (IE4+)

style Reference to the inline Style object for the element. (IE4+, N4+, DOM2)

syncMaster Specifies whether time container must synchronize with the element. See MSDN. (IE5.5+, SMIL)

tabIndex Numeric value indicating the tab order for the object. Elements with positive values for this property are tabbed to in order of increasing tabIndex (before any others). Elements with zero for this property (the default) are tabbed to in the order they occur in the document source. Elements with negative values are not tabbed to at all. (IE4+)

tagName String containing the name of the tag to which the object corresponds, for example, "H1." (IE5.5+, MOZ/N6+, DOM1)

tagUrn String containing the URN of the XML Namespace for the object. (IE5+)

timeContainer Sets or retrieves the type of timeline associated with the element. (IE5.5+, SMIL)

title String containing advisory text for the element. (IE4+, MOZ/N6+, DOM1)

uniqueID An auto-generated read-only unique id for this element. (IE5+)

Methods
addBehavior(url) Attaches the DHTML Behavior referenced by string url to the element. (IE5+)

addEventListener(whichEvent, handler, direction) Instructs the object to execute the function handler whenever an event of type given in the string whichEvent (for example, "click") occurs. The direction is a Boolean specifying the phase in which to fire, true for capture or false for bubbling. (MOZ/N6+, DOM2)

appendChild(newChild) Appends newChild to end of the node’s childNodes[] list. (IE5+, MOZ/N6+, DOM1 Core)

applyElement(newElement [, where]) "Applies" one element to another by enclosing one within the other. If where is omitted or has value "outside", the object referenced by newElement becomes the parent of the current element. Otherwise, newElement becomes the only child of the current element, enclosing all of the current element’s children. (IE5+)

attachEvent(whichHandler, theFunction) Attaches the function theFunction as a handler specified by the string whichHandler, for example, "onclick". (IE5+)

blur() Removes focus from the element. (IE5+ for most elements. For form fields N2+ or N3+ and IE3+ or IE4+ and DOM1, listed specifically for each object)

clearAttributes() Clears all nonessential HTML attributes from the element (leaves id, dir, etc.). (IE5+)

click() Simulates a mouse click at the object. (IE4+)

cloneNode(cloneChildren) Clones the node and returns the new clone. If cloneChildren is true, the returned node includes the recursively constructed subtree of clones of the node’s children. (IE5+, MOZ/N6+, DOM1 Core)

componentFromPoint(x, y) Returns a string that gives information about the pixel coordinate (x,y) in the client window with respect to the current element. The string returned may have one of the values in the following table [tabela 2]. The return value specifies whether the coordinate is inside of the element (""), outside of the element ("outside"), or a part of the various scrolling mechanisms that may be displayed for the element.

This method is often used with events to determine where user activity is taking place with respect to a particular element and to take special actions based on scroll bar manipulation. (IE5+)

contains(element) Returns a Boolean indicating if the object given in element is contained within the element. (IE4+)

detachEvent(whichHandler, theFunction) Instructs the object to cease executing the function theFunction as a handler given the string whichHandler, for example, "onclick". (IE5+)

dispatchEvent(event) Causes the Event instance event to be processed by the object’s appropriate handler. Used to redirect events. (MOZ/N6+, DOM2)

dragDrop() Initiates a drag event at the element. (IE5.5+)

fireEvent(handler [, event]) Causes the event handler given by the string handler to fire. If an Event instance was passed as event, the new event created reflects the properties of event. (IE5.5+)

focus() Gives focus to the element.

getAdjacentText(where) Returns the string of text corresponding to the text string at position where, with respect to the current node. The where parameter is a string with the following values [tabela 3]

There is no standard DOM method that mimics this behavior. Instead, you must examine the previousSibling, firstChild, lastChild, or nextSibling (in order corresponding to the values of where in the preceding table) and extract the string manually from their text node(s). (IE5+)

getAttribute(name) Returns a string containing the value of the attribute specified in the string name or null if it does not exist. (IE4+, MOZ/N6+, DOM1 Core)

getAttributeNode(name) Returns the attribute node corresponding to the attribute in the string name. (IE6+, MOZ/N6+, DOM1 Core)

getBoundingClientRect() Retrieves a TextRectangle with properties top, bottom, left, right indicating the pixel values of the rectangle in which the element’s content is enclosed. (IE5+)

getClientRects() Retrieves a collection of TextRectangle objects, which give the pixel coordinates of all bounding rectangles contained in the element. (IE5+)

getElementsByTagName(tagname) Retrieves a collection of elements corresponding to the tag given in string tagname. A value of "*" retrieves all tags. (IE5+, MOZ/N6+, DOM1 Core)

getExpression(propertyName) Retrieves the string giving the dynamic property expression for the property/attribute named propertyName. (IE5+)

hasAttribute(name) Returns a Boolean indicating if the attribute given in string name is defined for the node (explicitly or by default). (MOZ/N6+, DOM2 Core)

hasAttributes() Returns a Boolean indicating if any attributes are defined for the node. (MOZ/N6+, DOM2 Core)

hasChildNodes() Returns a Boolean indicating if the node has children. (IE5+, MOZ/N6+, DOM1 Core)

insertAdjacentElement(where, element) Inserts the element object given in element adjacent to the current element in the position given by the string where (IE5+).The possible values for where include these [tabela 4]

insertAdjacentHTML(where, text) Inserts the HTML given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is parsed and added to the document tree. (IE5+)

insertAdjacentText(where, text) Inserts the text given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is not parsed as HTML. (IE5+)

insertBefore(newChild, refChild) Inserts node newChild in front of refChild in the childNodes[] list of refChild's parent node. (IE5+, MOZ/N6+, DOM1 Core)

isSupported(feature [, version]) Returns a Boolean indicating whether feature and version given in the argument strings are supported. (MOZ/N6+, DOM2 Core)

mergeAttributes(source [, preserve]) Merges all attributes, styles, and event handlers from the element node source into the current element. (IE5+)

normalize() Recursively merges adjacent text nodes in the sub-tree rooted at this element. (IE6+, MOZ/N6+, DOM1 Core)

releaseCapture() Disables universal mouse event capturing at that object. (IE5+)

removeAttribute(name) Removes attribute corresponding to string name from the node. (IE4+, MOZ/N6+, DOM1 Core)

removeAttributeNode(attribute) Removes the attribute node given by node attribute and returns the removed node. (IE6+, MOZ/N6+, DOM1 Core)

removeBehavior(id) Removes the DHTML Behavior associated with id (previously returned by attachBehavior()) from the element. (IE4+)

removeChild(oldChild) Removes oldChild from the node’s children and returns a reference to the removed node. (IE5+, MOZ/N6+, DOM1 Core)

removeEventListener(whichEvent, handler, direction) Removes function handler as a handler for the event given in the string whichEvent (for example, "click") for the phase given by the Boolean direction. (MOZ/N6+, DOM2)

removeExpression(propertyName) Removes dynamic property expression for the property given in the string propertyName. (IE5+)

replaceAdjacentText(where, text) Replaces the text at position where relative to the current node with the text (non-HTML) string text (IE5+). Possible values for where include [tabela 5]

replaceChild(newChild, oldChild) Replaces the node’s child node oldChild with node newChild. (IE5+, MOZ/N6+, DOM1 Core)

replaceNode(newNode) Replaces the current node with newNode. (IE5+)

scrollIntoView([alignToTop]) Causes the object to be immediately scrolled into the viewable area of the window. If alignToTop is true or omitted, the top of the object is aligned with the top of the window (if possible). Otherwise, if alignToTop is false, the object is scrolled so that the bottom of the object is aligned with the bottom of the viewable window. (IE4+)

setActive() Sets the object as the active object without giving it focus. (IE5.5+)

setAttribute(name, value) Sets a new attribute for the node with name and value given by the string arguments. (IE4+, MOZ/N6+, DOM1 Core)

setAttributeNode(newAttr) Adds the attribute node newAttr (replacing and returning any attribute node with the same name). (IE6+, MOZ/N6+, DOM1 Core)

setCapture([containerCapture]) Causes all mouse events occurring in the document to be sent to this object. (IE5+)

setExpression(property, expression [, language]) Sets the expression given in string expression as the dynamic expression for the property given in string property. The optional language parameter specifies which scripting language the expression is written in, for example, "VBscript" (JScript is the default). Commonly used as a method of element nodes and Style objects. Used for setting dynamic expressions. (IE5+)

swapNode(node) Exchanges the location of the object with node in the object hierarchy. (IE5+)

unwatch(property) Removes the watchpoint on the property given in the string property. (N4+)

watch(property, handler) "Watches" the property given in string property and invokes the function handler whenever its value changes. The handler is passed the name of the property, the old value, and the value to which it is being set. Any value the function returns is interpreted as the new value for the property. (N4+)

Notes
With the exception of the object scriptable under traditional models (Form, Image, and so on), most elements become scriptable in Internet Explorer 4+, Mozilla/Netscape 6+, and DOM1.

HTML elements are referred to both in uppercase and lowercase under the DOM, so <p> and <P> are both equivalent to an HTMLParagraph object.

Tabela 1

Node Type Number Type Description Example
1 Element An HTML or XML element <p>…</p>
2 Attribute An attribute for an HTML or XML element align="center"
3 Text A fragment of text that would be enclosed by an HTML or XML element This is a text fragment!
8 Comment An HTML comment <!-- This is a comment -->
9 Document The root document object, namely the top element in the parse tree <html>
10 DocumentType A document type definition <!DOCTYPE HTML PUBLIC "-//W3C

//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

Tabela 2

Return Value Component at the Given Coordinate
"" Component is inside the client area of the object.
"outside" Component is outside the bounds of the object.
"scrollbarDown" Down scroll arrow is at the specified location.
"scrollbarHThumb" Horizontal scroll thumb or box is at the specified location.
"scrollbarLeft" Left scroll arrow is at the specified location.
"scrollbarPageDown" Page-down scroll bar shaft is at the specified location.
"scrollbarPageLeft" Page-left scroll bar shaft is at the specified location.
"scrollbarPageRight" Page-right scroll bar shaft is at the specified location.
"scrollbarPageUp" Page-up scroll bar shaft is at the specified location.
"scrollbarRight" Right scroll arrow is at the specified location.
"scrollbarUp" Up scroll arrow is at the specified location.
"scrollbarVThumb" Vertical scroll thumb or box is at the specified location.
"handleBottom" Bottom sizing handle is at the specified location.
"handleBottomLeft" Lower-left sizing handle is at the specified location.
"handleBottomRight" Lower-right sizing handle is at the specified location.
"handleLeft" Left sizing handle is at the specified location.
"handleRight" Right sizing handle is at the specified location.
"handleTop" Top sizing handle is at the specified location.
"handleTopLeft" Upper-left sizing handle is at the specified location.
"handleTopRight" Upper-right sizing handle is at the specified location.

Tabela 3

Value of where String Returned
"beforeBegin" Text immediately preceding element’s opening tag (back to but not including first element encountered).
"afterBegin" Text immediately following the element’s opening tag (up to but not including the first nested element).
"beforeEnd" Text immediately preceding the element’s closing tag (back to but not including the closing tag of the last enclosed element).
"afterEnd" Text immediately following element’s closing tag (up to but not including the first following tag).

Tabela 4

Value of where Effect
"beforeBegin" Inserts immediately before the object.
"afterBegin" Inserts after the start of the object but before all other content.
"beforeEnd" Inserts immediately before the end of the object, after all other content.
"afterEnd" Inserts immediately after the end of the object.

Tabela 5

Value of where Effect
"beforeBegin" Replaces text immediately before the object (back to but not including first tag or end tag encountered).
"afterBegin" Replaces text at the start of the object but before all other enclosed content (up to but not including first opening tag).
"beforeEnd" Replaces text immediately before the end of the object, after all other content (back to but not including last tag or closing tag).
"afterEnd" Replaces text immediately after the element’s closing tag (up to but not including the next tag).
Filed under // development  javascript  // 0 Comments