1. Making the wait for the holidays easier – the MDN advent calendar

    Tomorrow we will release the MDN advent calendar at http://thewebrocks.com/calendar with a daily link on a web technology product, a MDN wiki page or a great demo collected by us over the last few days. You can get a preview of how the calendar will look and work here:

    As an extra bonus, we thought it would be fun to document the step-by-step development of the calendar and release it for you to re-use or get inspired by.

    You can get a white-labeled version of the calendar on GitHub and there is a two-part step-by-step instruction how it was built available: Part 1Part 2.

    It is an example of how to build something server-side (so you can’t cheat by setting your operating system calendar ahead), enhance it with JavaScript and make it smooth by using CSS transitions. This should work for everybody and by playing each technology to its strengths, the code is very small indeed.

    Enjoy, and see you tomorrow and the day after, and the day after that and…

  2. Congrats to our October Dev Derby winners!

    Responsive design is more important than ever as people experience the Web on a variety of devices. Web developers can now take advantage of CSS Media Queries to build sites and applications that can be viewed on different screen sizes. So we decided to focus on that for the October Dev Derby.

    For this challenge, developers submitted 15 demos to show what you can do with CSS Media Queries. Check them out so see how they present unique styles and layouts in response to changes in viewing area.

    It was a fairly close race, so join us in congratulating the winners circle:
    October Dev Derby winners - CSS Media Queries

    1st Place: CSS3 Cherry Blossom – Media queries by elufo
    2nd Place: Santa’s Media Queries by tuxie
    3rd Place: Too many fish is the sea by michal.b

    Runners-up:
    Responsive 3D-Models For Any Device
    Spriting with CSS Media Queries

    Thanks to everyone that participated in the October Dev Derby! Only a couple of days left to participate in the November Dev Derby, so get your Canvas demos in now. Otherwise, start experimenting with IndexedDB for December.

    NOTE: We recently updated our Dev Derby rules to allow developers to participate in multiple contests until they win 1st place. That means if you’ve submitted awesome demos and come up short in the past, you still have a chance to win that top spot in future Dev Derbies… so keep those demos coming!

  3. People of HTML5: Joe Lambert unshredding images in Canvas

    Joe LambertToday we have a quickie for you: Joe Lambert, a web developer from Southampton, England working for Rareloop took on the Instagram engineering challenge of un-shredding a shredded image but instead of using server-side code, he used HTML5 canvas. Here’s a screencast of his solution to the problem:

    And here we are in a quick interview, chatting about how he approached the problem and why he used web technologies:

    1) The specs of the competition said you can use Python, Ruby or C++ and you went instead for JavaScript and Canvas. Why?

    JavaScript is my language of choice and what I use most of the time. I also find it the most fun as its easy to post your creations online and show people immediately, no downloads or dependencies to worry about. I wasn’t really looking to get hired by Instagram so adhering strictly to the rules wasn’t a big deal. Essentially it was an appealing problem that I thought could be solved in a browser, so wanted to prove that was the case.

    I actually knew from the start that creating the algorithm to unshred the image was only half of what I wanted to do. That in itself was going to be a challenge and quite satisfying to solve but I really wanted to get to a point where I could make the slices move into the right place. I wouldn’t have been able to create this effect as quickly in any other environment.

    2) How did you approach the problem of unshredding the images? Did you do similar things before? What is the logic you use?

    I wasn’t too worried about the most efficient algorithm so I just started by thinking about how a human might solve this type of problem. I’ve played around with image data a little before but nothing that would have been directly useful to this particular problem.

    If I were solving this in the physical world I’d start by picking up a slice at random then pick up each other shredded slice and see if it looked like it fitted to the left or right of the piece in my hand. I’d then repeat this till the image was back to its original state.

    This gave an indication of the kind of structure my code should have, I just needed to work out how to computationally measure whether two strips ought to be next to one another. For this I just compared the pixels closest to each edge and measured the euclidean distance between the colour values. It seemed to work pretty well!

    3) I see you are not using typed arrays in your solution yet. It seems to perform well the way it is now, do you think they’d make a difference?

    I’m not sure, efficiency wasn’t high on my priorities for this challenge so I didn’t really look to optimise it but as you mention it seems to perform quite well. I haven’t tried the algorithm with larger images but I suspect it would perform not so well.

    4) What was the feedback so far? Has Instagram contacted you?

    The feedback has been really positive, especially via Twitter. I think generally the competition has had quite a high profile which certainly helped.

    Instagram haven’t been in contact yet but it would be good to hear from them. I suspect they’re focusing on all the people who used the recommended languages

    5) Seeing how easy this was can you see other challenges with images and canvas? Could you think of ways how to make it easier for developers, for example by extending the API?

    The way you access pixel data in Canvas is a little complicated, it might be useful to have some helper functions to let you get access to a single pixel via X/Y coordinates. I ended up writing a little helper function to do this for this challenge, I’m going to try get the code up on GitHub shortly so this might be of use for others.

    It would also have been useful to have been able to call toDataURL() on a CanvasPixelArray object. My implementation used the DOM and CSS3 transitions to move the images into their correct places after the algorithm had solved the order, being able to access a Data URI for each slice would have be handy.

    If you want to chat with Joe, he is available on Twitter as @joelambert.

  4. Firefox – tons of tools for web developers!

    One of the goals of Firefox have always been to make the lives of web developers as easy and productive as possible, by providing tools and a very extensible web browser to enable people to create amazing things. The idea here is to list a lot of the tools and options available to you as web developers using Firefox.

    Continued…

  5. Luke Crouch on: HTML5 – code for all the platforms

    Back in October, Luke Crouch, one of the web developers working on the Mozilla Developer Network went to Techfest in Tulsa, Oklahoma to tell people all about HTML5. You can see his slides with his voiceover at Usergroup.tv:

    Luke Crouch: Code for all the platforms

    Luke gave an overview on the history of HTML5 vs. XHTML and the approaches of the W3C and the WHATWG. He explains how standards are produced and how this can be daunting. He then shows how “shipping code wins” and showcases lots of examples of new technology in action.

    He concludes with a nice comparison on how much simpler it is to build rich form interfaces with HTML5 and polyfills than with native code for various platforms.

    All in all a presentation very worth while from someone who is in the trenches and who is not afraid to use new technology and wait for the market to catch up.

  6. State of the docs, November 23, 2011

    This is the second in a series of posts about new or recently improved content or infrastructure on MDN. This post was slightly delayed by the U.S. Thanksgiving holiday (apologies).

    Web standards docs

    New pages!

    As the result of a discussion on the mozilla.dev.platform forum, Boris Zbarsky wrote an article on Writing forward-compatible websites, with contributions by Henri Sivonen and others. Discussion of and improvements to this article are ongoing.

    Jeremie Patonnier created pages for several SVG DOM interfaces:

    Masayuki created pages for DOM CompositionEvent and various specific composition events.

    David Bruant created a page for event.stopImmediatePropagation and wrote an article on Historical artifacts to avoid.

    Help wanted!

    It would be helpful to have an article about the Web standardization process, what the different spec draft levels are, and how web developers can decide when a new technology is stable enough to use and deploy. It could go under Web standards, which currently has some dated articles from the early days of Firefox.

    Other doc updates

    David Bruant expanded and added examples to DOM NodeList and the Javascript var statement.

    Our friends at Google were busy, holding their own mini-docsprint:

    Mozilla project docs

    The Mozilla coding style guidelines were updated by Jeff Walden, Benjamin Smedberg, and others.

    MND infrastructure

    Version 1.6 of MDN was launched. Luke Crouch blogged about the changes in 1.6.

    Eric Shepherd created new templates to guide readers who visit non-existant pages by following auto-generated links. This should alleviate the problem of non-logged-in readers being bounced to the front page in such cases. If you’re curious about the details, see his blog.

  7. HTML5 context menus in Firefox (Screencast and Code)

    You may not know it, but the HTML5 specifications go beyond what we put in the pages and also define how parts of the browser should become available to developers with HTML, CSS and JavaScript. One of these parts of the specs are context menus, or “right click menus”. Using HTML5 and a menu element you can add new options to these without having to write a browser add-on. In Firefox 8 (the current one) we have support for those. See the following screencast for a context menu demo.

    The image example is pretty simple and was actually written by Paul Rouget as a demo in the original Firefox bug request. The main core is the HTML of it:

    <section id="noninteractive" contextmenu="imagemenu">
     
      <img src="html5.png" alt="HTML5" id="menudemo">
     
        <menu type="context" id="imagemenu">
          <menuitem label="rotate" onclick="rotate()"
                    icon="arrow_rotate_clockwise.png">
          </menuitem>
          <menuitem label="resize" onclick="resize()"
                    icon="image-resize.png">
          </menuitem>
          <menu label="share">
            <menuitem label="twitter" onclick="alert('not yet')"></menuitem>
            <menuitem label="facebook" onclick="alert('not yet')"></menuitem>
          </menu>
        </menu>
     
    </section>

    As you can see you link the menu element to an element via its ID. The contextmenu attribute then points to this one. Each menu can have several menuitems. Each of those gets a textual label and a possible icon. You can also nest menu elements to create multiple layer menus. Here, we add inline onclick handlers to point to different JavaScript functions to call when the menu item gets activated. The resulting context menu looks like this:

    image with a context menu

    The functionality is simple, all the rotate() and resize() functions do is add class names to the image using querySelector and classList:

    function rotate() {
      document.querySelector('#menudemo').classList.toggle('rotate'); 
    }
    function resize() {   
      document.querySelector('#menudemo').classList.toggle('resize'); 
    }

    The real effect is in CSS transforms and transitions. As the image has an ID of menudemo here is what is needed in CSS to rotate and resize:

    #menudemo { 
      -moz-transition: 0.2s; 
      width:200px;
    }
    #menudemo.rotate { 
      -moz-transform: rotate(90deg); 
    }
    #menudemo.resize { 
      -moz-transform: scale(0.7); 
    }
    #menudemo.resize.rotate { 
      -moz-transform: scale(0.7) rotate(90deg); 
    }

    Notice that in a real product we should of course add the other browser prefixes and go prefix-less but as the functionality now only works in Firefox, this is enough for this demo.

    Detecting support and visual hinting

    Now, as this is extending the normal user offerings in the browser we need to make it obvious that there is a right-click menu available. In CSS3, there is a context-menu cursor available to us. When context menus are available, this should be shown:

    .contextmenu #menudemo, .contextmenu .demo {
      cursor: context-menu;
    }

    We test the browser for support by checking for contextmenu on the body element and for HTMLMenuItemElement in the window (this has been added as a pull request to Modernizr, too).

    if ('contextMenu' in document.body && 'HTMLMenuItemElement' in window) {
      document.documentElement.classList.add('contextmenu');
    } else {
      return;
    }

    Wouldn’t HTMLMenuItemElement be enough? Yes, but a real context menu should only offer functionality when it is sensible, and that is where contextMenu comes in.

    Turning menuitems on and off depending on functionality

    As a slightly more complex example, let’s add a “count words” functionality to the document. For this, we generate a counter element that will become a tooltip when the words were counted:

    var counter = document.createElement('span');
    counter.id = 'counter';
    counter.className = 'hide';
    document.body.appendChild(counter);
     
    counter.addEventListener('click', function(ev){
      this.className = 'hide';
    },false);

    This one is hidden by default and becomes visible when the hide class is removed. To make it smooth, we use a transition:

    #counter{
      position: absolute;
      background: rgba(0,0,0,0.7);
      padding:.5em 1em;
      color: #fff;
      font-weight:bold;
      border-radius: 5px;
      -moz-transition: opacity 0.4s;
    }
    #counter.hide{
      opacity: 0;
    }

    We start with two sections with context menus:

    <section id="noninteractive" contextmenu="countmenu">
      <menu type="context" id="countmenu">
          <menuitem class="wordcount" label="count words"></menuitem>
      </menu>
    </section>
     
    <section id="interactive" contextmenu="countmenuinteractive">
      <menu type="context" id="countmenuinteractive">
          <menuitem class="wordcount" label="count words"></menuitem>
      </menu>
    </section>

    We then loop through all the menuitems with the class wordcount and apply the functionality.

    var wordcountmenus = document.querySelectorAll('.wordcount'),
        i = wordcountmenus.length;
     
    while (i--) {
      wordcountmenus[i].addEventListener('click', function(ev){
        // add functionality 
      }, false);
    }

    We need to find out what has been selected in the page. We do this by using getSelection() and splitting its string version at whitespace. We then show the counter by removing the hide class name.

    var wordcountmenus = document.querySelectorAll('.wordcount'),
        i = wordcountmenus.length;
     
    while (i--) {
      wordcountmenus[i].addEventListener('click', function(ev){
        var text = document.getSelection(),
            count = text.toString().split(/\s/).length;
        counter.innerHTML = count + ' words';
        counter.className = '';
      }, false);
    }

    You can see this in action in the second context menu demo. Now, the issue with this (as explained in the screencast) is that it always counts the words, regardless of the user having selected some text. What we want is the menu only to be active when there is text selected.

    context menu item available or not available depending on selection

    So in order to make our menu only become available when it makes sense we check if there is a selection in the document. Every context menu fires an event called contextmenu when it opens. So all we need to do is to subscribe to this event.

    When something is selected in the document document.getSelection().isCollapsed is true. Otherwise it is false, so all we need to do is to enable or disable the menu item accordingly:

    document.querySelector('#interactive').addEventListener(
      'contextmenu', function(ev) {
        this.querySelector('.wordcount').disabled =
        document.getSelection().isCollapsed;  
      },
    false);

    The last thing to solve is the position of the mouse to position the counter element. As the menu selection event doesn’t give us the mouse position we need to add a contextmenu handler to the whole document that positions the counter invisibly behind the menu when it is opened:

    document.body.addEventListener(
      'contextmenu', function(ev) {
        counter.style.left = ev.pageX + 'px';
        counter.style.top = ev.pageY + 'px';
        counter.className = 'hide';
      }, 
    false);

    Further reading and resources

  8. Webinar: IndexedDB with Jonas Sicking

    Update 2011-12-20: The video recording of this webinar is now available:

    IndexedDB is the emerging standard for structured client-side data storage. The IndexedDB standard is supported by current versions of Firefox and Chrome, and support for it is expected in Internet Explorer 10.

    With this growing maturity and support, it’s time to start experimenting with what IndexedDB can do for Web applications. Working with IndexedDB requires a shift in mindset for many Web developers, as it is more similar to “NoSQL” systems like CouchDB or MongoDB than to traditional relational databases.

    IndexedDB will be the theme for December’s MDN DevDerby. And to kick off the theme for the month, on December 1st, we’re offering an MDN Webinar on IndexedDB with Jonas Sicking, one of the editors of the IndexedDB draft standard and one of the implementors of IndexedDB in Gecko.

    When
    December 1st, at 9:00 a.m. US Pacific Time (17:00 UTC). Add this event to your Google calendar:
    Where
    Air Mozilla, with text chat on #airmozilla on irc.mozilla.org. (There’s an IRC widget on the Air Mozilla page if you need it.)

    We’ll record this session for those who can’t attend (or can’t use Flash, which is currently used by Air Mozilla for live streaming video).

    We’d like to get a rough estimate of how many people will be attending. If you happen to use Plancast, and you plan to attend the seminar, please join the event on Plancast.