Archive

Posts Tagged ‘JavaScript’

Test your JavaScript code with JSFiddle

November 25, 2010 Leave a comment

I just discovered jsfiddle.net. It’s a website that lets you type (or paste) HTML, CSS and JS code and load a specific JavaScript library to test its effects live. It also gives you a “JSLint” link which checks the syntax of your JavaScript.

Great tool for web developers doing occasional JavaScript coding!

Descubriendo OpenLayers

January 29, 2010 2 comments

OpenLayers permite poner un mapa dinámico en cualquier página web.
Puede mostrar bloques de mapas y marcadores desde cualquier fuente, fue desarrollado inicialmente por MetaCarta y se lo dio al público para promover el uso de la información geográfica de todo tipo.
OpenLayers es totalmente gratuito, de código abierto de JavaScript (OpenSource), liberado bajo una licencia tipo BSD.

Qué es OpenLayers?

  • Es un API para construir Mapas en aplicaciones web’s
  • Ejecución desde el Cliente a travez JavaScript
  • Ajax
  • Licencia BSD (Berkeley Software Distribution)
  • v 2.8 estable

Ventajas

  • OpenLayers no es una solicitud. (no requiere instalación)
  • Menor procesamiento en el servidor.
  • Puede ampliar fácilmente el código para su aplicación en particular.
  • Puede utilizar múltiples Servidores de datos.

“Desventajas” mejor dicho Requisitos

  • Usted necesita saber JavaScript, CSS y HTML

¿Dónde se utiliza OpenLayers?

  • Sistema de Inventario de Desastres
  • Plantación de árboles
  • Seguimiento de peces

Para desarrolladores

OpenLayers es una librería JavaScript puro para la visualización de los datos del mapa en la mayoría de navegadores modernos, con ningún servidor de las dependencias lado. OpenLayers implementa un (aún en desarrollo) API de JavaScript para la construcción de web ricas aplicaciones basadas geográfica, similar a la de Google Maps y MSN Virtual Earth API, con una diferencia importante – OpenLayers es el Software Libre, desarrollado por y para la comunidad Open Source software.

esto es una breve introducción a esta potente librería, a continuación otros ejemplos de su uso:

Tambien les dejo la presentación que hice para el equipo de desarrolladores de Dokeos.

Editores en línea: Backgrounds, Ajax loaders, Lorem Ipsum …

Existen muchos sitios que nos proveen una ayuda para ahorrarnos tiempo cuando necesitamos un fondo, una imagen o simplemente un lorem ipsum!! Aqui una breve reseña de lo que encontré:

Pixelknete
http://www.pixelknete.de

Puedes hacer muchas combinaciones y nunca se verán igual.

www.pixelknete.de

Stripe Mania
http://www.stripemania.com

Útil generador de lineas verticales, horizontales con bonitos patrones.

stripemania.com


Pattern Cooler

http://www.patterncooler.com

Puedes hacer miles de combinaciones y nunca se verán igual (2).

www.patterncooler.com


Ajax load

http://www.ajaxload.info

Generador de loaders tipo Ajax, se puede seleccionar el tipo de color de fondo o transparente.

Ajaxload.info

Lorem Ipsum
http://www.lipsum.com

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent venenatis suscipit euismod.

loremipsum

Libreria XAJAX en PHP

May 9, 2009 15 comments

Xajax es una biblioteca código abierto de PHP capaz de generar aplicaciones Web con tecnología AJAX.
Xajax utiliza una forma de trabajo de funciones, designando qué funciones o métodos de código PHP se convierten en funciones AJAX
Puede descargarlo Aqui

Ejemplo 1 : Xajax y funciones PHP

<?php
//Incluir con PHP el archivo donde está la clase xajax
require (‘xajax/xajax_core/xajax.inc.php’);

//Instanciamos el objeto de la clase xajax
$xajax = new xajax();

