Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, December 3, 2008

Javascript image clipping

I was looking all over the place for some javascript code to clip images. The answer was right under my nose. What I needed was already built into HTML.

HTML DOM clip Property

The clip property sets the shape of an element.

What happens if an image is larger than the element it goes inside? - The "clip" property lets you specify the dimensions of an element that should be visible, and the element is clipped into this shape, and displayed.

Object.style.clip=rect(top,right,bottom,left)auto

rect(top,right,bottom,left) - Sets the shape of the element
auto - The browser sets the shape of the element

More... HTML DOM clip Property

Thursday, September 25, 2008

JavaScript load placement

Bigi Lui.

Programming for the Internet is fraught with a whole host of things that you can't depend on, but for the moment I'll be satisfied with talking about one of them: timing.
Any JavaScript that affects the way a page displays – either its content or its styling – has to first make sure that everything it requires is there i.e. that the page it's working on is downloaded (and parsed). Traditionally (well, for the past couple of years) this requirement has been met in one of two ways: placing an onload function call on the body element, or placing an automatically executed script late in the content of the page. However, these two methods have their disadvantages. Namely, that they can take a while to execute and thereby account for a page flicker where the content is visible before it has been transformed.
To demonstrate this, I've created an example page where a set of tables is hidden using JavaScript and a select box is used to display a particular one. There are four different pages of differing size (content after the tables) and each page has three different methods of running the JavaScript which hides the tables.
The third method is one of my own devising: a scheduling script that runs as soon as the "head" scripts are executed, but which checks to see if the required elements (the tables) exist yet. If they exist they are transformed, if they do not exist the script is scheduled to run after a short wait (1 millisecond), whereby it checks again ... Here's the results:*
Time taken to load JavaScript that hides page elements (Firefox)
body.onload
Content call
JavaScript scheduler
Small page 1103ms 1081ms 1062ms
Medium page 1128ms 1150ms 1134ms
Large page 1531ms 2621ms 1534ms
Image 11331ms 1849ms 1015ms
Time taken to load JavaScript that hides page elements (IE 6)
body.onload
Content call
JavaScript scheduler
Small page 2250ms 1644ms 1437ms
Medium page 2199ms 1522ms 1475ms
Large page 2256ms 1566ms 1509ms
Image 12556ms 3050ms 1628ms
*Times were averaged out over 5 attempts for each combination over a 56kb connection. Cache was cleared for each attempt. Timing of execution was initialised by the first script in the "head" and terminated when the function that hides the tables was executed.
At first glance, large differences can be seen in body.onload initialisation between Firefox and Internet Explorer. IE seems to only regard "body" as loaded until after CSS background images have been downloaded, whereas Firefox appears to treat "body" as loaded once its code has been downloaded and parsed.
The filesize of the web pages doesn't appear to affect JavaScript load times too greatly, but it can clearly be seen that the introduction of an image file adversely affects body.onload initialisation. Content calling and scheduling were on a rough par, but improvements could be seen in the scheduler for larger files and images.
Given the poor performance of body.onload under varying circumstances, it would appear that this is not a good option for the initialisation of page transforming JavaScript. Content calls could be an alternative, but they do not guarantee that the required content will be loaded, and they also require alteration of the page content itself. Scheduling of transformation appears to be the safer and faster option, although it still does not prevent flickering of content.

More...
http://www.themaninblue.com/writing/perspective/2004/09/29/

Javascript Q&A

