-
Update to addSizes (v0.3)
I have released version 0.3 of the addSizes script with various fixes and more file types. The code now looks at links to documents of the following types: pdf, doc, zip, mp3, ogg, m4u, jpg, png, swf. If you are using the script and want to add your own, feel free—let me know though, I would be interested to see how people use it.
Thanks to Marko Mrdjenovič for pointing out in a comment on the previous entry that I should in fact be using
encodeURIComponent()instead ofencodeURI()before sending the URL to json-head. It turns out encodeURI() assumes it is given an entire URL and does not escape & and other reserved characters.encodeURIComponent() on the other hand makes no such assumption and will escape all characters in the given string. Since json-head needs to take a fully escaped URI in order to get the head data,encodeURIComponent()should work better.In the original entry I should have stated more explicitly that this script will only work properly with files json-head can see. They need to be publicly visible on the web, ie files behind https may not behave as expected. I am still working on methods of getting around the issue with protected files.
A major fix to this version is that the code now works with relative file paths. Bizarly the issue relates to how I was getting the href of the link. With the previous versions I was using jQuery to get the href,
$(this).attr('href'), for relative file paths this returns the exact value, eg "media/test.doc". Changing this to usethis.href, fixes the issue as it actually interpretes the link to get the absolute URL. Magic.The code is released under the BSD license.
-
addSizes.js: Snazzy automatic link file-size generation
Often in the development of a site I come across the need to display the size of a document next to the link targeting it. I also like to display the type of file the link targets, for example, when linking to pdfs, mp3s or Word documents.
These indications distinguish the 'attachment' link from a normal web link, whilst also giving the user some inkling of the time they will need to wait to view the resulting content.
So I was pretty excited when Simon bounded in from work and enthusiastically demonstrated json-head, a Google App Engine application he built on the train home.
Every file on the web, be it a web page, a text file or whatever has HTTP headers associated with it. This is meta information about the file that is sent before the actual contents of the file itself. Included in this meta information is the size of the document.
You can call json-head with JavaScript (JSONP). It takes the URL of a file on the web and performs a HEAD request against it to return the headers and not the actual content itself. The application then returns this information in JavaScript object notation (JSON) to a callback function you have written.
One of the first things that occurred to me was how this could be used to solve the problem of dynamically adding the file size to links. The resulting script I wrote is being used on this site, so before I explain how it works here's a quick demo of a pdf document and an mp3 file. For a further demo take a look at this basic file.
Using jQuery we first use CSS selectors to find all of the links with the relevant file extensions:
$('a[href$=".pdf"], a[href$=".doc"], a[href$=".mp3"], a[href$=".m4u"]')For each link, we get the type of the target by splitting the href value on '
.' and grabbing the last value. This is the file extension.jQuery neatly abstracts the faff involved in using JSONP. We pass json-head the URL of the file we want to inspect and the name of the callback function we want it to run with the results. The callback function in this case is '
?', which tells jQuery to create a random function name hooked up to the function we pass togetJSON().var url= "http://json-head.appspot.com/?url="+encodeURI(this.href)+"&callback=?"; $.getJSON(url, function(json){ /* ... */ }We can now inspect the information sent to us by json-head. If everything went OK we have the size of the file in bytes in the
Content-Lengthheader.var length = parseInt(json.headers['Content-Length'], 10);
Once we have the exact size we need to do a bit more work to get human readable file sizes. We loop through an array to find the largest unit that fits. Once the right size has been found, the script breaks out of the loop storing the unit name and the length to 1 decimal place, so we end up with something like 1.2GB.
for(var i = 0; i < units.length; i++){ var unitSize = units[i][0]; var unitText = units[i][1]; if (length >= unitSize) { length = length / unitSize; // 1 decimal place length = Math.ceil(length * 10) / 10; var lengthUnits = unitText; break; } }Now the maths is over, all that remains is to insert the results back into the dom. I am using jQuery's
.after()method but if you wanted to insert the size and type directly into the link you could change this to use.append()I also add the type of the document as a class, to allow for additional styling such as adding an icon. A future version of the script will add the content type to the link as well.
link.after(' (' + type + ' ' + length + ' ' + lengthUnits + ')'); link.addClass(type);To use this script in your site, simply include jQuery and then the addSizes script itself will do the rest of the magic.
PLEASE NOTE: this may not be 100% reliable due to App Engine being occasionally and unavoidably flakey.
UPDATE: Please see the update to addSizes.
-
Anti-aliased Rounded corners with JQuery
-
Date slider widget
Date slider widget — Using Prototype / Scriptaculous this date slider allows you to choose a range of dates.
-
jQuery.ScrollTo
jQuery.ScrollTo — Very swish jQuery scrollto plugin.
-
Online beautifier for javascript (js beautify, pretty-print)
Online beautifier for javascript (js beautify, pretty-print) — Great online beautifier for javascript.
-
Google Analytics Integration with jQuery
Google Analytics Integration with jQuery — interesting plugin, I know there are some issues with file downloads and google analytics being used the old fashioned way.
-
YSlow for Firebug
YSlow for Firebug — integrated with Firebug this looks an interesting tool to help debug JS.
-
DebugBar - IE extension for web developer : DOM inspector, Javascript debugger, HTTP headers viewer, Cookies viewer
DebugBar - IE extension for web developer : DOM inspector, Javascript debugger, HTTP headers viewer, Cookies viewer — I have yet to play with this but it is effectively a 'firebug for ie' - Thanks Dan Webb for pointing me at this one.
-
Wait till I come! » Blog Archive » JavaScript shortcut notations that shouldn’t be black magic to the “average developer”
Wait till I come! » Blog Archive » JavaScript shortcut notations that shouldn’t be black magic to the “average developer” — Useful article on Javascript shortcuts from Christian Heilmann ... "OMG! Ponies!".
-
Background Image Maker
-
Grid Layout
Grid Layout — keybord co-ordinated grid layout toggle inspired by one of Jon Hicks's tweets.
-
Sangeeta asks the CSS Guy how to create a table like Orbitz's airline flights scheduling and pricing matrix (Ask the CSS Guy)
Sangeeta asks the CSS Guy how to create a table like Orbitz's airline flights scheduling and pricing matrix (Ask the CSS Guy) — Using tables cunningly.
-
jQuery UI: Widgets, Components, and Interactions
jQuery UI: Widgets, Components, and Interactions — Lovely plugin by the jQuery guys, the demos are still a little 'in development' but it has potential.
-
Displaying your flickr photos in an unobtrusive manner
Displaying your flickr photos in an unobtrusive manner — Really nice unobtrusive flickr badge from Chris Heilmann.
-
Farbtastic: jQuery color picker plug-in | Steven Wittens - Acko.net
Farbtastic: jQuery color picker plug-in | Steven Wittens - Acko.net — Fancy looking gjQuery colour picker.
-
Blueprints are not final
Blueprints are not final — I agree with this entirely.
-
BernieCode » How to debug JavaScript with Visual Web Developer Express
BernieCode » How to debug JavaScript with Visual Web Developer Express — Free useful javascript debugger for IE 6+7.
-
twittervision
twittervision — ooooh realtime twitter update visualisation by location, gosh I wish I had been watching this during eurovision! :).
-
Panic - Coda - One-Window Web Development for Mac OS X
Panic - Coda - One-Window Web Development for Mac OS X — So coda is pretty awesome, but currently a bit too buggy to use for professional development. The download site however is beautifully swish!
-
Uni-Form
Uni-Form — beautiful form design.
-
Handling Keyboard Shortcuts in JavaScript
Handling Keyboard Shortcuts in JavaScript — Looks like it could be quite a nive wrapper for keyboard shortcuts, might be good for accidental presses of Ctrl+S to save large text areas.
-
Keyboard Events and Codes
Keyboard Events and Codes — Keyboard event properties, handy reference that looks to be quite useful.
-
Unobtrusive connected select boxes - yet another solution approach - Wait till I come!
Unobtrusive connected select boxes - yet another solution approach - Wait till I come! — nicely implemented connected selects.
-
Timing and Synchronization in JavaScript
Timing and Synchronization in JavaScript — event grouping and the like.
-
Nifty Corners Layout
Nifty Corners Layout — New version of Nifty Corners ... still using the b tag with inline styles though I see.
-
Font detector
Font detector — using javascript and letter sizes to detect if a user has a font installed.
-
Creating web sites for the Wii Opera browser
Creating web sites for the Wii Opera browser — Using buttons and functionality on the wii-mote on your website with a js library ... crazy!
-
Better Living Through Bookmarklets [JavaScript & AJAX Tutorials]
Better Living Through Bookmarklets [JavaScript & AJAX Tutorials] — On the topic of auto making bookmarklets, Simon pointed out he wrote something similar back in 2004 (see pg2).
-
Daring Fireball: JavaScript Bookmarklet Builder
Daring Fireball: JavaScript Bookmarklet Builder — Script to build a bookmarklet from a script - very handy!
-
Bulletproof Ajax by Jeremy Keith
Bulletproof Ajax by Jeremy Keith — Definitely looking forward to having this in my bookshelf :).
-
swfIR: swf Image Replacement
swfIR: swf Image Replacement — This degrades nicely and is really quite sweet! - with everything going on recently I am beginning to be persuaded toward the benefits of flash - those who know me will note this is a big deal!
-
Stu Nicholls | CSSplay | Mini tabbed pages
Stu Nicholls | CSSplay | Mini tabbed pages — Cute, but I really dont like this type of user interface, where hoverover has an action that prompts a large change in form, its too easy to do by accident.
-
Prostitution :: hookr.net, a parody
Prostitution :: hookr.net, a parody — An 'interesting' usage of a maps mashup ... "A freely browsable database of prostitution in Chicago, with microformats.".
-
Em Calculator
Em Calculator — cute.
-
Event-Driven Web Application Design » Yahoo! User Interface Blog
Event-Driven Web Application Design » Yahoo! User Interface Blog — Designing exciting applications with events in mind.
-
Highslide JS - JavaScript thumbnail viewer
Highslide JS - JavaScript thumbnail viewer — This might be really really neat if it werent dreadfully slow, its also a bit anoying that the thumbnails disapear when you open up the larger image.
-
Unspace - Attributes > Classes: Custom DOM Attributes for Fun and Profit
Unspace - Attributes > Classes: Custom DOM Attributes for Fun and Profit — " [for] the ability to extend the nodes we use with customized, semantically meaningful attributes".
-
danwebb.net - Scripting Essentials
danwebb.net - Scripting Essentials — Dan Web's personal scripts as a library of essentials.
-
Really easy field validation * Dexagogo
-
Unobtrusive JavaScript by Christian Heilmann (Book)
Unobtrusive JavaScript by Christian Heilmann (Book) — Newly released book of the Unobtrusive Javascript tutorial.
-
Unobtrusive Javascript
Unobtrusive Javascript — Unobtrusive JS tutorial that I thought I had bookmarked ages ago but apparently not.
-
Linking a word automatically
Linking a word automatically — While serverside solutions are preferable for this sort of thing, this is a nice JS solution should you need one.
-
Vitamin Features » Create cross browser vector graphics
-
DerekAllard.com : Conditionally Sticky Sidebar
-
Firebug - Web Development Evolved
-
The Man in Blue > Resolution dependent layout update
The Man in Blue > Resolution dependent layout update — Update to the initial 2004 post on adding an additional stylesheet based on browser size.
-
Reliably attaching CSS
-
Reliably attaching CSS
In response to PPK's 24 ways article I thought I should describe the method I currently choose employ to hide elements onload. I have gone through this briefly in my article 'releasing the permalink slideshow'. As PPK mentioned, it is important to hide elements not needed for browsers that don't support JavaScript. The most important part of this hide technique is that there is no flicker in the period that the page is being loaded.
PPK suggests using document.write as to insert style elements inside the head. I propose instead using JavaScript's try / catch functionality to attach a stylesheet. Elements that need to be in the source for accessibility purposes, or need to be displayed for browsers without JavaScript, can then have a class that will hide them for browsers with JavaScript.
I like to use the try catch to ensure there are no issues in appending the link element to the head. The link contains the stylesheet that will then hide the elements that need to be hidden:
function setCSS(css) { try { // append stylesheet to alter document.getElementsByTagName("head")[0].appendChild(css); } catch (e) { setTimeout(function(){setCSS(css)}, 100); } } // create CSS element to set up the page var css = document.createElement("link"); css.setAttribute("href",path/to/stylesheet); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); // attempt to add the css and then keep trying till we do setCSS(css); css = null;The setTimeout ensures that if there is an issue attaching the link to the bottom of the head (e.g. if the head hasn't finished loading when the link is trying to be attached) it retries after 100ms. Resetting the css variable to null avoids potential memory leaks.
-
Rich text editor
Rich text editor — .
-
Using hasLayout to fix bugs in IE
Recently at work I came across a particularly tricky IE bug that I have seen a couple times now. I thought I would share the solution since it wasn't immediately obvious.
On the new Business in the community site (just launched by Torchbox) there is a timeline facility to show information about different events in Business, Politics and 'Business in the community' over time (Matthew did the awesome javascript that powers it).
The scrolling is controlled by animating the horizontal position relative value of the inner timeline div, the container window has
overflow: hidden. Whilst styling it, initially in quirks mode, the animation of the timeline div's worked just fine. IE behaved and respected the overflow on the container. However, in standards mode the overflow failed and the timeline divs were appearing outside of the container in both IE6 and 7, where of course other browsers were fine.
When debugged I realised that adding a position property fixed the issue, from this and from experience it was then apparent that the inner timeline was having its hasLayout property set to true in IE but the container was not.
The
hasLayoutproperty is Microsoft's way of identifying elements that form part of the structure of the page, it treats them differently and some crazy bugs can occur because of it. The solution was then to force the container to also sethasLayoutproperty to true, so putting position:relative on the container made theoverflow:hiddenbehave.hasLayoutis really annoying, it defaults to false unless (as found on the Microsoft site) an object has the properties height, display, float, position or width set (or also writingMode or zoom which are both proprietary Microsoft properties) however I would be careful believing entirely the 'remarks' section especially as it doesn't listposition:relativeas one of the triggers where as in fact it is.In case you haven't come across it before now, other craziness that can occur from the
hasLayoutproperty includes some elements disappearing behind containers with background colours (again quite easily fixed by forcing the elements inside to have thehasLayoutproperty as true)hasLayloutalso affects keyboard navigation in subtle ways as explained in this article. -
Lightbox JS
Lightbox JS — .
-
DOM Tool
DOM Tool — .
-
HowtoSimpleAjax - MochiKit - Trac
-
24 ways: DOM Scripting Your Way to Better Blockquotes
-
Javascript slideshow documentation
Javascript slideshow documentation — Documentation to easily reuse the permalink slideshow - now uses the YUI.
-
Graceful Exits » How to write a Javascript file
-
The continued adventures of the Permalink slideshow
In implementing the permalink slideshow for a few projects at work, it is now improved and a lot easier to set up. You can find the most recent version of the code here: http://natbat.net/code/clientside/js/permalinkSlideshow/slideshow.js (working example)
The idea now is that if you just follow a simple structure for your html, and create an additional stylesheet (that is imported with javascript) then all you need is the relevant javascript files (the slideshow one and the relevant YUI ones) and it should just work.
The script now relies on the Yahoo User interface library as this allowed for funkier effects other than just the linear fade I had wrote myself, as well as events and helper functions and the like. Naturally it is not perfect and there is still quite a bit that can be improved (such as the issue with conflicting namespaces) but it is definitely more customisable than it was and not such a nightmare to set up.
For the slideshow script to work you will need the Yahoo library's: 'yahoo', 'dom', 'event' and 'animation' to be imported before your slideshow js file (http://developer.yahoo.com/yui/)
<script type="text/javascript" src="/javascript/YUI/yahoo-min.js"></script> <script type="text/javascript" src="/javascript/YUI/dom-min.js"></script> <script type="text/javascript" src="/javascript/YUI/event-min.js"></script> <script type="text/javascript" src="/javascript/YUI/animation-min.js"></script> <script type="text/javascript" src="/javascript/slideshowFile.js"></script>
At the top of the new slideshow javascript file there are a number of global variables that are explained in the code, these control the hooks for the script and elements of its behaviour.
The compulsory variables are:
- u_fadeSlide - specifies how long the fade transition between slides will take - setting this variable to between 0.3 and 0.5 for a fade works nicely.
- u_importedCSSfile - the path from the root to the css file to import
- u_slideName - this is the initial id of your slide, without the number, the url may look like ... http://yourSite.com#slideName1 your slides will also need u_slideName as a classname
- u_slideTitlePrefix - this is the long title for your slide, it appears on the title bar
- u_slideContainerID - the containing div for your slides.
If you set u_fadeSlide to 0 the fade will be instantaneous and you need to take this into consideration when deciding if the height should be fixed or not, if the height cannot remain constant between slides (and you still *really* want fading) I will need to do more jiggery pokery in order to get it to work. At the moment the fade will only work with fixed height slides because currently they need to be positioned absolutely.
Your document will then need to follow the structure:
<div id="u_slideContainerID"> <div id="u_slideName1" class="u_slideName"> <!-- some sort of slide, an image or text or whatever --> </div> <div id="u_slideName2" class="u_slideName"> <!-- some sort of slide, an image or text or whatever --> </div> <div id="u_slideName3" class="u_slideName"> <!-- some sort of slide, an image or text or whatever --> </div> <div id="u_slideName4" class="u_slideName"> <!-- some sort of slide, an image or text or whatever --> </div> <!-- and on and on and on ..... (you can have other div's in here but not with the same class name or ID format)--> </div>In the initial styles for the page you will need to find a way of displaying all your slides so that it looks good on one page, this is what it will look like without javascript, you will probably want to set the next and previous links as well as the 'page X of X' text to display: none however leave your navigational elements as a list of permalinks to allow for navigation by non script enabled browsers. Your slide navigation may well resemble:
<ol id="u_navList"> <li><a href="u_slideName1">1</a></li> </ol>
In the css set the className 'selected' for the links in the above list to have some special style as this will be set with the JS for the slide that you are currently on. In the imported CSS you will need to override the
display: none's you did for the pages and next previous etc. (These aren't added dynamically btw because they could be anywhere in the page for a new version of this) then you want to make all the slides stack up on top of each other. One way to do this is to have the#u_slideContainerIDdiv set to position relative and the individual.u_slideNameset toposition: absolute; top:0;You will need to set the slides todisplay: noneand slide 1 todisplay: blockso it doesn't jump too much as the page loads (you may also need to set#slideshowSlide1 todisplay: block) the Javascript will work out the rest.An imported css file for a set of fading slides of all the same height might look something like:
#u_slideContainerID { position: relative; height: 200px; overflow: hidden; } #u_slideContainerID .u_slideName { position: absolute; top: 0; display: none; } #u_slideContainerID #u_slideName1, #u_slideContainerID #slideshowSlide1 { display: block; }Whereas you could miss the positioning and the height off if you are setting the
u_fadeSlide(the time between fades) to 0 so that the slide takes up its natural height:#u_slideContainerID { position: relative; } #u_slideContainerID .u_slideName { display: none; } #u_slideContainerID #u_slideName1, #u_slideContainerID #slideshowSlide1 { display: block; }The optional parameters can be left blank if not required but will not break the page if they are not accurate. These include:
- u_nextLink - the id or ids of the nextlink link elements, if more than one next link provide a comma separated list, e.g. 'id1,id2'
- u_previousLink - as above but with the previous page links
- u_navList - id of list for permalink paging elements, comma separated id list again
- u_pages - id of the paragraph where you want to put the text 'Page X of X' where the word 'page is replaced with u_slideName, e.g. 'chapter 1 of 7'
Printing the entire document like you can here on wrap is quite easy too, you need a function that removes the link to the imported stylesheet and you may also need to import a new stylesheet for printing, I haven't included a print function in this version yet though, as I said, its not quite perfect.
Looking at how it works, starting from the bottom up it attaches the imported stylesheet with a try catch instead of an onload event to avoid any flicker of styles:
function setCSS(css) { try { // append stylesheet to alter document.getElementsByTagName("head")[0].appendChild(css); } catch (e) { setTimeout(function(){setCSS(css)}, 100); } } // create CSS element to set up the page var css = document.createElement("link"); css.setAttribute("href",u_importedCSSfile); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); // attempt to add the css and then keep trying till we do setCSS(css); css = null;An onload listener then initiates the startup function which sets the whole thing going, it assigns all the id's of the slides to be in the form 'slideshowSlide', it needs to have a different id in order to avoid a jump in IE. It then identifies what slide we are supposed to be on if any, through the hash of the URL. Setting the title of the page and assigning the navigation is the next step, write what page we are on then display the current slide. The last step of the startup function is to set up an interval checker to listen to any changes in the URL.
Nothing happens then until a slide is requested, either through clicking the next previous links, changing the URL hash or using the permalink navigation. When this occurs (listeners set up in the initial call to the assign navigation function) the startFade function sets a global variable to indicate there is a fade in process, nothing can happen until it finishes, if it is ok for the fade to proceed it sets ever slide except the current slide to be
display:noneandvisibility: hidden, then it sets the requested slide to appear but as this has a lower z-index it is currently below the slide we are on.If the fade time is 0 it simply swaps the slides, otherwise it uses the YUI to fade the top slide out revealing the requested slide:
// fade the top slide onto the bottom var anim = new YAHOO.util.Anim(gSlides[gCurrentSlide], { opacity: { from: 1, to: 0 } }, u_fadeSlide, YAHOO.util.Easing.easeBoth); anim.onComplete.subscribe(function() { insEndFade(requestedSlide) }); anim.animate(); anim = null;The end fade function then sorts out the rest, resets the navigation, what page we are on, the page title and unsets the global fade variable to allow other fades to occur, finally restarting the URL checker to listen for changes to the URL.
So I hope that code this helps you if there is a need to have a fading slideshow, or even any kind of unobtrusive permalink pageable application, let me know if you have any trouble with it or have found a way of making it better!
-
A re-introduction to JavaScript - MDC
-
Particletree » Dynamic CSS Changes
Particletree » Dynamic CSS Changes — alternate stylesheets in js.
-
A List Apart: Articles: Print to Preview
-
Oxford Bus Routes
Oxford Bus Routes — very very cool!
-
dp.SyntaxHighlighter - free JavaScript syntax highlighting
dp.SyntaxHighlighter - free JavaScript syntax highlighting — .
-
API: Event YAHOO.util.Event.html (YUI Library)
-
Vitamin Features » 15 Things you can do with Yahoo! UI
-
Clearance // ShaunInman.com
-
Forget addEvent, use Yahoo!’s Event Utility
-
Neil Fraser: Software: MobWrite
Neil Fraser: Software: MobWrite — very veery cool inded.
-
Accessible JavaScript Newsticker | Bartelme Design
-
Screencast 02: Ajax with Connection Manager
Screencast 02: Ajax with Connection Manager — nice example of oo js via si.
-
Open Source Flash - flashaid
-
DOM Scripting: FlashAid
-
DonkeyMagic: Google Map Maker
-
Ryan J Lowe’s Dev Blog » Blog Archive » LITBox
-
Tracks
Tracks — .
-
AJAX Activity indicators | Animated GIFs designed to indicate your site is doing something
AJAX Activity indicators | Animated GIFs designed to indicate your site is doing something — .
-
SanBaldo » Blog Archive » Ajax loading animated gif
-
dp.SyntaxHighlighter - free JavaScript syntax highlighting
dp.SyntaxHighlighter - free JavaScript syntax highlighting — .
-
bobbyvandersluis.com | Unobtrusive Flash Objects (UFO) v3.0
bobbyvandersluis.com | Unobtrusive Flash Objects (UFO) v3.0 — .
-
Thierry Image Placement
-
Encytemedia: Working With Events In Prototype
-
A List Apart: Articles: Getting Started with Ajax
-
Preparatory notes for "The Yahoo! User Interface Library" at XTech
Preparatory notes for "The Yahoo! User Interface Library" at XTech — .
-
Simon Willison: Notes from my Yahoo! UI Library talk
-
bobbyvandersluis.com | Ten good practices for writing JavaScript in 2005
bobbyvandersluis.com | Ten good practices for writing JavaScript in 2005 — .
-
Unobtrusive Javascript
-
innerHTML for Mozilla (WebFX)
-
London JavaScript Night
-
A List Apart: Articles: A More Accessible Map
-
4.8. Inserting content after an element [Dive Into Greasemonkey]
4.8. Inserting content after an element [Dive Into Greasemonkey] — insertafter.
-
JavaScript tutorial - DOM objects and methods
-
A Basic Primer in Using S5
-
clagnut sandbox
clagnut sandbox — .
-
Nice titles
Nice titles — .
-
Flash / JavaScript Integration Kit
-
deconcept › FlashObject: Javascript Flash detection and embed script
deconcept › FlashObject: Javascript Flash detection and embed script — .
-
Rounded Corners with CSS and JavaScript [JavaScript & DHTML Tutorials]
Rounded Corners with CSS and JavaScript [JavaScript & DHTML Tutorials] — .
-
Javascript tooltips
-
JavaScript - Import XML Document
JavaScript - Import XML Document — neat way of turning XML into a table.
-
JavaScript Kit- DOM Element properties
-
JavaScript Memory Leaks - The JavaScript Weblog
JavaScript Memory Leaks - The JavaScript Weblog — more fun with memory leaks in DHTML.
-
Fixing JavaScript memory leaks for good. - talideon.com
Fixing JavaScript memory leaks for good. - talideon.com — I currently have a problem with my slideshow script, I have a feeling that this will magically fix it, perhaps.
-
Nearly there with the 'permalink-slideshow'
Well at the risk of too many entries on this permalink-slideshow, here goes another. I have always wanted (since i lost my fear of JavaScript) something that i can cut my teeth on so to speak. A medium-ly complex project to do in JavaScript that I can have fun playing around with, and more importantly to learn from. I think I may have found it.
This evening I have had some fun playing with performance, which incidentally seams to work fine now, there appeared to be a problem with the images stacking on top of each other with 'visibility: hidden' and a not-quite-opaque opacity. Using 'display: none' in addition seams to sort things out just fine. I also sorted out the weird forward / back problem pointed out by Richard by not letting the fade start unless it is not already running, unfortunately another global variable but unavoidable in this case I think.
The images now start at 1 not 0 because it made more sense when reading it, I also put in 'page x of x' at the bottom of the image and changed the document.title so that the back history remains understandable, quick fixes but quite a nice effect.
With regards to the image id's not matching the location.hash to avoid jumping, it really was quite a problem so I changed to my initial idea of 'position:absolute; top:0;' with the padding on the image to position it instead, though depending on how it will be used eventually the jump may be unavoidable. Oh well.
I still need to implement the funky image pre-loading trick as it hangs while you wait for the images to load, but other than that - and the hideous browser incompatibilities - I'm relatively happy with it. Tomorrow I show it to the people at work for real, if they don't like it that doesn't really matter as I have had a lot of fun making it!
Current working version:
UPDATE [4th Apr 06]: new demo (see comments for list of changes)
-
Fixing a few JavaScript slideshow loose ends
As pointed out by Jeremy, my linkable slideshow (v2) needed some work to fix the load order of the page without altering the 'unobtrusiveness' of its behaviour.
I opted for Jeremy's second method; not waiting for the page to load, instead hiding the images and sorting things out later on. Since the slideshow already relied on importing the CSS with JavaScript I simply moved this outside of the function called onload.
To ensure nothing untoward happens with crazy partial loaded DOM editing I encased the addition of the CSS into a try / catch. On fail of inserting the link rel into the page, the function then simply just calls itself again.
So in the root of the JavaScript file:
... function setCSS(css) { try { // append stylesheet to alter document.getElementsByTagName("head")[0].appendChild(css); } catch (e) { setTimeout(function(){setCSS(css)}, 100); } } // on load addEvent(window, 'load', setupPage); // create CSS element to set up the page var css = document.createElement("link"); css.setAttribute("href","style3.css"); css.setAttribute("rel","stylesheet"); css.setAttribute("type","text/css"); // attempt to add the css and then keep trying till we do setCSS(css);The CSS then sets all the images except the first one (over-ridden in the JS) to have 'visibility: hidden;' and to be positioned absolute in the right place.
Other changes to this version include vague attempts to improve performance through clearing the setInterval() during the fade and resetting after, also through using 'display: none' as well as the visibility. This seamed to improve it slightly but nothing revolutionary, it always slows down after 7 or so images regardless of how long you leave between page load and moving to an image.
Image maps work right enough with the slideshow too now which is good, since this was part of the original specification. I also stopped the jumping due to the id's of the image, I am not too pleased with the solution to this as it involves using a different hash fragment to the image id's.
The jumping was due to the browser automatically moving to the top of the image with the id, using non-existent id's stopped this problem but does sort of spoil the seamless effect. For example if i bookmark an image then turn off JavaScript that bookmark will no longer work. The only other solution I can think of to this issue is playing with z-indexes of the other page elements and having the image positioned absolute at the top of the page with padding down to the appropriate height.
This new version is available for your interest here:
-
mad4milk : scroll your internal links smoothly
-
mootoolkit documentation
mootoolkit documentation — very neat solution to the issue of violating page model with in page links, like back to top etc.
-
JavaScript slideshow fun
There are things that go smoothly, run like a dream and never complain; there are others that don't. For me, debugging JavaScript is always one the latter.
I have only recently begun to appreciate the power and fun to be had hacking at javascript, I used to panic at the thought of it. This was until I joined Torchbox where I received not only the help and confidence boost I needed, but also the office has a copy of Stuart's book '