//Escribimos una función en PHP, que luego llamaremos con por medio de ajax
function cambia_texto($mensaje){

//instanciamos el objeto para generar la respuesta con ajax
$respuesta = new xajaxResponse();
//escribimos en la capa con id=”mensajeDiv” el texto de $mensaje
$respuesta->assign(“mensajeDiv”,”innerHTML”,$mensaje);
//tenemos que devolver la instanciación del objeto xajaxResponse
return $respuesta;
}
//asociamos la función creada anteriormente al objeto xajax
$xajax->registerFunction(“cambia_texto”);
//El objeto xajax tiene que procesar cualquier petición
$xajax->processRequest();
?>

<html>
<head>
<!– En el <head> indicamos al objeto xajax se encargue de generar el javascript necesario –>
<?php $xajax->printJavascript(“xajax/”); ?>
</head>
<body>
<!– Se llama a la funcion javascript generada por xajax con el prefijo ‘xajax_’ seguida del nombre de la funcion creada con php –>
<input type=”button” onclick=”xajax_cambia_texto(‘Hola Ajax’);” value=”Pulsa” />
<div id=”mensajeDiv”></div>
</body>
</html>

Ejemplo 2: Xajax y objetos

<?php
//Incluir con PHP el archivo donde está la clase xajax
require_once(“xajax/xajax_core/xajax.inc.php”);
//Creamos la clase cuyo metodo utilizara el xajaxResponse
class alumno{
private $mensaje=”Ajax”;
public function hola(){
//instanciamos el objeto para generar la respuesta con ajax
$objResponse = new xajaxResponse();
//En este caso el metodo lanzara un alert js con el texto “Ajax”
$objResponse->alert(‘Hola ‘.$this->$mensaje);
//Devolvemos el objeto xajaxResponse
return $objResponse;
}
}
$alumno = new alumno()
//Instanciamos el objeto de la clase xajax
$xajax = new xajax();
//asociamos el metodo del objeto $alumno al objeto xajax con un array(“nombreEnJS”,$objeto,”metodo”)
$xajax->registerFunction(array(“miFuncion”, $alumno,”hola”));
//El objeto xajax tiene que procesar cualquier petición
$xajax->processRequest();
?>

<?php $xajax->printJavascript(“xajax/”) ?>
<input type=”submit” value=“Llamar” onclick=”xajax_miFuncion(); return false;”>

METODOS DE LA CLASE XAJAX

$xajax = new xajax();
$xajax->setFlag(“debug”, true);
$xajax->setFlag(“decodeUTF8Input”, true);
$xajax->setFlag(“characterEncoding”,’ISO-8859-1′);
$xajax->registerFunction(“miFuncion”);
$xajax->processRequest();

METODOS DE LA CLASE AJAXRESPONSE

