Home
About
Color Tool
 

Share Wonders is proudly powered by WordPress
Entries (RSS) and Comments (RSS).
11 queries. 0.566 seconds.
Valid XHTML

Archive for the 'javascript' Category

XSLT: tAsc 1.0 - An AJAX Powered JavaScript XSL Transformation Script

Wednesday, May 17th, 2006

I made tAsc 1.0 today. It is an AJAX powered JavaScript XSL Transformation (XSLT) script for Gecko browsers and Internet Explorer (6 & 7). I have made it very easy to use. Just follow the instructions in the beginning comments. All you need is a blank HTML page, and a preexisting XML file and its accompanying XSL stylesheet. There may be something like this out there already, probably better, but I wanted to learn how to do this and so I made this script and it works well.

Here is an example of tAsc 1.0. It works well in recent Gecko browsers (FireFox 1.5, Camino, Epiphany, etc) and IE6. It should also work in IE 7, but I haven’t tested it there yet. Let me know if you see any bugs or have any concerns. This script does not require any other libraries of any sort. It comes with an MIT License.

Here is the code:

/***********************************************
************************************************
NAME: tAsc v 1.0

DESCRIPTION:
An AJAX powered JavaScript XSL Transformation script
for Gecko browsers and Internet Explorer (6 & 7).

AUTHOR: Bjorn Tipling

EMAIL: bjorn (at) ambientchill (dot) com
Please use this email for bugs.

WEBSITE: https://sharewonders.com

LICENSE: MIT
http://www.opensource.org/licenses/mit-license.php

USAGE:
Create a basic HTML page with nothing within
the body tags. Link to this javascript file by
placing this in the header:

The tag should look like this:
with the same
id and and onload values.
Give xslFile and xmlFile the names of the xsl file
and the xml file respectively.

NOT ALL BROWSERS ARE CAPABLE OF JAVASCRIPT XSL
TRANSFORMATIONS. WILL ONLY WORK WITH LOCAL FILES.

************************************************
************************************************/

//Change these to the correct values:
var xslFile = ‘test.xsl’;
var xmlFile = ‘test.xml’;

var xmlGlobal;
var xslGlobal;
var xsltProcessorGlobal = new XSLTProcessor();

function start(){

var IE = document.all?true:false;

if(IE){
// Load XML
ieGetXML(’test.xml’);
}else{
// load the xslt file, test.xsl
ffGetXSL(xslFile);
}
}

function ffGetXSL(filename){
var httpRequest = new XMLHttpRequest();
httpRequest.open(”GET”, filename, true);
httpRequest.send(null);
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState==4) {
xslGlobal = httpRequest.responseXML;
xsltProcessorGlobal.importStylesheet(xslGlobal);
// load the xml file, test.xml
ffGetXML(xmlFile);
}
}
}

function ffGetXML(filename){
var httpRequest = new XMLHttpRequest();
var fragment;
httpRequest.open(”GET”, filename, true);
httpRequest.send(null);
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState==4) {
xmlGlobal = httpRequest.responseXML;
//do the transformation:
fragment = xsltProcessorGlobal.transformToFragment(xmlGlobal, document);
document.getElementById(”myBody”).innerHTML = “”;
document.getElementById(”myBody”).appendChild(fragment);
}
}
}

function ieGetXML(filename){
if (window.XMLHttpRequest)
{
var httpRequest = new XMLHttpRequest;
httpRequest.open(”GET”, filename, true);
httpRequest.send(null);
}else{
try {
httpRequest = new ActiveXObject(”Msxml2.XMLHTTP”);
} catch (e) {
try {
httpRequest = new ActiveXObject(”Microsoft.XMLHTTP”);
} catch (e) {}
}
}
httpRequest.onreadystatechange = function(){
var string;
if (httpRequest.readyState==4) {
xmlGlobal = httpRequest.responseXML;
ieGetXSL(xslFile);
}
}
httpRequest.open(”GET”, filename, true);
httpRequest.send(null);
}

function ieGetXSL(filename){
if (window.XMLHttpRequest)
{
var httpRequest = new XMLHttpRequest;
httpRequest.open(”GET”, filename);
httpRequest.send();
return httpRequest.responseXML.xml;
}else{
try {
httpRequest = new ActiveXObject(”Msxml2.XMLHTTP”);
} catch (e) {
try {
httpRequest = new ActiveXObject(”Microsoft.XMLHTTP”);
} catch (e) {}
}
httpRequest.onreadystatechange = function(){
var piece;
var string;
if (httpRequest.readyState==4) {
xslGlobal = httpRequest.responseXML;
piece = xmlGlobal.transformNode(xslGlobal);
document.getElementById(”myBody”).innerHTML = piece;
}
}
httpRequest.open(”GET”, filename, true);
httpRequest.send(null);
}
}