Q - How is JavaScript executed by browsers?
A - JavaScript is parsed first (analyzed), and then it is executed (carried out). If an error is found in the code during the parsing phase, then the execution phase is canceled. If the JavaScript contains no errors, then the code is executed by the browser. In the context of a browser, this means that statements written in the global scope that are not functions, get executed.
Q - In what order is JavaScript executed in a browser?
A - Inline and external scripts are executed in the order in which they appear in an (x)HTML document. The contents of each script is parsed and executed before continuing on to the next script. It should be noted that the loading of an (x)HTML page is halted while loading external JavaScript files.
Q - In what order are (x)HTML pages and there assets loaded?
A - Browsers will loosely load an (x)HTML document in the following order:
(x)HTML is parsed by the browser
External scripts/style sheets are loaded
Scripts are executed as they are parsed in the document
(x)HTML DOM is fully constructed
img, embed, object, and iframe content is loaded
The page is finished loading and the JavaScript onload event is invoked
Q - What is the onload event?
A - The onload property of the window object specifies an event handler function that is invoked when a document or frameset is completely loaded into its window or frame. This property can also be set by using the onload attribute of the body element.
Q - Why isn't the window.onload adequate for all my DOM scripting needs?
A - There are two major limitations to the onload property. The first limitation is that this property can only accept one function. If you try to attach two functions to this event, the last one declared will be attached to the event and the first function assigned will be discarded.
The second limitation of window.onload is that the event fires only after everything in an (x)HTML document is loaded — including images, flash, and frames! Waiting for these elements to load before the onload event is fired can cause UI errors if the user tries to interact with the page before the JavaScript event handlers have been applied to the DOM via the onload event. Moreover, the user experience can really suffer if JavaScript functionality is delayed due to large assets being loaded into the browser.
Q - Why do I often see JavaScript written/included before the closing body element in an (x)HTML document?
A - DOM elements can not be accessed by JavaScript until the browser has loaded the HTML elements into the DOM. By placing JavaScript at the end of an (x)HTML document (before the closing body element), you will ensure that the script is called as soon as the DOM is constructed/loaded and ready for manipulation. An advantage of this approach is that JavaScript code is executed right after the DOM is constructed and possibly before the onload event would fire.
JavaScript beginners get tripped up by this constantly by placing code that manipulates the DOM in the header element of an (x)HTML document. This causes an error because the DOM has not yet been constructed and thus is not yet accessible to JavaScript that traverses/manipulates the DOM.
Q - Is JavaScript in the global scope still being executed even after the onload event is fired?
A - All JavaScript that is available when the browser first parses the page is executed before the onload event is fired. Of course, other events can trigger JavaScript execution after the onload event.
Q - Can you explain the difference between the following DOM event techniques: onload, DOM Ready, and Element Ready?
A - All of these techniques are essentially used to execute JavaScript only after the entire page has been loaded, the DOM has completely loaded, or the DOM has partially loaded in a web browser. Below I specifically discuss each technique.
onload - This technique is rather self explanatory. A Function assigned to the onload property of the window object will be executed once an (x)HTML document has been completely loaded by a web browser. For example:
view plaincopy to clipboardprint
//
window.onload = function(){ alert("page loaded") };
// //
window.onload = function(){ alert("page loaded") };
//

Since only one function can be assigned to this property at a time, many developers started using an event utility script to add multiple onload handlers to a web page. You might be familiar with the original addevent script, and its numerous predecessors.
DOM ready - This technique tries to improve upon the onload technique by executing javascript code once the DOM is constructed, and before the page has actually finished loading. How this is done has been the topic of numerous blog posts.
Element ready - This technique attempts to surpass the DOM ready technique by checking the DOM loading status at intervals for the availability of a specific element. Doing this will allow for the execution of JavaScript DOM manipulation code as soon as the element itself, but not necessarily the entire DOM, is ready.
Q - Can I assign an event handler to window.onload, and at the same time set the onload attribute of the body element to a different event handler?
A - No, providing a value to the onload attribute of the body element will override any event handlers you assign to the window object.
Q - What is meant when it is said that client-side javascript is single threaded?
A - This means that the parsing of (x)HTML documents stops while scripts are loaded and executed, and that web browsers stop responding to user input while event handlers are being executed.
This is a good thing, and a bad thing. It's good because you can rest comfortable knowing that two event handlers will never run at the same time. Also, you can manipulate document content knowing that no other thread is attempting to modify the same piece of content.
It's bad in that intensive scripts can hold up the user experience by causing periods of unresponsiveness from a JavaScript driven UI.