$objResponse = new xajaxResponse();
$objResponse->redirect(“http://www.google.com&#8221;);
$objResponse->alert(“Mostramos un alert.”);
$objResponse->confirmCommands(2, “Mensaje que pregunta?”);
$objResponse->call(“funcionJS”, “arg 1″, “arg N” );
$objResponse->includeScript(archivo.js);
$objResponse->assign(“etiqDiv”, “innerHTML”, “dato”);
$objResponse->assign(“etiqueta3”, “style.width”, “25%”)
$objResponse->remove(“etiqDiv”);

Ejemplo 3 : Formularios Xajax

<?php
require_once(“xajax/xajax_core/xajax.inc.php”);
function testForm($formData){
$objResponse = new xajaxResponse();
$objResponse->assign(“submittedDiv”, “innerHTML”, nl2br(print_r($formData, true)));
return $objResponse;
}
$xajax = new xajax(); $xajax->registerFunction(“testForm”);
$xajax->processRequest();
?>

<form id=”testForm1″ onsubmit=”return false;”>
<input type=”text” name=”textInput” value=”text” />
<input type=”text” name=”textInput2″ value=”text” />
<select id=”select” name=”select”>
<option value=”1″>One</option> <option value=”2″>Two</option>

<option value=”3″>Three</option>

<option value=”4″>Four</option>
</select>
<input type=”submit” value=“submit por xajax” onclick=”xajax_testForm(xajax.getFormValues(‘testForm1’)); return false;” />
</form>
<div id=”submittedDiv”></div>

Ejemplo 4 : Llamar una funcion javascript desde codigo php

<?php
require(“xajax/xajax_core/xajax.inc.php”);
function callScript() {
$response = new xajaxResponse();
$value2 = “elemento 2”;
$response->call(“myJSFunction”, “argumento 1”, 9432.12,
array(“myKey” => “elemento 1”, “key2” =>$value2));
return $response;
}
$xajax = new xajax();

$xajax->registerFunction(“callScript”);

$xajax->processRequest();
?>

<?php $xajax->printJavascript(“xajax/”) ?>
<script type=”text/javascript”>
function myJSFunction(Argtext, ArgNum, ArrayArg) {
var newString = Argtext + ” y ” + (+ ArgNum + 100) + “\n”;
newString += ArrayArg[“myKey”] + ” | ” + ArrayArg.key2;
alert(newString);
}
</script>
<input type=”button” value=”Click Me” onclick=”xajax_callScript()” />

CAMBIOS EN LA VERSION 0.5 XAJAX

$xajax->registerFunction(‘funcion’);
X
$xajax->register(XAJAX_FUNCTION, ‘funcion’);
$xajax->processRequests();
X
$xajax->processRequest();
Publica todos los métodos públicos de un objeto:
$xajax->register( XAJAX_CALLABLE_OBJECT, $objeto);

Regexpal – Editor de expresiones regulares en línea

Acabo de encontrar una interesante herramienta para poder editar expresiones regulares en línea se llama RegexPal.

regex
Podemos ver en línea el resultado de nuestra expresión regular, asi como una información sobre los caracteres especiales que podemos utilizar.

Categories: Spanish, técnico Tags: , ,

AjaxRain Repositorio javascript, Ajax

January 22, 2009 2 comments

hace un tiempo encontre este portal AjaxRain que es a mi parecer unos de los portales más grandes de almacenamiento de código javascript y componentes Ajax organizados según los kits de desarrollo a los que pertenecen.

AjaxRain provee una invaluable cantidad de poderosos recursos para el desarrollo de interfaces Web, trabajando con los kits mas populares: jquery, dojo toolkit, yahoo, scriptacolous, prototype, lightbox, extjs, etc.

En Ajax Rain podemos encontrar un poco de todo, desde librerias para calendarios, sistemas de puntuación, tablas, gráficas, login, etc. La web te muestra imágenes de cada ejemplo, está ordenada por etiquetas y te permite votar los scripts y marcarlos como favoritos.

Actualmente cuenta con + de 1134 aplicaciones que podemos utilizar en los distintos lenguajes PHP, Asp.net entre otros.


ajaxrain

enlace: http://www.ajaxrain.com

FCKeditor bugs in Dokeos implementation – the debugging process

For the sake of remembering myself of what I did, not being an expert in JavaScript coding but still needing to fix that placeholder bug in Dokeos, I’m writing this part as a real log, not really a well-presented article, but I’m still publishing it in case it would help someone else.

In Dokeos, we use FCKeditor. The first problem that comes to mind is that I don’t know exactly which version. I didn’t integrate it, but based on this feature request, we use 2.2, while the current version (as of today) is 2.6.2. So there are considerable differences here. Julio is working on integrating version 2.6.2 for Dokeos 1.8.6, but I had to get working faster than that on the placeholder bug, that is, with the features we have added (as plugins or new developments) to Dokeos, you are able to insert a MP3 or a video into an HTML document. Well, this only works for adding resources, and the update feature doesn’t work (it does with the MP3 player, but not the video).

Some of the assumptions I’m taking below might be wrong, but the overall objective of this precise article (as opposed to all other articles on this blog) does not seek the truth but rather the effectiveness of debugging this tool.

As I don’t know anything about FCKeditor, I’m pretty much starting from scratch. I’m using the Firefox Firebug extension to see what’s happening in my code by putting breaks in the editor/js/fckeditorcode_gecko_1.js file, which is apparently where most things are happening.

FCKeditor works this way: you include the generic FCKeditor file from inside a document and call a function that will display the editor. The generic file is most likely fckeditor/fckeditor_1.js

This file includes fckeditor/editor/js/fck_startup.js, which checks which browser is used and loads either of the two pairs of files below:

  • fckeditor/editor/js/fckeditorcode_gecko_1.js
  • fckeditor/editor/js/fckeditorcode_gecko_2.js

OR

  • fckeditor/editor/js/fckeditorcode_ie_1.js
  • fckeditor/editor/js/fckeditorcode_ie_2.js

The version “1” of these files is actually defining most of the generic functions of FCKeditor. The version “2” just adds a few useful functions (I didn’t get that initially, I though version “2” was loaded because it was a recent browser version).

For the sake of simplicity, I will only use gecko in my examples below.

When you install a plugin into your FCKeditor, the plugin will have to be defined in the configuration file, and it will get picked up (along with its properties and methods) by fckeditorcode_gecko_2.js (var FCKPlugins = …).

Each plugin will define its own methods to deal with common upload, insert and delete of objects defined by the plugin (if this plugin is something to add resources, that is).

The tricky thing here is that, although you would think re-editing a page including one of these resources would call one of the plugins methods, it doesn’t (at least in this version of FCKeditor). In fact, maybe it does but the hand is very quickly given back to fckeditorcode_gecko_1.js, through the use of a method called oEditor.FCKDocumentProcessors_CreateFakeImage(  )

In this example, I am not giving any parameters to the function, but it generally takes two: a name and an object (the resource).

Somehow, however, and I haven’t found the link just yet, the switch that decides what type of resource this is and how it should be handled is found in fckeditorcode_gecko_1.js as:

For the sake of remembering myself of what I did, not being an expert in JavaScript coding but still needing to fix that placeholder bug in Dokeos, I’m writing this part as a real log, not really a well-presented article, but I’m still publishing it in case it would help someone else.

In Dokeos, we use FCKeditor. The first problem that comes to mind is that I don’t know exactly which version. I didn’t integrate it, but based on this feature request, we use 2.2, while the current version (as of today) is 2.6.2. So there are considerable differences here. Julio is working on integrating version 2.6.2 for Dokeos 1.8.6, but I had to get working faster than that on the placeholder bug, that is, with the features we have added (as plugins or new developments) to Dokeos, you are able to insert a MP3 or a video into an HTML document. Well, this only works for adding resources, and the update feature doesn’t work (it does with the MP3 player, but not the video).

Some of the assumptions I’m taking below might be wrong, but the overall objective of this precise article (as opposed to all other articles on this blog) does not seek the truth but rather the effectiveness of debugging this tool.

As I don’t know anything about FCKeditor, I’m pretty much starting from scratch. I’m using the Firefox Firebug extension to see what’s happening in my code by putting breaks in the editor/js/fckeditorcode_gecko_1.js file, which is apparently where most things are happening.

FCKeditor works this way: you include the generic FCKeditor file from inside a document and call a function that will display the editor. The generic file is most likely fckeditor/fckeditor_1.js

This file includes fckeditor/editor/js/fck_startup.js, which checks which browser is used and loads either of the two pairs of files below:

  • fckeditor/editor/js/fckeditorcode_gecko_1.js
  • fckeditor/editor/js/fckeditorcode_gecko_2.js

OR

  • fckeditor/editor/js/fckeditorcode_ie_1.js
  • fckeditor/editor/js/fckeditorcode_ie_2.js

The version “1” of these files is actually defining most of the generic functions of FCKeditor. The version “2” just adds a few useful functions (I didn’t get that initially, I though version “2” was loaded because it was a recent browser version).

For the sake of simplicity, I will only use gecko in my examples below.

When you install a plugin into your FCKeditor, the plugin will have to be defined in the configuration file, and it will get picked up (along with its properties and methods) by fckeditorcode_gecko_2.js (var FCKPlugins = …).

Each plugin will define its own methods to deal with common upload, insert and delete of objects defined by the plugin (if this plugin is something to add resources, that is).

The tricky thing here is that, although you would think re-editing a page including one of these resources would call one of the plugins methods, it doesn’t (at least in this version of FCKeditor). In fact, maybe it does but the hand is very quickly given back to fckeditorcode_gecko_1.js, through the use of a method called oEditor.FCKDocumentProcessors_CreateFakeImage(  )

In this example, I am not giving any parameters to the function, but it generally takes two: a name and an object (the resource).

Somehow, however, and I haven’t found the link just yet, the switch that decides what type of resource this is and how it should be handled is found in fckeditorcode_gecko_1.js as:

FCKFlashProcessor.ProcessDocument=function(A) { …

It looks like this function is called automatically from the editor when someone opens a new page for edtion. This function goes through the DOM element given and looks for EMBED or OBJECT tags, then disects them to find those resources we know are managed by plugins.

I have considerably updated this code already, and right now it looks like this (pretty ugly):

var FCKFlashProcessor=new Object();
FCKFlashProcessor.ProcessDocument=function(A)
{
//Treating tags first is a dirty hack. Because tags are enclosed into <object> tags,
// and because we treat <object> tags afterwards, we can do whatever we want here with embed tags
// inside the <object> tag and then remove the object tag when we get to it to “clean” it.
var B=A.getElementsByTagName(‘EMBED’);
var C;
var i=B.length-1;
while (i>=0&&(C=B[i–])){
if(C.parentNode && C.parentNode != null)
{
//check if the parent of this tag is an <object> tag. If so, just leave the process
//to the code in the next section, that treats objects specifically
if(C.parentNode.nodeName.toString().toLowerCase() == ‘object’) continue;
if (C.src.endsWith(‘.swf’,true)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};
var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__Flash’,D);
E.setAttribute(‘_fckflash’,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
}
else if (C.src.search(‘/\.flv&/’) || C.src.search(‘/\.avi&/’) || C.src.search(‘/\.mpg&/’) || C.src.search(‘/\.mpeg&/’) || C.src.search(‘/\.mov&/’) || C.src.search(‘/\.wmv&/’) || C.src.search(‘/\.rm&/’)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};
var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__Video’,D);
E.setAttribute(‘_fckVideo’,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
};
};
};
var B=A.getElementsByTagName(‘OBJECT’);
var C;
var i=B.length-1;
while (i>=0&&(C=B[i–])){
//look for the <param name=”movie” …> child
var F;
var j=C.childNodes.length-1;
var treated = false;
while (j>=0 && (F=C.childNodes[j–]) && treated == false){
if(C.parentNode && C.parentNode!=null && F.name && F.name.toString() == ‘movie’)
{
if(F.value.toString()!=” && F.value.toString().length>1)
{
//we have found an attribute <param name=”movie” …>
var Fval = F.value.toString();
if (Fval.endsWith(‘.mp3’,true)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};
var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__MP3’,D);
E.setAttribute(‘_fckmp3′,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
treated = true;
}else if (Fval.search(‘/\.avi&/’) || Fval.search(‘/\.mpg&/’) || Fval.search(‘/\.mpeg&/’) || Fval.search(‘/\.mov&/’) || Fval.search(‘/\.wmv&/’) || Fval.search(‘/\.rm&/’)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};

var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__Video’,D);
E.setAttribute(‘_fckVideo’,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
treated = true;
};
}
}
else if(C.parentNode && C.parentNode!=null && F.name && F.name.toString() == ‘FlashVars’)
{
if(F.value.toString().length>1)
{
//we have found an attribute <param name=”FlashVars” …>
var Fval = F.value.toString();
if (Fval.endsWith(‘.mp3’,true)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};
var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__MP3’,D);
E.setAttribute(‘_fckmp3′,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
treated = true;
}else if (Fval.search(‘/\.flv&/’)) {
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};

var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__Video_flv’,D);
E.setAttribute(‘_fckVideo’,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
treated = true;
}else if ( Fval.search(‘/\.avi&/’) || Fval.search(‘/\.mpg&/’) || Fval.search(‘/\.mpeg&/’) || Fval.search(‘/\.mov&/’) || Fval.search(‘/\.wmv&/’) || Fval.search(‘/\.rm&/’)){
var D=C.cloneNode(true);
if (FCKBrowserInfo.IsIE){
D.setAttribute(‘scale’,C.getAttribute(‘scale’));
D.setAttribute(‘play’,C.getAttribute(‘play’));
D.setAttribute(‘loop’,C.getAttribute(‘loop’));
D.setAttribute(‘menu’,C.getAttribute(‘menu’));
};

var E=FCKDocumentProcessors_CreateFakeImage(‘FCK__Video’,D);
E.setAttribute(‘_fckVideo’,’true’,0);
FCKFlashProcessor.RefreshView(E,C);
C.parentNode.insertBefore(E,C);
C.parentNode.removeChild(C);
treated = true;
};
}
}
}
};
};

