coder and technology lover
javascript
Image background fallback using <img/> tag error handlers
Aug 20th
In the project I’m working on, we make large use of external assets like images, coming from several providers. Unfortunately these links are often broken, resulting in “empty squares” which are unpleasant for the user. The best thing to do, since we don’t have the full control over these resources, is to display the classic “image not available” pic, but this is not simple as writing an if statement such:
1 2 3 4 5 | if (record.image) { <img src="record.image" /> } else { <img src="imageNotAvailableLink" /> } |
because in our case “record.image” is defined although its path is unreachable. So, we have to try to load the image and replace it at runtime when we know that the src is broken. How can we catch that exception? We just need to listen to onerror and onabort img events, so we can simply write this smart img tag:
1 | <img src="providerSrc" onerror="this.src=fallbackSrc" onabort="this.src=fallbackSrc" /> |
The this key inside an event attribute, refers to the dom node itself, so we can switch an attribute like src with a little piece of inline JavaScript.
Anyway in my scenario the problem is bigger than this example, because thumbs images are rendered as divs background in order to make a sort of polaroid effect and, at the same time, to solve a potential issue related to exceeding image dimensions or a stretched one.
Fortunately the solution I found, is not so far from the above, the only difference is that I used an invisible img tag located inside the div and when it catch the error rather than change its src it changes its parent background:
1 2 3 | <div style="background:url(providerSrc)"> <img style="display:none" src="providerSrc" onerror="this.parentNode.style.backgroundImage='url(fallbackSrc)'" /> </div> |
Of course in my final implementation I replaced the piece of inline js assignment with an utility function call that does the job and also trace a debug message to the console, displaying the path of the broken image… I’m pretty satisfied about my work :^)
Extending Eclipse using JavaScript and Monkey Script engine
Dec 16th
I was wondering how to wrap a string with quotes in Eclipse by using a shortcut, then I realized that there is not such command, so I started thinking for a solution and initially I created an Aptana’s snippet, but I was not satisfied, because I want to have an handy shortcut to invoke my snippet. By googling, I discovered Eclipse Monkey Script engine, that is an extremely powerful tool for every JavaScript developer who wants to extend Eclipse features by writing few lines of JavaScript code. In order to use the js engine, you must have the package org.eclipse.eclipsemonkey (which is installed by default by Aptana) installed. Unfortunately I can’t find a complete and exhaustive reference for this project, which seems forgotten by authors, so I learnt what I know reading different posts.
Basically, Monkey Script allow developers to access editor’s instance, get selected test, get document content, edit it and update it. Moreover is possible to print text to consol, read and create files on the filesystem… and finally the scripts created will be accessible from Eclipse menu (under “Scripts”) and invokable through user defined shortcut… really nice!
So, backing to my experiment, I created this monkey script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | /* * Key: M1+M2+C * Menu: Custom Scripts > Wrap with double quotes * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript * Kudos: Davide Zanotti */ function main() { // no editor... exit if (typeof editors.activeEditor == "undefined") { return alert("No active editor"); } // get a reference to the editor in use var editor = editors.activeEditor; // beginning of text selection var startOffset = editor.selectionRange.startingOffset; // end of text selection var endOffset = editor.selectionRange.endingOffset; // selected text var selection = editor.source.substring(startOffset, endOffset); try { // surround selection with quotes editor.applyEdit(startOffset, endOffset - startOffset, '"' + selection + '"'); } catch (e) { alert("Error " + e.code + ": " + e.message); } }; |
It’s important to notice some points, first you MUST write an “header” using the comment syntax “/* */” into which you MUST declare at least 2 parameter: the “Menu” path (you can nest several menu items by writing several “>”) and the “DOM” package (which allows you to access specific objects like “editors“). You can write several js functions, but you must provide a main() function, which is called automatically by Eclipse once you launch your script, otherwise you can call the main function as you like but you must then provide the “OnLoad” param in the header, specifying which function will be called.
To define a shortcut you can use the “Key” parameter and define your own keys combination by choosing among the four modifiers: M1, M2, M3, M4, that are a platform-independent way of representing keys (these stand for ALT, COMMAND, CTRL, and SHIFT). The strange (at least to me) parameter “Kudos” is used to declare the author of the monkey script.
To test my little script or create your own, you have simply to create a new project into Eclipse by calling it as you like (ie: “custom-extensions”), then create a “scripts” folder into which you will save your .js files… that’s all, try yourself and enjoy :)
This is how it looks:

eclipse monkey script menu
ps: I’m going to explore the Monkey Script API in order to write more complex and useful extensions :P
.cjs (Compiled JavaScript): an idea for a new file extension
Dec 10th
Due to the growing diffusion of tools to compress and optimize JavaScript files (such Google Closure), I feel the need of an introduction of a standard way to identify and differentiate them (compiled files) from other uncompressed files. Basically, I would adopt a different file extension like CJS (which stands for compiled/compressed JavaScript). In this way it would be easy to browse a directory of hundreds of js files and identify those which are ready to be used in our project because already compressed and optimized.
What do you think about?
Find outermost top level XML/HTML tags with regular expressions
Sep 10th
I’m working on a personal big project (which I’m going to release soon) and in this project I need to parse strings containing XHTML tags with the goal of extract the top level of a given tag name, ie. from:
1 2 3 4 5 6 7 8 9 | <onetag id="t1"> <onetag id="t1-1"></onetag> <onetag id="t1-2"></onetag> </onetag> <onetag id="t2"></onetag> <onetag id="t3"></onetag> <onetag id="t4"> <onetag id="t4-1"></onetag> </onetag> |
I have to get 4 tags (t1, t2, t3, t4 with t1 and t4 containing their child nodes).
My regex knowledge is unfortunately very basic, so I googled for a ready to use regex, but none satisfied my need… all the examples I found didn’t handle properly nested tags… so, after some hours of testing I realized my own regex (my first real one), the result is the following:
1 | var pattern = /<(onetag)[^<>]*>(<\1[^<>]*><\/\1>)*<\/\1>/gi; |
In my case I’m using that pattern in Javascript, but I think it can be used with any language, because it doesn’t make use of advanced features like “atomic grouping” and these kind of “black magics”. To match the desired tag you can use it by replacing “onetag” with the tag you are looking for (even a tag with a namespace like “<foo:mytag>”).
EDIT:
The pattern above will work only if applied to a single line string (ie: var myString = “<onetag id=’t1′>…”), if you use that pattern on a “complex string” (a string containing spaces and new lines) it won’t works properly. Fortunately you can remove “bad characters” before by using a simple replace:
1 | var parsedString = originalString.replace(/\s(?!\w)/gi, "").match(pattern); |
\s(?!\w) will match any space and new line not followed by an alphanumeric characters (in this way spaces between tag attributes won’t be removed)
EDIT 2:
The pattern /<(onetag)[^<>]*>(<\1[^<>]*><\/\1>)*<\/\1>/gi won’t works properly in presence of several type of nested tags, ie:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <onetag id="t1"> <anothertag> <onetag id="t1-1"></onetag> <onetag id="t1-2"></onetag> </anothertag> </onetag> <onetag id="t2"></onetag> <onetag id="t3"></onetag> <onetag id="t4"> <anothertag> <onetag id="t4-1"></onetag> </anothertag> </onetag> |
The updated pattern is the following:
1 | var newP = /<(onetag)[^<>]*>.*?(<\1[^<>]*>.*?<\/\1>)*.*?<\/\1>/gi; |
I hope this will works without further modifications :P
Adapting iframe height to its content with 2 lines of javascript
Jun 12th
In a project, I have to use an iframe and I need that its height is automatically calculated based on its content. However is not possible to accomplish this by simply setting the attribute height to 100%, instead we must smartly use javascript to dynamically assign that value after a computation. The solution I’m going to show you is not 100% my work but instead an optimization and a better implementation of clever intuitions I found on the web.
The “trick” works in this way:
1. The iframe should has an ID assigned:
1 | <iframe id="slideshow_frame" src="frame.html" frameborder="0" width="100%" marginheight="0" marginwidth="0" scrolling="no"></iframe> |
2. the page loaded into the iframe should contains all the html into an “easy retrievable” container (a div with an ID is perfect!):
1 2 3 4 5 | <div id="content"> <div style="background: red; width: 400px; height: 120px"></div> <div style="background: green; width: 400px; height: 300px"></div> <div style="background: yellow; width: 400px; height: 60px"></div> </div> |
3. on the iframe’s page “onload” event, a function will be executed to adjust its height:
1 2 3 4 5 6 7 8 | function resizeIframe(iframeID) { var iframe = window.parent.document.getElementById(iframeID); var container = document.getElementById("content"); iframe.style.height = container.offsetHeight + "px"; } |
Jetpack: building Firefox plugin with Javascript (and jQuery)
May 29th
I discovered a couple of days ago a new open source project from Mozilla labs: Jetpack.
It’s an “API set” which allows to build Firefox’s plugins by using Javascript, HTML (including new HTML 5 tags: “video” and “audio“) and CSS (oh yes, in a single word Ajax).
Jetpack is still in an early development phase and released as 0.1 version.
Here you can find the (really brief) api documentation and here some examples.
I would like to try it in the future
jQuery is not a magic… if you think so, you shouldn’t use it!
Apr 28th
I decided to write this post, because I revised a Javascript code realized by a colleague and it was simply terrifying!
It was bad formatted, it had HTML style comments (<!- – - ->) with insignificant or unclear content, missing var declarations and so on.
What I would like to say is that, in order to use jQuery and similar js libraries a mere HTML knowledge is not enough, Javascript is not hard to understand and use as Java, C++ or other object oriented programming languages are, but several things must be clear before to write some code. If you want to use in a clever and productive way such libraries you should at least:
- Understand the difference and behavior of String, Number, Array, Date and so on
- Have a deep understanding of what DOM is and how it works (you should at least know these methods: getElementbyId(), getElementsByTagName(), createElement(), appendChild(), removeChild() and innerHTML property)
- Know what objects and constructors are and how they behave
- Know what a function is and how to create one
- Know events, event listeners and event handlers
- Understand loops
Too much stuff to learn? It’s the minimum to know, there are then prototyping, JSON, closures, XMLHttpRequest and so on…
Javascript is a programming language (not a tool for designers), don’t believe that a call to $.doMagic() will resolve your problems, you have to understand what is behind that doMagic() (at least the foundations) in order to realize concrete stuff… otherwise you will only write “magic spaghetti code”!
Using jQuery to load an XML configuration file
Mar 11th
At work I’m integrating Viamichelin’s map api on a site and I realized a Javascript class which works as a proxy to Viamichelin’s services.
The api provide several methods to customize appearance of map’s controls and ui components (colors, dimensions, opacity and so on) but following the api’s documentation and examples this means to have several “hard coded” settings inside my code, which is an issue I want to avoid, so I thought to use an external XML configuration file and then call the methods using parametric values (which are retrieved by reading the file). Is pretty simple with ajax to load a text file, the only problem is that by default (or better, by nature) ajax is asynchronous and this can be an obstacle but fortunately with jQuery (but even with other libraries and personal XMLHttpRequest implementation) we can make synchronous calls by specifying it.
Object oriented programming in Javascript
Mar 10th
After several approaches, I finally found an elegant and functional solution to use Javascript in an OOP way, without use third party libraries or use particular tricks.
The objectives I had in mind was:
- Realize a Java/Actionscript-like class
- Provide a constructor for the class
- Implementing public method
- Implementing private method
- Ensure encapsulation (class properties can’t be changed by assigning a value to the relative instance’s property)
parseInt(): difference between Javascript and Actionscript
Mar 6th
Today is the day of the little big discoveries. I realized that the parseInt() function, which objective is the same in both languages (Actionscript and Javascript), is a bit different between them. In Actionscript the function is based on base 10 numeration, in Javascript instead the funny thing is that it try to guess the radix by analyzing the string received as first argument, so if you want to be sure of the result returned you have to explicitly pass the radix in the second argument.
Example:
var myString = "000123"; alert(parseInt(myString));
The code above will alert 83 instead of 123 (because the default base guessed by Javascript isn’t 10 like in Actionscript), to get 123 the code must be:
var myString = "000123"; alert(parseInt(myString, 10));
Recent comments