More...
http://javascriptant.com/articles/
http://javascriptant.com/articles/10/qa-on-javascript-execution-onload-techniques

Tuesday, September 9, 2008

Creating time delays in Javascript

Creating time delays
There are two ways of creating time delays with JavaScript. The first is more simple and will simply wait for a specified amount of time before executing a function. The second does the same but will repeatedly execute the function.

Note, most browsers have a minimum delay length of between 25 and 75 ms. If a shorter delay is specified, the actual delay will be the minimum delay length. Even with higher numbers, the delay is never perfect. Most browsers will take slightly longer than the time you ask for, typically just a few miliseconds error. Some may correct their errors over time with interval timers. Also note, setting many timers with short delays on one page will cause the browser to become slow and somewhat unresponsive. Three or four timers is usually the reliable limit.

setTimeout
The first method uses a window method called setTimeout(). The method waits for a specified number of milliseconds then executes the specified code. The code can either be a direct reference to a function, or it can be a string that will be evaluated as if it contained source code.

window.setTimeout(referenceToFunction,timeInMilliseconds);window.setTimeout('runMoreCode()',timeInMilliseconds);Wherever possible, you should use a direct function reference as it is much more efficient. Using a string requires the browser to create a new script environment so it can process the script.

If you create a timeout, the code after the call to setTimeout will continue to run as normal. After the specified delay, the timeout will start a new thread, and the code specified in the call to setTimeout will be run in the new thread, along side any code that is still running in the initial thread. Unlike with many more complex languages, JavaScript does not offer any way to control when those threads sleep, wake, or yield. The JavaScript engine handles all of that, and you must accept that your new thread could be executing at any time next to another thread. Many JavaScript engines will simply allow one thread to complete before allowing the other thread to start. The same applies to events, which run in their own threads, and can be triggered at any time.

More...
http://www.howtocreate.co.uk/tutorials/javascript/timers

Monday, September 8, 2008

W3 Scools, HTML, CSS Javascript, XML, Etc..

Full Web Building Tutorials - All Free
The Largest Web Developer Site on the Net.

At W3Schools you will find all the Web-building tutorials you need, from basic HTML and XHTML to advanced XML, SQL, Database, Multimedia and WAP.

More...
http://www.w3schools.com/

Sunday, September 7, 2008

Cookies in JavaScript

Written by Jason Davies Topics: JavaScript

This tutorial should get you started with cookies in JavaScript. Some utility JavaScript functions are included for you to use freely in your own code.

JavaScript cookies are easily manipulated using the document.cookie property.

Setting Cookies
To set a cookie all we need to do is assign a value to the document.cookie property.

document.cookie = "name=value";
Retrieving Cookies
Reading cookies is equally as easy. Simple read the value of document.cookie.

alert(document.cookie);
JavaScript Cookie Functions
This all looks very simple, but what about getting cookies with a specific name, or setting expiry dates? To do this we need to use a bunch of utility cookie functions.

/**
* Sets a Cookie with the given name and value.
*
* name Name of the cookie
* value Value of the cookie
* [expires] Expiration date of the cookie (default: end of current session)
* [path] Path where the cookie is valid (default: path of calling document)
* [domain] Domain where the cookie is valid
* (default: domain of calling document)
* [secure] Boolean value indicating if the cookie transmission requires a
* secure transmission
*/
function setCookie(name, value, expires, path, domain, secure) {
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}

/**
* Gets the value of the specified cookie.
*
* name Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
* or null if cookie does not exist.
*/
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Deletes the specified cookie.
*
* name name of the cookie
* [path] path of the cookie (must be same as path used to create cookie)
* [domain] domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

More...

http://www.netspade.com/2005/11/16/javascript-cookies/

ASP.Net Feeds