1. new CSS3 properties in Firefox 3.5 – *-of-type

    In today’s feature post we’ll talk briefly about three new CSS3 pseudo-classes: only-of-type, first-of-type and last-of-type. These are all very similar to the *-nth classes we covered in an earlier post.

    first-of-type and last-of-type

    These two pseudo-classes allow you to select the first and last item in a list of siblings within a particular element. You can use this to color the first item in a list, use opacity to make the last paragraph on a page fade out or a number of other things. Here’s an example that sets small caps on the first paragraph of a document:

    #type-ex1 div:first-of-type {
        font-variant: small-caps;
    }
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nulla neque, cursus venenatis vehicula ac, rutrum id libero. Nullam porttitor ultricies eros, laoreet mollis nunc vestibulum in. Sed iaculis nibh nec tellus vulputate pulvinar. Aliquam ultricies mauris vel nulla semper ac dignissim arcu sollicitudin.
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras molestie elit sed libero pretium faucibus. Ut sed lacus eget est gravida aliquet sed sed risus. Maecenas vitae volutpat purus. Fusce porttitor aliquam lectus sit amet vehicula. Nulla molestie mi lacus.

    only-of-type

    only-of-type is similar to the previous two, but only selects an element if it has no siblings with the same name. Here’s a somewhat contrived example* that will hide single images inside of a div. If there’s more than one image in the div they will be visible:

    .type-ex2 img:only-of-type {
        display: none;
    }
    This is some text before a single image.

    This is some text after a single image.
    This is some text before two images.


    This is some text after two images.

    And that’s it. Enjoy!

    [ * Note: if someone can come up with a better example for only-of-type I'm all ears. There are very few examples of where this is useful. ]

  2. exploring music with the audio tag

    Today’s demo comes to us from Samuel Goldszmidt. He’s a web developer specializing in audio applications at Institut de Recherche et Coordination Acoustique/Musique (IRCAM). IRCAM is a European institute covering science, sound and avant garde electro-acoustical art music.

    The demo uses XML to describe the various segments of a piece of music – Florence Baschet’s StreicherKreis (Circle of Strings). The music itself is a combination of stringed instruments and electronic effects. From the XML, SVG is generated for each section of the music. You can click on each section to listen to that part of the piece and a description is shown on how that particular section was created.

    As far as demos go, this is relatively simple. But it’s worth highlighting because it shows how easy it is to build a timeline around a piece of music and add descriptive information. In this case, it’s information meant to teach people how a particular effect was created. But it could be anything, from showing different camera angles of people playing the music to links about different covers of a popular piece. Opening up media to the web means that we can combine it with text, images and other media. This is just a small example.

  3. Firefox 3.5 is out

    Today we released Firefox 3.5, which as we said at the beginning of the 35 days project is a huge upgrade for both end users but also for the web.

    In the past we’ve always published a list of web developer features for a release. But the feature list for developers for 3.5 is so long that we thought it might be useful to try and break it down into easy-to-swallow bites. And my suspicion, given the number of comments and the number of daily views this weblog gets, is that it’s actually been useful to people.

    We’ve been writing articles on features to get people informed on what the changes are, but we’ve also been featuring demos to get people inspired. Some of them have been built by people at the Mozilla core, but the really great thing that we’ve seen is that people have started to show up and build demos for our project without us having to ask. I think that this points to the fact that people are really bullish on the future of the web. People want to see change, they want to see improvements and they understand that every individual has a role to play in that. To everyone involved, I say thank you. You’re helping to improve the web, one action at a time.

    We’re about half way through our 35 days posts and we will continue to make posts. And we’re still looking for help. If you want to get involved, you’re more than welcome to join us. There’s always something that you can do – follow our twitter account, write a demo, document a feature or, really, just start using this stuff. We’re helping to write the future of the web and everyone has a part to play.

  4. taming long words with word-wrap

    This post is from Les Orchard, who works on Mozilla’s web development team.

    Web browsers have a long history of sharing features between them. The word-wrap CSS property is a feature that originally came from Microsoft and is included in CSS3.

    Now available in Firefox 3.5, this CSS property allows the browser to arbitrarily break up long words or strings of characters to fit within a given element.

    How is this helpful? Well, have you ever had to display an extremely long URL or block of data on a page? Sure, URL shortening services have helped, but the basic layout issue still remained.

    Consider the following URL using the data scheme:

    Presented in a <textarea>, this huge URL behaves well enough to at least not break the layout of this page. But, it’s not really handled all that gracefully beyond that. Most browsers don’t quite know what to do with the scrollbar, styling is a pain, and presenting the URL in an editable field isn’t really the intent here.

    Alternatively, you could stuff the URL into a <div> and slap an overflow: hidden style on it, like so:

    Again, the page layout isn’t broken, but now the URL is cut off. So, why not try an overflow: auto style instead?

    This will give you a scrollbar, at least:

    data:text/html;charset=utf-8;base64,Q29uZ3JhdHVsYXRpb25zISBZb3UndmUgZm91bmQgdGhlIGhpZGRlbiBtZXNzYWdlIQ0KDQpUbyBjbGFpbSB5b3VyIHByaXplLCB2aXNpdCBodHRwOi8vZ2V0ZmlyZWZveC5jb20gdG9kYXkhDQoNCkZyZWUgYnJvd3NlciBpbiBldmVyeSBib3ghDQo%3D

    But now, visitors to your page have to scroll to see the whole
    thing, and highlighting the text for copy & paste can be
    cumbersome.

    So, finally, here’s the word-wrap: break-word payoff:

    data:text/html;charset=utf-8;base64,Q29uZ3JhdHVsYXRpb25zISBZb3UndmUgZm91bmQgdGhlIGhpZGRlbiBtZXNzYWdlIQ0KDQpUbyBjbGFpbSB5b3VyIHByaXplLCB2aXNpdCBodHRwOi8vZ2V0ZmlyZWZveC5jb20gdG9kYXkhDQoNCkZyZWUgYnJvd3NlciBpbiBldmVyeSBib3ghDQo%3D
    word-wrap:

    normal

    break-word

    See the difference for yourself: Use the radio buttons above to switch between the values normal (the default) and break-word. The normal value will cause the URL to spill out of the containing <div>, possibly breaking the layout of this page.

    On the other hand, using word-wrap: break-word will allow the browser to coerce the text into the confines of the <div>, thus preserving your page layout and quite possibly your sanity.

  5. the potential of web typography

    This post counts as both a demo and commentary about the changing nature of typography on the web. Ian Lynam and Craig Mod have put together a page that is an excellent example of typography in action, but also offer some suggestions on what the next steps for typography on the web might look like. The page itself takes advantage of a number of typefaces that Craig and Ian got permission to use and uses a pleasing multi-column layout. Please click through to the complete article to get the full effect.

  6. the script defer attribute

    This post is by Olivier Rochard. Olivier does research at Orange Labs in France.

    In HTML, the script element allows authors to include dynamic script in their documents. The defer attribute is boolean attribute that indicates how the script should be executed. If the defer attribute is present, then the script is executed when the page has finished parsing. The element is added to the end of the list of scripts that will execute when the document has finished parsing. Think about a FIFO processing queue : the first script element to be added to the queue will be the first script to be executed, then processing proceeds sequentially in the same order.

    There is one very good reason for using the defer attribute: performance. If you include a script element in your HTML page the script must be evaluated immediately while the page is being parsed. This means that objects have to be created, styles must be flushed, etc. This can make page loading slower. The defer attribute implies that the script has no side effects on the document as it’s being loaded and can safely be evaluated at the end of the page load.

    The defer attribute was first introduced in Internet Explorer 4, and added in the HTML 4 specification.

    A simple test.

    Here is a simple first test to see how the attribute works. The following lines are in the head element of a page:

    ‹script›
    	var test1 = "Test 1 : fail";
    ‹/script›
    ‹script defer›
      	console.log(test1);
    ‹/script›
    ‹script›
    	test1 = "Test 1 : pass";
    ‹/script›

    If the defer attribute for the script element is correctly implemented the browser will:

    1. Render the page.
    2. Execute the second script element after all the others.
    3. Display “Test 1 : pass” on the Firebug console.

    If the console displays “Test 1 : fail” it’s because the scripts are executed in the same order as in the source code.

    Note that the correct syntax for XHTML documents is:

    <script defer="defer"></script>

    A more advanced test

    This second test is a way to see how the feature works in a webpage with multiple script elements inserted:

    • Inline in the head and body elements
    • External via src attribute in head and body elements
    • With dynamic DOM insertion

    Here is partial source code of a webpage that tests how defer affects script loading and parsing order:

    ‹!doctype html›
    ‹html›
        ‹head›
            ‹title› Test 2 ‹/title›
            ‹script› var test2 = "Test 2 :\n\n"; ‹/script›
            ‹script› document.addEventListener("DOMContentLoaded",
                    function(){
                            test2 += "\tDOMContentLoaded\n";
                    }, false);
            ‹/script›
            ‹script defer› test2 += "\tInline HEAD deferred\n"; ‹/script›
            ‹script› test2 += "\tInline HEAD\n"; ‹/script›
            ‹script src="script1.js" defer›
                    // External HEAD deferred (script1.js) 
            ‹/script›
            ‹script src="script2.js"›
                    // External HEAD  (script2.js)
            ‹/script›
    	‹script›
                // Dynamic DOM insertion of a script (script3.js)
                head = document.getElementsByTagName('head')[0];
                script3 = document.createElement('script');
                script3.setAttribute('src', 'script3.js');
                head.appendChild(script3);
                // Dynamic DOM insertion of a deferred script (script4.js)
                script4 = document.createElement('script');
                script4.setAttribute('defer', 'defer');
                script4.setAttribute('src', 'script4.js');
                head.appendChild(script4);
    	‹/script›
    	‹script defer›
                // Deferred dynamic DOM insertion of a script (script5.js)
                head = document.getElementsByTagName('head')[0];
                script5 = document.createElement('script');
                script5.setAttribute('src', 'script5.js');
                head.appendChild(script5);
                // Deferred dynamic DOM insertion of a deferred script
                // (script6.js)
                script6 = document.createElement('script');
                script6.setAttribute('defer', 'defer');
                script6.setAttribute('src', 'script6.js');
                head.appendChild(script6);
    	‹/script›
        ‹/head›
        ‹body onload="test2 += '\tBody onLoad\n';"›
            ‹script defer› test2 += "\tInline BODY deferred\n"; ‹/script›
            ‹script› test2 += "\tInline BODY\n"; ‹/script›
     
    	... other body content ...
     
    		<a onclick="alert(test2);">Launch test 2</a>
     
    	... other body content ...
     
            ‹script src="script7.js" defer›
                    // External BODY deferred (script7.js)
            ‹/script›
            ‹script src="script8.js"›
                    // External BODY (script8.js)
            ‹/script›
        ‹/body›
    ‹/html›

    When you click on the “Launch test 2″ link in the document a pop-up appears with a list in it. This list shows the order of script elements loaded during the session.

    The test also displays the DOMContentLoaded and body.onload events when they are fired.

    If the defer attribute is correctly implemented in the browser, all the deferred lines should be near the bottom of the list.

    Results of the second test for each browser are below (deferred scripts are in green color) :

    • The defer attribute behavior in the Firefox 3.5 browser is correct:

      1. Inline HEAD
      2. External HEAD (script2.js)
      3. Dynamic DOM insertion of a script (script3.js)
      4. Inline BODY
      5. External BODY (script8.js)
      6. Inline HEAD deferred
      7. External HEAD deferred (script1.js)
      8. Dynamic DOM insertion of a deferred script (script4.js)
      9. Inline BODY deferred
      10. External BODY deferred (script7.js)
      11. Deferred dynamic DOM insertion of a script (script5.js)
      12. Deferred dynamic DOM insertion of a deferred script (script6.js)
      13. DOMContentLoaded
      14. Body onLoad
    • The defer attribute behavior in the IE 8 browser is erratic: the order is different at each reload :

      1. Inline HEAD
      2. External HEAD (script2.js)
      3. Inline BODY
      4. External BODY (script8.js)
      5. Dynamic DOM insertion of a script (script3.js)
      6. Dynamic DOM insertion of a deferred script (script4.js)
      7. Inline HEAD deferred
      8. External HEAD deferred (script1.js)
      9. Inline BODY deferred
      10. External BODY deferred (script7.js)
      11. Body onLoad
      12. Deferred dynamic DOM insertion of a script (script5.js)
      13. Deferred dynamic DOM insertion of a deferred script (script6.js)
    • The defer attribute behavior in a WebKit browser (Safari 4.0) is erratic : the order is different at each reload :

      1. Inline HEAD deferred
      2. Inline HEAD
      3. External HEAD deferred (script1.js)
      4. External HEAD (script2.js)
      5. Inline BODY deferred
      6. Inline BODY
      7. External BODY deferred (script7.js)
      8. Deferred dynamic DOM insertion of a script (script5.js)
      9. Dynamic DOM insertion of a deferred script (script4.js)
      10. Deferred dynamic DOM insertion of a deferred script (script6.js)
      11. Dynamic DOM insertion of a script (script3.js)
      12. External BODY (script8.js)
      13. DOMContentLoaded
      14. Body onLoad
    • The defer attribute behavior in the Opera 10.00 Beta browser:

      1. Inline HEAD deferred
      2. Inline HEAD
      3. External HEAD deferred (script1.js)
      4. External HEAD (script2.js)
      5. Dynamic DOM insertion of a script (script3.js)
      6. Dynamic DOM insertion of a deferred script (script4.js)
      7. Deferred dynamic DOM insertion of a script (script5.js)
      8. Deferred dynamic DOM insertion of a deferred script (script6.js)
      9. Inline BODY deferred
      10. Inline BODY
      11. External BODY deferred (script7.js)
      12. External BODY (script8.js)
      13. DOMContentLoaded
      14. Body onLoad

    We hope that this has been a useful introduction to how the defer attribute works in Firefox 3.5. The tests above will also help you predict behavior in other browsers as well.

    Resources

  7. creating pop art with html5 video

    This post is by Felipe Gomez, a long-time Mozilla contributor and really awesome dude. Felipe attends school in Brazil.

    This demo contains another interesting effect that can be done with the HTML5 elements present in Firefox 3.5. What better way to create a cool effect than mixing the open web with pop art? This demo uses only JavaScript, <video> and <canvas>. We’ll use them to create an effect similar to the famous Andy Warhol style art on a live video.

    The effect is quite simple. What we want to do is to create a stamp effect based on the brightness of the image. We calculate the brightness of each pixel and separate them into 3 groups, from darkest to brightest. Them, for each of our four frames we use a different color palette to convert the original pixels into our desired colors for the best effect.

    With that, we already have a cool effect, but it lacks a bit of detail:

    So we mix our colors with 30% of the original image, and now we have the final version, with more shades of color while preserving the nice colorization in Andy Warhol style.

    We can access the pixels of each frame of the video using <video> and <canvas>, creating a live effect while the video plays.

  8. saving data with localStorage

    This post was written by Jeff Balogh. Jeff works on Mozilla’s web development team.

    New in Firefox 3.5, localStorage is a part of the Web Storage specification. localStorage provides a simple Javascript API for persisting key-value pairs in the browser. It shouldn’t be confused with the SQL database storage proposal, which is a separate (and more contentious) part of the Web Storage spec. Key-value pairs could conceivably be stored in cookies, but you wouldn’t want to do that. Cookies are sent to the server with every request, presenting performance issues with large data sets and the potential for security problems, and you have to write your own interface for treating cookies like a database.

    Here’s a small demo that stores the content of a textarea in localStorage. You can change the text, open a new tab, and find your updated content. Or you can restart the browser and your text will still be there.


    The easiest way to use localStorage is to treat it like a regular object:

    >>> localStorage.foo = 'bar'
    >>> localStorage.foo
    "bar"
    >>> localStorage.length
    1
    >>> localStorage[0]
    "foo"
    >>> localStorage['foo']
    "bar"
    >>> delete localStorage['foo']
    >>> localStorage.length
    0
    >>> localStorage.not_set
    null

    There’s also a more wordy API for people who like that sort of thing:

    >>> localStorage.clear()
    >>> localStorage.setItem('foo', 'bar')
    >>> localStorage.getItem('foo')
    "bar"
    >>> localStorage.key(0)
    "foo"
    >>> localStorage.removeItem('foo')
    >>> localStorage.length
    0

    If you want to have a localStorage database mapped to the current session, you can use sessionStorage. It has the same interface as localStorage, but the lifetime of sessionStorage is limited to the current browser window. You can follow links around the site in the same window and sessionStorage will be maintained (going to different sites is fine too), but once that window is closed the database will be deleted. localStorage is for long-term storage, as the w3c spec instructs browsers to consider the data “potentially user-critical”.

    I was a tad disappointed when I found out that localStorage only supports storing strings, since I was hoping for something more structured. But with native JSON support it’s easy to create an object store on top of localStorage:

    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }
     
    Storage.prototype.getObject = function(key) {
        return JSON.parse(this.getItem(key));
    }

    localStorage databases are scoped to an HTML5 origin, basically the tuple (scheme, host, port). This means that the database is shared across all pages on the same domain, even concurrently by multiple browser tabs. However, a page connecting over http:// cannot see a database that was created during an https:// session.

    localStorage and sessionStorage are supported by Firefox 3.5, Safari 4.0, and IE8. You can find more compatibility details on quirksmode.org, including more detail on the storage event.

  9. new CSS3 properties in Firefox 3.5 – nth-*

    Firefox 3.5 supports several new CSS3 selectors. In this post we’ll talk about four of them: :nth-child, :nth-last-child, :nth-of-type and :nth-last-of-type.

    Each of these is called a Pseudo-class and can be used to apply styles to existing selectors. The best way to describe how this works is with some examples.

    :nth-child

    This pseudo-class lets you apply styles to groups of elements. The most common use case is to highlight odd or even items in a table:

    tr:nth-child(even)
    {
        background-color: #E8E8E8;
    }

    A live example (works in Firefox 3.5):

    Row 1
    Row 2
    Row 3
    Row 4

    But you can also use it to apply styles to groups of more than two using a special notation. The documentation for this rule is pretty obtuse but basically the “3″ in the example splits the number of elements into groups of three and the “+1″ is the offset in that group. There are more examples in the spec as well.

    tr:nth-child(3n+1) {  background-color: red; }
    tr:nth-child(3n+2) {  background-color: green; }
    tr:nth-child(3n+3) {  background-color: blue; }

    A live example (works in Firefox 3.5):

    Row 1
    Row 2
    Row 3
    Row 4
    Row 5
    Row 6

    :nth-last-child

    The :nth-last-child pseudo-class works exactly like the :nth-child pseudo-class except that it counts elements in the opposite direction:

    tr:nth-last-child(3n+3) {  background-color: red; }
    tr:nth-last-child(3n+2) {  background-color: green; }
    tr:nth-last-child(3n+1) {  background-color: blue; }

    Example (works in Firefox 3.5):

    Row 1
    Row 2
    Row 3
    Row 4
    Row 5
    Row 6

    :nth-of-type

    The :nth-of-type pseudo-class uses the same kind of syntax as the other elements here but allows you to select based on element type.

    div:nth-of-type(odd) { border-color: red }
    div:nth-of-type(even) { border-color: blue }

    Example (works in Firefox 3.5):

    I should be red!
    I should be blue!

    :nth-last-of-type

    Much like :nth-last-child, :nth-last-of-type is the same as :nth-of-type except that it counts in the opposite direction.

    These four properties allow you to do interesting things with style and element groups and we hope that they make it easier to style your pages.