Aug 20 2010

Image background fallback using <img/> tag error handlers

Category: javascriptDavide Zanotti @ 3:49 pm

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 :^)


Dec 16 2009

Extending Eclipse using JavaScript and Monkey Script engine

Category: javascriptDavide Zanotti @ 9:20 am

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

eclipse monkey script menu

ps: I’m going to explore the Monkey Script API in order to write more complex and useful extensions :P

Tags: , ,


Sep 10 2009

Find outermost top level XML/HTML tags with regular expressions

Category: javascriptDavide Zanotti @ 7:58 am

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

Tags: ,


Jun 12 2009

Adapting iframe height to its content with 2 lines of javascript

Category: javascriptDavide Zanotti @ 2:38 am

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";
           
}

Tags: ,


May 29 2009

Jetpack: building Firefox plugin with Javascript (and jQuery)

Category: browsers,javascriptDavide Zanotti @ 8:08 am

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

Tags: , , , ,


Next Page »