Mozilla

Web Developers Articles

Sort by:

View:

  1. Mozilla’s Boot to Gecko – The Web is the Platform

    Mozilla’s Boot to Gecko (B2G) is about building a complete, standalone operating system for the open web. It aims at making web technologies the number one choice for applications on desktop and mobile, and we believe it can displace proprietary, single-vendor stacks for application development. And we have made some exciting progress that we want to share with you!

    Continued…

  2. 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…

  3. getUserMedia is ready to roll!

    We blogged about some of our WebRTC efforts back in April. Today we have an exciting update for you on that front: getUserMedia has landed on mozilla-central! This means you will be able to use the API on the latest Nightly versions of Firefox, and it will eventually make its way to a release build.

    getUserMedia is a DOM API that allows web pages to obtain video and audio input, for instance, from a webcam or microphone. We hope this will open the possibility of building a whole new class of web pages and applications. This DOM API is one component of the WebRTC project, which also includes APIs for peer-to-peer communication channels that will enable exchange of video steams, audio streams and arbitrary data.

    We’re still working on the PeerConnection API, but getUserMedia is a great first step in the progression towards full WebRTC support in Firefox! We’ve certainly come a long way since the first image from a webcam appeared on a web page via a DOM API. (Not to mention audio recording support in Jetpack before that.)

    We’ve implemented a prefixed version of the “Media Capture and Streams” standard being developed at the W3C. Not all portions of the specification have been implemented yet; most notably, we do not support the Constraints API (which allows the caller to request certain types of audio and video based on various parameters).

    We have also implemented a Mozilla specific extension to the API: the first argument to mozGetUserMedia is a dictionary that will also accept the property {picture: true} in addition to {video: true} or {audio: true}. The picture API is an experiment to see if there is interest in a dedicated mechanism to obtain a single picture from the user’s camera, without having to set up a video stream. This could be useful in a profile picture upload page, or a photo sharing application, for example.

    Without further ado, let’s start with a simple example! Make sure to create a pref named “media.navigator.enabled” and set it to true via about:config first. We’ve put the pref in place because we haven’t implemented a permissions model or any UI for prompting the user to authorize access to the camera or microphone. This release of the API is aimed at developers, and we’ll enable the pref by default after we have a permission model and UI that we’re happy with.

    There’s also a demo page where you can test the audio, video and picture capabilities of the API. Give it a whirl, and let us know what you think! We’re especially interested in feedback from the web developer community about the API and whether it will meet your use cases. You can leave comments on this post, or on the dev-media mailing list or newsgroup.

    We encourage you to get involved with the project – there’s a lot of information about our ongoing efforts on the project wiki page. Posting on the mailing list with your questions, comments and suggestions is great way to get started. We also hang out on the #media IRC channel, feel free to drop in for an informal chat.

    Happy hacking!

  4. CSS 3D transformations in Firefox Nightly

    When the first 3D transformations in CSS got support on Webkit browsers people got incredibly excited about them. Now that they have matured we also support 3D CSS in Firefox. To see it for yourself, check out one of the latest nightly builds.

    You can see them in action in this demo of a rotating HTML5 logo and the screencast below:

    This means now that we need your support in trying out CSS 3D examples in Firefox and add other extensions than -webkit- to your CSS 3D products and demos. To show that this is possible, we took the well-known webkit-only “poster circle” demo and made it work with Firefox nightly by adding the -moz- (and of course the other prefixes and one set of instructions without browser prefixes). Here is a slight excerpt:

    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    -o-transform-style: preserve-3d;
    -ms-transform-style: preserve-3d;
    transform-style: preserve-3d;

    You can see this in action in the screencast below alongside Chrome and you try the demo out yourself. The slight jerkiness is actually my MacBook Air impersonating a starting jet every time I use ScreenFlow and not the browser.

    To celebrate the release and to show how CSS 3D can be applied as subtle effect, have a game of pairs using your favourite browsers (and a cat) :

    browser pairs

    Oleg Romashin also spent some time to convert a few CSS 3D demos to work with Mozilla and you can check the 3D city for more “wow”.

    If you are new to CSS 3D transformations here’s a good beginner course and a tool to create them.

    The rotating HTML5 logo demo also shows how you can check if the currently used browser supports 3D transforms. Instead of repeating the animation frames for all the prefixes we test in JavaScript and create the CSS on the fly:

    function checksupport() {
      var props = ['perspectiveProperty', 'WebkitPerspective',
                   'MozPerspective', 'OPerspective', 'msPerspective'],
          i = 0,
          support = false;
      while (props[i]) {
        if (props[i] in form.style) {
          support = true;
          pfx = props[i].replace('Perspective','');
          pfx = pfx.toLowerCase();
          break;
        }
        i++;
      } 
      return support;
    }
    if (checksupport()) {
      var s = '';
      styles = document.createElement('style');
      s += '#stage{-'+ pfx +'-perspective: 300px;}'+
           '#logo{-'+ pfx +'-transform-style: preserve-3d;position:relative;}'+  
           '#logo.spin{-'+ pfx +'-animation: spin 3s infinite linear;}'+
           '@-'+ pfx +'-keyframes spin {'+  
           '0% {'+ 
           '-'+ pfx +'-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg);'+   
           '}'+
           '100% {'+   
           '-'+ pfx +'-transform: rotateX(0deg) rotateY(360deg)'+
           ' rotateZ(360deg);'+ 
           '}}';
      styles.innerHTML = s;
      document.querySelector('head').appendChild(styles);
    }

    For more information on creating your own pages that use 3D transformations, take a look at the draft specification

    As always, If you find any bugs, please report them at bugzilla.mozilla.org!

    So please reward our hard work bringing the third dimension to Firefox’s CSS engine by supporting and testing. Cheers!

  5. Old tricks for new browsers – a talk at jQuery UK 2012

    Last Friday around 300 developers went to Oxford, England to attend jQuery UK and learn about all that is hot and new about their favourite JavaScript library. Imagine their surprise when I went on stage to tell them that a lot of what jQuery is used for these days doesn’t need it. If you want to learn more about the talk itself, there is a detailed report, slides and the audio recording available.

    The point I was making is that libraries like jQuery were first and foremost there to give us a level playing field as developers. We should not have to know the quirks of every browser and this is where using a library allows us to concentrate on the task at hand and not on how it will fail in 10 year old browsers.

    jQuery’s revolutionary new way of looking at web design was based on two main things: accessing the document via CSS selectors rather than the unwieldy DOM methods and chaining of JavaScript commands. jQuery then continued to make event handling and Ajax interactions easier and implemented the Easing equations to allow for slick and beautiful animations.

    However, this simplicity came with a prize: developers seem to forget a few very simple techniques that allow you to write very terse and simple to understand JavaScripts that don’t rely on jQuery. Amongst others, the most powerful ones are event delegation and assigning classes to parent elements and leave the main work to CSS.

    Event delegation

    Event Delegation means that instead of applying an event handler to each of the child elements in an element, you assign one handler to the parent element and let the browser do the rest for you. Events bubble up the DOM of a document and happen on the element you want to get and each of its parent elements. That way all you have to do is to compare with the target of the event to get the one you want to access. Say you have a to-do list in your document. All the HTML you need is:

    <ul id="todo">
      <li>Go round Mum's</li>
      <li>Get Liz back</li>
      <li>Sort life out!</li>
    </ul>

    In order to add event handlers to these list items, in jQuery beginners are tempted to do a $('#todo li').click(function(ev){...}); or – even worse – add a class to each list item and then access these. If you use event delegation all you need in JavaScript is:

    document.querySelector('#todo').addEventListener( 'click', 
      function( ev ) {
        var t = ev.target;
        if ( t.tagName === 'LI' ) {
          alert( t + t.innerHTML ); 
          ev.preventDefault();
        }
    }, false);

    Newer browsers have a querySelector and querySelectorAll method (see support here) that gives you access to DOM elements via CSS selectors – something we learned from jQuery. We use this here to access the to-do list. Then we apply an event listener for click to the list.

    We read out which element has been clicked with ev.target and compare its tagName to LI (this property is always uppercase). This means we will never execute the rest of the code when the user for example clicks on the list itself. We call preventDefault() to tell the browser not to do anything – we now take over.

    You can try this out in this fiddle or embedded below:

    JSFiddle demo.

    The benefits of event delegation is that you can now add new items without having to ever re-assign handlers. As the main click handler is on the list new items automatically will be added to the functionality. Try it out in this fiddle or embedded below:

    JSFiddle demo.

    Leaving styling and DOM traversal to CSS

    Another big use case of jQuery is to access a lot of elements at once and change their styling by manipulating their styles collection with the jQuery css() method. This is seemingly handy but is also annoying as you put styling information in your JavaScript. What if there is a rebranding later on? Where do people find the colours to change? It is a much simpler to add a class to the element in question and leave the rest to CSS. If you think about it, a lot of times we repeat the same CSS selectors in jQuery and the style document. Seems redundant.

    Adding and removing classes in the past was a bit of a nightmare. The way to do it was using the className property of a DOM element which contained a string. It was then up to you to find if a certain class name is in that string and to remove and add classes by adding to or using replace() on the string. Again, browsers learned from jQuery and now have a classList object (support here) that allows easy manipulation of CSS classes applied to elements. You have add(), remove(), toggle() and contains() to play with.

    This makes it dead easy to style a lot of elements and to single them out for different styling. Let’s say for example we have a content area and want to show one at a time. It is tempting to loop over the elements and do a lot of comparison, but all we really need is to assign classes and leave the rest to CSS. Say our content is a navigation pointing to articles. This works in all browsers:

    <header>
      <h1>Profit plans</h1>
    </header>
    <section id="content">
      <nav id="nav">
        <ul>
          <li><a href="#step1">Step 1: Collect Underpants</a></li>
          <li><a href="#step2">Step 2: ???</a></li>
          <li><a href="#step3">Step 3: Profit!</a></li>
        </ul>
      </nav>
      <article id="step1">
        <header><h1>Step 1: Collect Underpants</h1></header>
        <section>
          <p>
            Make sure Tweek doesn't expect anything, then steal underwear 
            and bring it to the mine.
          </p>
        </section>
        <footer><a href="#nav">back to top</a></footer>
      </article>
      <article id="step2">
        <header><h1>Step 2: ???</h1></header>
        <section>
          <p>WIP</p>
        </section>
        <footer><a href="#nav">back to top</a></footer>
      </article>
      <article id="step3">
        <header><h1>Step 3: Profit</h1></header>
        <section>
          <p>Yes, profit will come. Let's sing the underpants gnome song.</p>
        </section>
        <footer><a href="#nav">back to top</a></footer>
      </article>
    </section>

    Now in order to hide all the articles, all we do is assign a ‘js’ class to the body of the document and store the first link and first article in the content section in variables. We assign a class called ‘current’ to each of those.

    /* grab all the elements we need */
    var nav = document.querySelector( '#nav' ),
        content = document.querySelector( '#content' ),
     
    /* grab the first article and the first link */
        article = document.querySelector( '#content article' ),
        link = document.querySelector( '#nav a' );
     
    /* hide everything by applying a class called 'js' to the body */
    document.body.classList.add( 'js' );
     
    /* show the current article and link */ 
    article.classList.add( 'current' );
    link.classList.add( 'current' );

    Together with a simple CSS, this hides them all off screen:

    /* change content to be a content panel */
    .js #content {
      position: relative;
      overflow: hidden;
      min-height: 300px;
    }
     
    /* push all the articles up */
    .js #content article {
      position: absolute;
      top: -700px;
      left: 250px;
    }
    /* hide 'back to top' links */
    .js article footer {
      position: absolute;
      left: -20000px;
    }

    In this case we move the articles up. We also hide the “back to top” links as they are redundant when we hide and show the articles. To show and hide the articles all we need to do is assign a class called “current” to the one we want to show that overrides the original styling. In this case we move the article down again.

    /* keep the current article visible */
    .js #content article.current {
      top: 0;
    }

    In order to achieve that all we need to do is a simple event delegation on the navigation:

    /* event delegation for the navigation */
    nav.addEventListener( 'click', function( ev ) {
      var t = ev.target;
      if ( t.tagName === 'A' ) {
        /* remove old styles */
        link.classList.remove( 'current' );
        article.classList.remove( 'current' );
        /* get the new active link and article */
        link = t;
        article = document.querySelector( link.getAttribute( 'href' ) );
        /* show them by assigning the current class */
        link.classList.add( 'current' );
        article.classList.add( 'current' );
      }
    }, false);

    The simplicity here lies in the fact that the links already point to the elements with this IDs on them. So all we need to do is to read the href attribute of the link that was clicked.

    See the final result in this fiddle or embedded below.

    JSFiddle demo.

    Keeping the visuals in the CSS

    Mixed with CSS transitions or animations (support here), this can be made much smoother in a very simple way:

    .js #content article {
      position: absolute;
      top: -300px;
      left: 250px;
      -moz-transition: 1s;
      -webkit-transition: 1s;
      -ms-transition: 1s;
      -o-transition: 1s;
      transition: 1s;
    }

    The transition now simply goes smoothly in one second from the state without the ‘current’ class to the one with it. In our case, moving the article down. You can add more properties by editing the CSS – no need for more JavaScript. See the result in this fiddle or embedded below:

    JSFiddle demo.

    As we also toggle the current class on the link we can do more. It is simple to add visual extras like a “you are here” state by using CSS generated content with the :after selector (support here). That way you can add visual nice-to-haves without needing the generate HTML in JavaScript or resort to images.

    .js #nav a:hover:after, .js #nav a:focus:after, .js #nav a.current:after {
      content: '➭';
      position: absolute;
      right: 5px;
    }

    See the final result in this fiddle or embedded below:

    JSFiddle demo.

    The benefit of this technique is that we keep all the look and feel in CSS and make it much easier to maintain. And by using CSS transitions and animations you also leverage hardware acceleration.

    Give them a go, please?

    All of these things work across browsers we use these days and using polyfills can be made to work in old browsers, too. However, not everything is needed to be applied to old browsers. As web developers we should look ahead and not cater for outdated technology. If the things I showed above fall back to server-side solutions or page reloads in IE6, nobody is going to be the wiser. Let’s build escalator solutions – smooth when the tech works but still available as stairs when it doesn’t.

    Translations

  6. Hidden Gems of HTML5: classList

    If you are a web developer, you surely must know how handy it is to dynamically change the class attribute on an element. The benefits this technique are quite a few:

    • You leave any changes in the look and feel to the CSS
    • You avoid having to loop lots of elements as you can allow CSS to do that job for you by assigning a class on a parent element
    • You can trigger CSS transitions and avoid having to write your own animation
    • And many more…

    The issue with classes is that it is not too simple to work with because of their representation in the DOM. When you read out className you get one string and you need to split it and use regex to find if a class was used and all kind of other annoyances. This is also why it is a very common interview questions for web developers to write a function to deal with classes.

    Well, you might not be aware of it, but HTML has a very cool new way to deal with classes called classList. This makes it dead easy to add, remove, toggle and check for classes on an element – natively in your browser. You can play with it at JSFiddle:

    JSFiddle demo.

    The methods you have are all you really need:

    • element.classList.add('foo') adds the class foo to the element (if it already exists it does nothing)
    • element.classList.remove('foo') removes the class foo from the element
    • element.classList.toggle('foo') alternatively adds and removes the class foo from the element
    • element.classList.contains('foo') returns if the class is applied to the element or not
    • element.classList.toString() returns all the classes as a string (same as reading out className)

    The browser support is very good with IE being the party pooper. However, there is a polyfill by Eli Grey available for you to use.

  7. People of HTML5 – Bruce Lawson

    Leggi la traduzione in italiano

    HTML5 needs spokespeople to work. There are a lot of people out there who took on this role, and here at Mozilla we thought it is a good idea to introduce some of them to you with a series of interviews and short videos. The format is simple – we send the experts 10 questions to answer and then do a quick video interview to let them introduce themselves and ask for more detail on some of their answers.

    fowd-london-18-19.05.2010_5761The first person to feature is Bruce Lawson of Opera, co-author of Introducing HTML5 and one of the curators of HTML5 Doctor.

    Bruce works from home somewhere in the darker and unknown regions of England, and if you haven’t had the chance to see him speak, make sure to catch one of his talks. Also, despite his disturbing fetish for cheesy cam effects, he really knows his stuff and is a very funny man to boot.

    You can find Bruce on Twitter as @brucel.

    The video interview

    Watch the video on YouTube or Download it from Archive.org as WebM (45MB), OGG (70 MB) or MP4 (70 MB)

    Ten questions about HTML5 for Bruce Lawson

    1) What, in your view, is HTML5 and what does it mean for web development as a whole?

    It’s the language for web applications: it makes writing apps more robust, more interoperable and expands the capabilities of browsers so the web can come closer to native apps.

    2) How did you get involved in the HTML5 world? What is your background and even more importantly, what drives you?

    My background is in accessibility and writing markup. So getting involved in the development of the new language for the Web was too exciting to pass over, and because Opera (my employer) was so closely associated with the genesis of HTML5, it was easy to persuade my boss to let me have the time!

    3) What do you consider the most exciting of the new technologies?

    HTML5, of course — and also DAP (“Device APIs and Policy Working Group”). This thrillingly-named set of specifications is further extending the capabilities of the Web by specifying APIs that allow access to device features like camera, contact books and calendar — much like Geolocation gives browsers access to the device’s GPS capabilities. Like HTML5, the DAP are adapting existing proprietary APIs that have been road-tested, and other manufacturers have committed to supporting the specifications.

    4) You’ve co-authored “Introducing HTML5″ — what was the most frustrating part about writing an HTML5 book? Isn’t HTML5 still a bit of a moving target?

    Apart from the freakishly anachronistic processes behind dead-tree publishing (everything to be submitted in Microsoft Word!) the hardest part was the fact that the spec kept moving from under us. The chapter on video had just been proofread and indexed when the webM format was announced and we had to rewrite. But we were pretty sure that most of the stuff that was ready to use was pretty stable — and in a short Introductory book, we weren’t trying to cover the more esoteric areas, anyway.

    5) You’ve been advocating using the term “NEWT” instead of talking about HTML5, what does that mean and why not HTML5 as an umbrella term?

    Clients and journalists will use “HTML5″ to mean CSS 3/video-that-runs-on-iThings/Geo-enabled applications. It’s the new “Web 2.0″. But we practitioners need to get our nomenclature straight. There are no HTML5 image transitions, just as there are no CSS semantics — and to say there are shows that you didn’t get the 2001 memo about separating style and content.

    If we need an over-all term to encompass DAP, CSS 3, HTML5, Geolocation, SVG, WebGL, then let’s call it the Open Web Stack. But, because people seem to like easy-to-pronounce acronyms and cute logos, I proposed NEWT as a tongue-in-cheek way to highlight the jargon abuse I see happening.

    6) What is in your opinion the biggest obstacle to mainstream HTML5 adoption?

    Developer ignorance: “I can’t use it because it’s not finished” and “I can’t use it because I still have to support IE6″ are the main stumbling blocks. “It’s not finished” annoys me the most. Perhaps we should stop using the English language because it’s “not finished yet” and move to French, as that was apparently finished in 1799.

    Then there’s the IE6 fallacy. The HTML5 Shim allows you to style HTML5 elements in IE6, as long as you have JavaScript. If a visitor is surfing the Web with IE6 and JS turned off, their experience of the whole Web will be pretty dreadful and your site won’t be any worse.

    And, of course, it’s not The Law that you must use HTML5; it’s really for Web applications. HTML4 and XHTML 1 will continue to work fine for documents.

    7) There are a lot of fixes right now available to make HTML5 degrade gracefully on older browsers and IE6. If you look, for example, at the HTML5 boilerplate, this seems a lot of work and extra code and files. Is this worth it? What is your stance on so called “polyfills”?

    All you really need is Remy’s HTML5 Shim so you can style your new HTML5 elements. Depending on your project you choose individual polyfills. is it a lot of work? Perhaps — but is linking to a pre-written polyfill that fakes WebSockets in old browsers harder work than writing that functionality from scratch and making it work in IE6 to 8?

    Polyfills come with built-in obsolescence. They’re only needed for old browsers, and by definition, that’s a dwindling number of installs. Newer browsers don’t even know of their existence. It ain’t pretty, but feature detection and polyfilling are better than browser sniffing or locking out users.

    8) Is there something in the HTML5 recommendations and specs that ails you? Are they taking a direction you don’t agree with?

    I wish that accessibility aspects of canvas had been specified long ago, so that they were in browsers now. People are already abusing canvas to make User Interfaces, and it’s going to be the biggest problem, I think. I also think it’s silly that you can’t use CITE around the name of a person, which is one of the few instances of breaking backwards compatibility with HTML4.

    9) If I wanted to learn about HTML5, where would you say is the best place to start?

    There’s a wonderful book that introduces HTML5. The title escapes me for a moment… Mark Pilgrim has an online book, too, which is pretty good. I co-curate a site called HTML5 Doctor which has a lot of beginner’s articles in tasty morsels. There are, unfortunately, so-called schools sites with out-of-date information and even published books based on archaic versions of the spec.

    10) HTML5 takes a much more lenient approach to markup than HTML4.01 strict or XHTML. You can for example mix upper and lowercase tags and omit the quotes around attributes. Isn’t that a step back in terms of code quality?

    Nope. It should be easy for people to move their sites from XHTML 1 or HTML4, and browsers never cared about syntax (when served text/html), so why impose an arbitrary rule forbidding lower case, or upper case, or requiring trailing slashes? Authors should pick a style that works for them and stick to it. Sites like HTML Lint offer the ability to opt-in to “lifestyle” syntactical choices like quoting attributes, lower case, etc. and I expect authoring tools to do the same.

    The real test of quality is the DOM that the browser constructs from the code, and when browsers have HTML5 parsers, they’ll construct identical DOMs even from invalid code, which is a fantastic win for the interoperable Web.

    Bonus: What’s next? What do you consider the next big issue we need to fix to make the web a better place and easier to build for it?

    We need a CSS layout mechanism that can be understood by mere mortals, some real accessibility for canvas and webGL, and more pictures of nude Open Standards evangelists.

    Do you know anyone I should interview for “People of HTML5″? Tell me on Twitter: @codepo8