JavaScript: Easing Animation Formula

Thursday, May 11th, 2006

This page is an example of easing with JavaScript. Easing is slowing the transition of a moving object as it nears its intended destination. It looks much nicer than just a consistent rate of movement and a sudden and hard stop. When you put the breaks to your car as you near a red light, you slow down gradually. Imagine just going all the way to the stopline at the same speed you were driving and then just suddenly halting. Easing with JavaScript is more subtle than not slamming your breaks, but it is noticable.

The formula for easing is somewhat simple in Javascript, but you may have to tweak it a bit. With ActionScript in Flash it is much more straightforward: the speed of movement is half the distance. So if you’re 500 pixels away from your destination, you’re moving at 250 pixels per transition, at 499 you’re moving at (499/2):
rate = (distance - currentPosition)/2
currentPosition += rate

I still haven’t gotten it to look just the way I want it to, and I’m still using setTimout, and I am only experimenting, but here is my code:

distancePerInterval = Math.ceil((destination - parseInt($('mover').style.left))/32);

Not quite the same thing. It also does not move at the same speed in all browsers. In Firefox it is too fast, in IE it is too slow.
I will keep playing with it to see if I can get it to be just the way I want it.

setTimeout: JavaScript is Asynchronous - Animation with JS

Tuesday, May 9th, 2006

Did you see the title? Let me say it again: JavaScript is Asynchronous. I am not the best at explaining things, but bear with me.

It is not just AJAX that is asynchronous, the entire language seems to be that way. I have had a wonderful ‘AHA!’ moment, trying to figure out why setTimeout() was not working the way I wanted it do. I kept playing with it, until I figured it out.

Allow me to demonstrate what I mean. setTimeout() creates separate threads for each time it is called. You are probably going ‘huh?’ right now, but here: When you call setTimeout the code will not be run sequentially. Usually if you have code such as this:


function myFunction(){
for(i=0;i<4;i++){
alert('this is the first alert.');
alert('this is the second alert.');
}
}

You would expect a total of 8 alerts. The first alert, would be ‘this is the first alert.’, followed by the next one, then the ‘for loop’ iterates and goes through the loop again until the variable i is equal to 4 and it stops. That is sequential. First the first line is executed, then the next one down. In a loop you go through the same steps over.

In asynchronous code, this does not happen. JavaScript will create separate threads of execution. The code up there was one thread of execution, the main thread. Imagine the execution of code to be a spider climbing down a single ‘thread’ if you need to visualize this somehow. Each weave in the thread is another line of execution the spider climbs over. With setTimeout you split the thread into several threads, depending on how many times you call setTimeout. If you call it only once, you only create one more thread. Each thread will have its own spider making its way down, independently. Separately. The spider on the main thread (the first one before things split) is still going its own way, doing its own thing, executing code independent of the other threads.

So what do you do? Well, for setTimeout I was trying to do some animation, you know move a box like scriptaculous can, like the color picker on my color tool moves. I tried to call setTimeout to move a box incrementally, slowly, so it would look like animation, but because I did not understand how things don’t happen sequentially, it came out terrible. The solution was to wait until the thread created by setTimeout completed, and then call it again; that is wait until one thread was done, before creating the next.
Check out the difference:

setTimeout is asynchronous.

That page has two boxes, if you move the second one called ‘moverB’ by clicking the second link, you will see this code in action:

function calcMoveB(){
for(i=0;i<100;i++){
$('infoB').innerHTML += " >> All at once. “;
window.setTimeout(’moveB()’,'500′);
}
return;
}

function moveB(){
var element = $(’moverB’);
var x = parseInt(element.style.left);
x += 10;
element.style.left = x + “px”;
return;
}

That code above assumes that things happen sequentially, much like the first function I showed up above with the 8 alerts. This is incorrect. You can see that the ‘for loop’ in the function ‘calcMoveB’ iterates to completion before all the calls to the function ‘moveB()’ given to setTimeout to execute have even begun!

The first box, moverA, on the other hand waits until, the first pause of setTimeout has completed, and then calls setTimeout again (by calling ‘calcMove’ recursively):


var moveDistance = 10;
var moveAmount = 0;

function calcMoveA(){
$('infoA').innerHTML += " >> One step at a time. ";
window.setTimeout('moveA()','500');
return;
}

function moveA(){
var element = $('moverA');
var x = parseInt(element.style.left);
if(moveAmount < moveDistance){
moveAmount++;
calcMoveA();
x += 10;
element.style.left = x + "px";
}
return;
}

This is a recursive script that executes until moveAmount is equal to moveDistance. These are global variables. I think I have blabbered on enough. Look at the code, and the execution of that code carefully. I think I have demonstrated how setTimeout and JavaScript are asynchronous. If I have made any mistakes, or have any questions, let me know! That’s what comments are for.

Remove CSS with JavaScript

Sunday, May 7th, 2006

***UPDATE: Previous version didn’t work in IE. Ooops. This one does.

I’m working on an accessability panel for this webpage. One aspect of this panel will be to remove CSS styling. I thought someone out there in Googleland will be searching for such a thing for their site so I thought I would publish what I have. It is a pretty simple script, but some people not familiar with scripting might want this too. It only works on CSS, not depreciated HTML, and the rest of the instructions and usage warnings are in the script comments.

Here is a test page to see it in action: CSS Remove Test.

The code is below, but if you rather download it, here you go: cssRemove.js


/*******************************
REMOVE CSS SCRIPT
Filename: cssRemove.js
Author: Bjorn Tipling
Email:
Website: https://sharewonders.com
License: MIT License http://www.opensource.org/licenses/mit-license.php

Instructions:
Add:

inbetween your tags.
Add:

somewhere on your webpage. Click link to remove CSS. Customize as you wish with a class attribute.

IMPORTANT: This only works on CSS. Depreciated HTML tags and attributes such as or border=”1″ will not be removed.
********************************/

function removeStyle(){
var style;
var linkP = document.getElementById(’cssRemoveLink’);
for(i=0;i
void(document.styleSheets.item(i).disabled=true);
}
style = document.getElementsByTagName('*');
for ( i=0; i
void(style[i].style.cssText = '');
}
linkP.innerHTML = "CSS removed.";
return false;
}

Getting Color Information From Images with JavaScript, PHP, and the GDLib

Sunday, April 23rd, 2006

Colr.org has the ability to generate random colors from an image that you can load. I looked at the code and wondered why only one hundred randomly selected colors were loaded into the script, and I have now realized why.

There is a lot of data in image.

My own attempt at getting colors from images is a lot less random. You can hover over the image to get the color value for the pixel pointed at. It’s a nice feature, but it has draw backs. For one, it is really, really slow. Opera is the slowest and Firefox will throw ’script unresponsive’ warnings at the user (even though it’s just taking its time and will respond). Nevertheless I had fun making this. It works, and you can use it to get the RGB values from JPEG and PNG file types. It loads colors for GIF file types, but I’ve seen some inconsistency in it. There’s nothing to be done about it, I blame the GD Graphics Library, which only recently started to support gifs again.

So how do I do it? The image is loaded into PHP which uses the PHP image functions to get information for colors, including the color values for pixels. PHP records all the colors and their locations (for tens to hundreds of thousands of pixels), stores it in a string and sends it to JavaScript via AJAX. JavaScript then splits the string into several arrays, and associates rgb values with locations in a big multidimensional object. As the mouse hovers over the image, JavaScript uses onmousemove to get the X and Y position of the mouse pointer, calculates where it is above the image, and uses the location to retrieve the RGB values. JavaScript then converts the RGB values into a webcolor.

So there you go! Hopefully you’ll have some use for it. I know I will.

JavaScript and SVG

Sunday, April 23rd, 2006

Check out the following two pages. They’re an example of how JavaScript can be used to manipulate SVG. SVG are scalable vector graphics. It’s very cool!

(Note you’ll need to use Firefox or IE with the Adobe SVG Viewer plugin for you to be able to see this).

A clock SVG image that tells the time with JavaScript.

Three clickable elements in an SVG document that will change colors when you click on them. Yes, you can add events to elements in an SVG document!

I plan on doing some SVG manipulation with JavaScript too. It looks like you could do just about anything with this, perhaps even build a vector drawing application for the browser!

 

Share Wonders

Look out honey, because I’m using Technology