So the problems are that:

  1. I’m not sure which part of the code actually gets the right tags out of the document when trying to guess the resource type
  2. This code still doesn’t handle videos resizing correctly (the video disappears with as little as selecting it).

After deeper analisys, the FCKFlashProcessor.ProcessDocument() method is the one that deals with analysing an HTML document and getting the graphical placeholders in place from <object> and tags. Something of the utmost importance in there is that the call to the FCKDocumentProcessors_CreateFakeImage() method has to take as a second argument the object that we are removing while showing the placeholder. This object will then be stored in a “bin” that will be used upon submission of the changes, to replace the placeholder by the initial and true object. If the reference is wrong there, there’s no way to recover the lost object.

The FCK.GetRealElement() is the method used to recover the “binned” object upon saving.

The corresponding changes have been added to the Dokeos SVN for Gecko browsers as of the 13th of July 2008. IE-changes will come soon.

JavaScript: Image rollover

This article was first written in May 2005 for the BeezNest technical
website (http://glasnost.beeznest.org/articles/258).

Description

Allow to implement images rollovers by simply defining the images of a specific CSS class.
Then you only have to call the function “rollover_register()” and pass it the optional parameters:

  • the CSS class you want to trigger. Default: “img.rollover”.
  • the pattern you want to add to the original image (e.g.: image.png and image.over.png). Default: “.over”.
  • the handler function for onMouseOver. Default: “rollover_over_handler”.
  • the handler function for onMouseOut. Default: “rollover_our_handler”.

Code

var rollover_pattern = '.over';

function rollover_register(selector, pattern, over, out)
{
        if (isNaN(selector)) selector='img.rollover';
        if (!isNaN(pattern)) rollover_pattern=pattern;
        if (isNaN(over)) over='rollover_over_handler';
        if (isNaN(out)) out='rollover_out_handler';
        elems=document.getElementsBySelector(selector);
        for (var i=0;i<elems.length;i++){
                addEvent(elems[i],'mouseover',eval(over));
                addEvent(elems[i],'mouseout',eval(out));
        }
}

function rollover_over_handler(e)
{
        // get the source element in a cross-browser way
        if (window.event) {
                img=window.event.srcElement;
        } else if (e.target) {
                img=e.target;
        } else {
                return;
        }
        img.src=img.src.replace(/(\.[a-z]+)$/i,rollover_pattern+'$1');
}

function rollover_out_handler(e)
{
        // get the source element in a cross-browser way
        if (window.event) {
                img=window.event.srcElement;
        } else if (e.target) {
                img=e.target;
        } else {
                return;
        }
        re=new RegExp(rollover_pattern.replace('.', '\.')+'(\\.[a-z]+)$', 'i');
        img.src=img.src.replace(re,'$1');
}

Dependencies

  • addEvent()
  • getElementsBySelector()

Usage

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
        <title>Image Rollover</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
        <script src="../events.js" language="JavaScript" type="text/javascript"></script>
        <script src="../getElementsBySelector.js" language="JavaScript" type="text/javascript"></script>
        <script src="../rollover.js" language="JavaScript" type="text/javascript"></script>
        <script language="JavaScript" type="text/javascript">
        addEvent(window, 'load', function _init() { rollover_register(); });
        </script>
</head>

<body>
<img src="image.gif" class="rollover" alt="image" />
</body>
</html>

JavaScript: getElementsBySelector()

This article was first written in May 2005 for the BeezNest technical
website (http://glasnost.beeznest.org/articles/257). As of 2008, I don't
remember the source exactly, but the links will lead you to them.

Inspired by Andy, I decided to have a crack at something I’ve been thinking about trying for a long time. document.getElementsBySelector is a javascript function which takes a standard CSS style selector and returns an array of elements objects from the document that match that selector. For example:

document.getElementsBySelector('div#main p a.external')

This will return an array containing all of the links that have ‘external’ in their class attribute and are contained inside a paragraph which is itself contained inside a div with its id attribute set to ‘main’.

So far I’ve only tested it on Phoenix but it seems to work as intended for the small number of test cases I’ve tried. If you spot any bugs please let me know. I’m about to fire up a Windows PC and see how much it breaks in IE…

Update: I’ve put together a demo page showing the function in action. It works fine in IE 6.

http://simon.incutio.com/archive/2003/03/25/getElementsBySelector

JavaScript Libraries

This article was first written in May 2005 for the BeezNest technical
website (http://glasnost.beeznest.org/articles/256). As of 2008, the most famous JavaScript libraries
are probably Dojo, JQuery and Prototype, but others like MeeBoo, Sarissa and Scriptaculous 
should be considered as well.

Dithered.com – Javascript Library

This is a collection of scripts that I’ve created and/or modified. All the scripts are released under a Creative Commons License. Do whatever you want with them – use them as is or modify them to suit your purposes. Both personal and commercial usage is ok by me.
Unless otherwise noted, all scripts degrade gracefully in older browsers that don’t support the functionality the script provides (ie. no error messages are triggered) and, with the obvious exception of the Browser Detect script, all use object detection instead of browser detection (which ensures a broad range of browsers will run these scripts including future browsers).
Website: http://www.dithered.com/javascript/index.html
Scripts: 1k DHTML API, Acrobat (PDF) Detection / Redirection, Browser Detect, Cookie API, Countdown Timer, Form Functions, Form Validation, Image Preloader, Quicktime Detection / Redirection, Rollovers, Window Opener Functions, Window Properties.
DOM Support / Extensions: Array Extensions, DOM1 Core, DOM2 Events, DOM2 Traversal, DOM2 Views, DOM Extensions.

Scott Andrew – The JavaScript Junkyard

The JavaScript Junkyard is a bunch of silly code I’ve found useful for one reason or the other. Some of them are truly useful, such as the cookie functions, while others are more like adventuresome like inPoly. Many of the geometry and trig-based functions were designed as components for arcade-style DHTML games.
Website: http://www.scottandrew.com/weblog/jsjunk Scripts: sortByProperty, addEvent / RemoveEvent, Cookie Functions, getQueryArgs, getRandomColor, readFile, roundTo, getDistance, getAngle, inPoly.

DomAPI

DomAPI is an application-centric development environment targeted at version 5.0 or better browsers running on Windows, MacOS and Linux. Supported browsers include Internet Explorer, Netscape Navigator, Mozilla, Safari, Chimera and Opera.
Website: http://www.domapi.com/
Licence: Versions <= 3: LGPL; >= 4: ?.