Creating a fluid header with CSS

In CSS, fluid dimensions should be always preferred when determining the overall width of page elements. In this post I'm going to show you how to create a fine styled CSS header that always fits the browser viewport.

First, you need a basic HTML structure like this:

<div id="branding">
    <h1><span>Site Name</span></h1>
</div>

A semantical name for our element: that's what we need. Now let's apply CSS:

body {
    
    margin: 0;
    padding: 0;
    background: #fff;
    color: #222;
    
}

#branding {
    
    height: 259px;
    background: #333 url(fluid-header/branding.png) repeat-x;
    color: #fff;
    
}

#branding h1 {
    
    margin: 0 auto;
    width: 90%;
    background: url(fluid-header/header-bg.jpg) repeat-x;
    height: 200px;
    position: relative;
    top: 59px;
    border-radius: 10px 10px 0 0;
    
}

#branding h1 span {
    
    display: block;
    text-align: center;
    padding: 10px 0 0 0;
    font-size: 4em;
    font-weight: normal;
}

The secret here is to use percentages and repeated background images. For example, the second background image is more than 900 pixels wide. Since we don't know in advance what kind of screen resolution we're going to support, it's better to choose images that can be repeated so that there won't be any blank or empty spaces.

Demo

Live demo

jQuery: creating a splash screen effect without Flash

Popups are dinosaurs. Though today they've been actually revitalized by Flash, they're still something heavy, clumsy and clunky. When a visitor enters our page, we want something cool happen, without wasting our time with searching the entire web for a good tutorial on Flash popups. So it's jQuery. What we want is some kind of animation, like a splash screen, that takes place when the page is finished loading. So it's a box, a div, with some content inside, first hidden and then revealed in time.

Our box might have the following styles:

#test {
    
    background: orange;
    width: 0px;
    position: absolute;
    overflow: hidden;
    font-size: 7em;
    text-align: center;
    color: #fff;
    font-family: Impact, sans-serif;
    letter-spacing: 0.1em;
    
}

The width of the box is zeroed and we prevent any overflow of content from happening thanks to the overflow property. Absolute positioning is required here to work with jQuery animations. Now jQuery. First, we want a box with proportional dimensions, using the whole document object as a reference. Then, this box must be horizontally and vertically centered within the viewport. Here's the jQuery code:

$(document).ready(function() {
    
    
    var docWidth = $(document).width();
    var docHeight = $(document).height();
    
    var divWidth = Math.round(docWidth / 2);
    var divHeight = Math.round(docHeight / 2);
    
    var offsetLeft = '50%';
    var offsetTop = '50%';
    
    $('#test').animate(
                   {
                   width: divWidth,
                   height: divHeight,
                   top: offsetTop,
                   left: offsetLeft,
                   marginTop: -(divHeight / 2),
                   marginLeft: -(divWidth / 2),
                   lineHeight: divHeight
                   
                   
                   
                   }, 'slow');
    
    
    
});

Our box is half of the dimensions of the whole page. The CSS trick used here is pretty simple: to center an element within the viewport, use the top and left properties set to 50%. Then use negative values for the margin-top and margin-left properties. These values must be the half of the height and width of the element, respectively.

What else? You can add a lot of improvements to this code. You can make the element disappear, or create a closing button. The only limit is your imagination. Goodbye Flash.

Demo

Live demo

jQuery: expanding and contracting boxes

In this post I'm going to take a step further with repeated jQuery animations creating a simple effect on boxes that allows us to expand and contract them over and over again. This process requires the use of the jQuery chain to concatenate animations.

We start with these CSS styles:

#container {
    width: 500px;
    height: 400px;
    background: silver;
    position: relative;
}

ul {
    width: 400px;
    height: 200px;
    background: orange;
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -100px 0 0 -200px;
}

Then we can add the jQuery code within a setTimeout() loop:

$(document).ready(function() {

  window.setTimeout(function() {

   $('#container')
   .animate({width: 400, height: 300}, 1000)
   .find('ul')
   .animate({width: 200, height: 100, marginLeft: -100, marginTop: -50}, 1000)
   .end()
   .find('li')
   .animate({fontSize: '1.4em'}, 1000)
   .parent().parent()
   .animate({width: 500, height: 400}, 1000)
   .find('ul')
   .animate({width: 400, height: 200, marginLeft: -200, marginTop: -100}, 1000)
   .find('li')
   .animate({fontSize: '1em'}, 1000);
   
     window.setTimeout(arguments.callee, 2000);
   
   }, 1000);


});

By doing so, boxes are always centered, plus they contract and expand over a certain amount of time.

Demo

Live demo

Happy Birthday onwebdev

Finally onwebdev celebrates its first year of activity, with 1059 posts (including this one), some comments and good feedback around the web and a lot of plans for the future. I'd like to thank all my readers and feed subscribers who think that this is a good blog on web development, though I'm not really inclined to be very satisfied of it, mostly because I'm really obsessed with improvements.

I'm sorry that some of my examples don't work in older versions of Internet Explorer (mainly 6), but the fact is that on my PC (and, of course, my Mac.. Mac doesn't run IE!) I switched to Windows 7, so the only versions available there are 7 and 8.

If you're reading this, please don't get me wrong. The aim of this blog is to help developers to find some solutions (I'm not saying ideal or perfect solutions) to their daily problems. If you find some good solutions, thank web standards and browsers, not me. Otherwise, if you don't find any solution at all here, blame me, not web standards and browsers.

Thanks for reading this. I'm really happy to have you as one of my readers.

CSS: styling a content slider

Many tutorials on jQuery and JavaScript teach you how to make a content slider work. In this post, I'm going to show you how to stylize a content slider with CSS to get it ready for being animated with jQuery or JavaScript. First of all, since most jQuery plugins use unordered lists as content sliders, I'm going to use an unordered list too.

Here's our basic markup:

<div id="slider-container">

<ul id="slider">

  <li id="slider-left"></li>
  
  <li id="slider-center"></li>
  
  <li id="slider-right"></li>

</ul>

<ul id="slider-controls">

    <li id="prev"><a href="#"><</a></li>
    <li id="next"><a href="#">></a></li>

</ul>

</div> 

We're going to insert also the slider controls, so I did create another list for that purpose. Our CSS will be:

body {
  margin: 0;
  padding: 3em 0;
  overflow-x: hidden;
  font-family: Arial, sans-serif;
  
}

#slider-container {
  width: 100%;
  height: 500px;
  position: relative;
}

#slider {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  list-style: none;
  position: relative;
}

#slider li {
    width: 500px;
    height: 500px;
    background: silver;
    position: absolute;
}

#slider-left {
    top: 0;
    left: -400px;
}
#slider-center {
   top: 0;
   left: 50%;
   margin-left: -250px;
}
#slider-right {
    top: 0;
    right: -400px;
}

#slider-controls {
    width: 536px;
    height: 20px;
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -10px 0 0 -268px;
}

#slider-controls li {
   width: 20px;
   height: 20px;
}

#slider-controls #prev {
  float: left;
}
#slider-controls #next {float: right;}

#slider-controls a {
    display: block;
    float: left;
    width: 100%;
    height: 100%;
    line-height: 20px;
    text-align: center;
    font-weight: bold;
    color: #fff;
    background: #d40;
    text-decoration: none;
    border-radius: 6px;
}

We use contextual absolute positioning to place the slides in the correct order. Further, also our slider controls will be absolutely positioned but with a larger width so that they will not overlap with the main slide. Each slide is 500 pixels wide, so our controls container will be a little bit wider. Note that we've specified overflow-x: hidden on the body element to prevent browsers from showing any unnecessary scrollbar.

Here's how it looks like in IE6:

This horizontal scrollbar can be easily fixed by adding an overflow declaration where appropriate.

Demo

Live demo

jQuery UI explode and animations

jQuery UI provides an interesting effect called explode which basically divides an element into pieces while making it appear or disappear. We can actually combine this feature with the core jQuery's animate() method to get interesting effects. This features allows us also to specify the number of pieces and the speed of the animation.

For example, we can use explode in this way:

$(document).ready(function() {
 
   $('#test').click(function() {
   
 
 $(this).animate({width: 100, height: 100}, 2000, function() {
  
     $(this).hide('explode', { pieces: 8 }, 2000).show(2000, function() {
     
         $(this).animate({width: 150, height: 150}, 2000);
         
     });
      
  
  
 });
 
  });
  
  
 
});

The box dimensions first change, then the element is hidden and split into pieces, and finally appears again and get its normal dimensions. As you can see, explode can be attached as a parameter to the hide() method together with the number of pieces (stored in the property pieces) and the actual speed of the animation expressed in milliseconds.

Demo

Live demo

jQuery: animations and timers

There are two types of timers in JavaScript: timers that delay the execution of an action for a certain amount of time and timers that make that action enter in an infinite loop, thus repeating the action itself over and over again. In this post I'm going to show how to implement repeated jQuery animations using the setTimeout() function of JavaScript. Bear in mind that jQuery creates a local private scope each time you use one of its methods, so to use this global function we have to use the extended syntax window.function() to make it work. Let's see a practical example.

$(document).ready(function() {


    window.setTimeout(function() {
    
        $('#test').animate({opacity: 'toggle'}, 2000);
        
        window.setTimeout(arguments.callee, 2000);
    
    
    }, 2000);
    
    window.setTimeout(function() {
    
    
        $('#test2').animate({left: 150}, 1000, function() {
            $(this).animate({left: 0}, 1000);
            
        });
        
        window.setTimeout(arguments.callee, 2000);
        
        
    
    
    }, 2000);


});

By using another setTimeout() function inside the main one and passing a reference to the main function itself as one of its arguments, we actually make the whole action enter in an infinite loop. Since the actions lasts 2000 milliseconds, we have to use consistent time references, both on setTimeout() and animate().

Note that these are two separate actions. If you want to achieve the effect of sequential infinite animations, just create a function with nested timers and then invoke that function inside setTimeout() using arguments.callee as the first argument of a second timer. Example:


function repeatAction() {

window.setTimeout(function() {

    // action 1
    
    window.setTimeout(function() {
    
    
    // action 2
    
        window.setTimeout(function() {
        
          // action 3
        
        
        }, 1000);
    
    
    }, 1000);



}, 1000);

}


window.setTimeout(function() {


   repeatAction();
   
   window.setTimeout(arguments.callee, 3000); // repeatAction() timers: 1000 + 1000 + 1000


}, 1000);

We've specified 3000 milliseconds in the second call to setTimeout() because this is the resulting sum of all the timers used in the repeatAction() function.

Demo

Live demo

CSS design and imagination

The beauty of a CSS design lies in what we could call the golden rule of your inner sight. A beautiful CSS design it's not a matter of technique. It has more to do with your ability of seeing your layout already finished before even starting to code it. "Can you see?": a single question that haunts the Minority Report movie from the very beginning. In this movie, seeing something is foreseeing it. In fact, Tom Cruise's physical eyes are surgically removed and replaced, so they're mere matter with very few purpose. The key thing here is the inner sight. Another movie seems to give an answer to that question: "I can see" it's the dark motto of In the mouth of madness, an horror movie directed by John Carpenter (1994).

This is something that you cannot learn from books or online tutorials and articles. This is something that you should learn from everyday life, trying to use your inner sight, your projection and your imagination to see things that your eyes, your physical eyes, are not able to see just because they got used to everything. Even if you've walked your way home every day for countless years, try to rethink it in a new way, try to observe those little details that so often have been neglected. The horror writer H. P. Lovecraft was able to make you see his scenes, his settings, his cities, just because of these little details. His books are scaring thanks to these details.

Use your imagination. See that sign on the corner? Can you imagine it as the branding header or logo for a web site? Can you see its colors, its rust? Did you notice how magazine and newspapers use colors, images, columns and fonts? Walking along the seashore, what's the most striking color that makes you feel amazed? Can you reproduce it in some ways? Try to imagine.

jQuery: mouse-driven sliding effect

One of the most interesting features of the mobile world is the incredible ability given to the user of sliding contents just with a single finger movement. This is a really useful enhancement, because it frees you from being forced to rely on some buttons or controls to make the sliding effect run. Is it possible to achieve a similar effect with jQuery on a traditional, PC-based environment? Yes, but with a major difference: on a traditional environment, the majority of screen events are bound to mouse movements, so we're going to use these ones with the aid of the animate() method. The following is our first test:

$(document).ready(function() {

    $('#container').mousemove(function(e) {
    
        var leftX = e.pageX;
        
        
        $('#slide').animate({left: leftX}, 100);
                
    });


});

The pageX property of the Event object stores the current value of the mouse's position along the x-axis (horizontal). By adding this value to the CSS left property used with animate(), we rearrange the position of the target element every time the mouse is moved by the user.

This is only the first test. If you've tested something similar or, more important, a better solution than this, please let me know.

Demo

Live demo

jQuery: turning strings into links

Some popular social networks don't accept HTML markup in their formats, so they render and store URLs as text. Sometimes this can cause some problems especially when we want to display such URLs as normal HTML links. With jQuery and a simple regular expression (you can find many more regular expressions that match URLs on the web), we can turn these strings into links by using the JavaScript function replace(). Here's how:

(function($) {


    $.fn.toLink = function() {
    
    
        var text = this.text();
        var urlRegExp = /((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/gm;
        
        if(!urlRegExp.test(text)) {
        
            throw new Error('This is not a valid URL.');
            
            return;
        
        
        }
        
        var newText = text.replace(urlRegExp, '<a href="$1">$1</a>');
        
        this.html(newText);
        
        return this;
    
    
    };



})(jQuery);

The replace() function is used here with the global and multiline options. The notation $1 signifies that the content of the href attribute and of the link itself will be generated using the first match of the regular expression. Here's a simple demo:

$(document).ready(function() {


    $('#run').click(function() {
    
    
       $('ul li').each(function() {
       
       
           $(this).toLink();
       
       
       });
    
        return false;
    
    });



});

Demo

Live demo

CSS: negative z-index

In CSS, the z-index property controls the layering order when elements overlap due to positioning. This property accepts both negative and positive values. An element with a greater z-index value will be nearer to the user's eye than an element with a lower value. This turns out to be very useful when elements have some active content (such as links) that needs to be clickable by the user. In fact, if you don't use this property correctly, some of your content might be left inactive by browsers. But what happens when an element has a negative z-index value? This is interesting. For example, given an initial situation like this:

#container {
    width: 400px;
    height: 300px;
    position: relative;
    background: #cecece;
    border: medium solid silver;
}

#one {
    position: absolute;
    width: 150px;
    height: 2em;
    top: 1em;
    left: 2em;
    background: orange;
    z-index: 1;
}

#two {
    position: absolute;
    width: 100px;
    height: 2em;
    top: 1em;
    left: 4em;
    background: fuchsia;
    z-index: 2;
}

#three {
   position: absolute;
   width: 90px;
   height: 2em;
   top: 1em;
   left: 5em;
   background: yellow;
   z-index: 3;
}

you got this result:

Nothing unusual, as you can see. Now let's try to use a negative value on the first element, like so:

#one {
    position: absolute;
    width: 150px;
    height: 2em;
    top: 1em;
    left: 2em;
    background: orange;
    z-index: -1;
}

You got this result instead:

Simply put, a negative value results in the element to be hidden from view. I didn't test this in Internet Explorer, so any comment in that sense would be really appreciated.

jQuery: tracking and concatenating animations

Tracking jQuery animations is not enough. Often we want also to concatenate one animation with another, thus creating an animation chain that will lead to more interesting effects. jQuery allows for this behavior by arming the animate() method with a callback function to be invoked when an animation is complete. Using this function we can attach a second animation to the first one, and so on. For example:

$(document).ready(function() {
   
   var paddingCounter = $('#test li:first').css('padding');

   $('#test li:first').addClass('test').click(function() {
   
       paddingCounter += 1;
      
        var thisWidth = $(this).width();
        
        $(this).animate({
        
           width: thisWidth / 2
        
        }, 'slow', function() {
        
        
           var thisOpacity = $(this).css('opacity');
        
        
           $(this).animate({
           
           
              opacity: thisOpacity - 0.3
           
           }, 'slow', function() {
           
           
               var thisPadding = $(this).css('padding');
               
               $(this).animate({
               
               
                  padding: (paddingCounter + 0.1) / 2
               
               
               }, 'slow');
           
           });
        
        });
   
   });



});

Three sequential animations that change the padding, width and opacity of a given element in a continuous process that involves also the use of tracking in order to get values that will be automatically incremented each time a user activates the trigger action.

Demo

Live demo

jQuery: tracking animations

When you have sequential animations in jQuery involving the use of positioning, it's important to keep track of the current position of an element if you want to progressively change its status on the screen. Basically, all jQuery animations that take place during a call to animate() are a one-way process: you trigger the animation, it takes place, it ends. End of the story. Suppose that you have an element and a trigger link that activates an animation. Each time you click on this link, the affected element must be moved leftwards by 100 pixels. One could write something like this:

$('#run').click(function(e) {

    $('#test').animate({
       left: += 100
    });
    
    e.preventDefault();


});

You click once on the link and everything works just fine. You click twice and sometimes nothing happens. Why? Because we need to track the position of the element in order to run sequential animations, like so:

$('#run').click(function(e) {

    var track = $('#test').offset().left;

    $('#test').animate({
       left: track + 100
    });
    
    e.preventDefault();


});

We've stored the current left offset of the element in a variable. On the first click, this value is 0, so the computation is 0 + 100. On the second click, this value is 100, so we'll have 100 + 100. And so on. As you can see, it's all very simple and requires just a single additional step.

CSS: contextual positioning

In CSS, contextual positioning is the way by which two positioned elements relate to each other. When you use absolute positioning in CSS, a positioned element will always be positioned with respect to the global viewport of the document. But when a positioned element (relatively or absolutely) contains one or more child elements which are also positioned, then these elements will be positioned using their parent element (or a positioned ancestor) as a reference, not the viewport. In other words, the coordinates of the child elements will be calculated with respect to their parent element (or ancestor). Suppose that you have the following CSS rules:

#parent {
    position: absolute;
    width: 400px;
    height: 200px;
    top: 0;
    left: 0;
}

#parent #child {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 0;
    right: 0;
}

The result is depicted below.

As you can see, contextual positioning is a powerful way of handling positioned elements and it turns out to be very useful, especially when you have to deal with complex layouts and you don't want to use floats.

Using the W3C CSS Validator

In this article we will discuss the online CSS validator provided by the W3C at http://jigsaw.w3.org/css-validator/ and discover how to successfully validate our CSS files also by customizing the URL to be sent to the validator.

The validator and CSS syntax

By default, the W3C CSS validator will validate our CSS against the CSS 2.1 specifications. This means that:

  • Browser-specific extensions (such as -moz-border-radius) are not valid (this is also true for other CSS specifications).
  • CSS3 properties and selectors are not valid , although in the case of selectors often the validator does not detect it due to the backward compatibility of CSS3 specifications.
  • Color values shall comply with the CSS 2.1 specifications, which means that the RGBA notation and nominal values different from the defaults are not valid.

Validator's URL

The URLs of the validator all have this form:

http://jigsaw.w3.org/css-validator/validator/parameters

where parameters is a list of one or more pairs of keywords / values listed by the W3C here. A few examples follow. Suppose that I want to validate my style sheet with the CSS3 specifications. I can then use the keyword profile combined with the value css3 in my URL:

http://jigsaw.w3.org/css-validator/validator/?uri=http://yoursite.com/&profile=css3

As you can see, the uri keyword must always use the URI of your site. Then we use a conventional separator (&) and add the keyword profile with css3 as its value. In this way the validator will use the CSS3 specification as a reference.

However, if we wanted to validate our style sheet against a target media other than the screen (such as print), we can use the keyword usermedium followed by one of the values accepted by the CSS specifications. Example:

http://jigsaw.w3.org/css-validator/validator/?uri=http://yoursite.com/&usermedium=print

As you can see, it's all very simple. I refer to the W3C page mentioned above for more details.

Writing correct URLs

To avoid validation errors in the markup, the URL of the validator should be coded following the formal rules for URL encoding. For example, the & character should be encoded in the markup with the corresponding entity &amp; to avoid validation errors. The rest of the URL, in theory, could be left unchanged, even if we could optimize it by following the encoding rules expressed on the W3Schools web site.

jQuery content slider: CSS

In a previous post I shortly introduced the very basic concepts behind a jQuery content slider. Now it's time to talk about the theory that underlies the development of a content slider. First of all, a jQuery content slider is made up of two components: CSS and jQuery itself. In this post I'm going to cover the CSS component in details.

Content overflow

In CSS, the content exceeding from a container is ruled by the overflow property. When you set this property to hidden, all the exceeding content is hidden from view. This property turns out to be very useful when it comes to content sliders. In fact, by using this content you actually make sure that only a part of the content is visible. For example, consider the following image:

You can achieve this result with the following CSS:

#slider {
  width: 340px;
  height: 100px;
}

div.slide {
  float: left;
  width: 100px;
  height: 100px;
  margin-right: 10px;
}

In this case, floats are contained by the fact that we've specified a stated height for their container. Now suppose that you want only the first box to be visible. You can rewrite the above code as follows:

#slider {
  width: 100px;
  height: 100px;
  overflow: hidden;
}

div.slide {
  float: left;
  width: 100px;
  height: 100px;
}

By setting the container's width to the width of a single slide and adding the overflow property to it, you make sure that only the very first box will be visible. For the sake of completeness, bear in mind that CSS3 allows also for the use of the overflow-x and overflow-y properties. As their name says, these properties control the x and y axis of the overflow process, respectively.

Positioning schemes

In CSS, there are two positioning schemes available: relative and absolute. Both rely on the position property and its auxiliary properties to work, namely top, right, bottom and left.

The position of a relatively positioned element always refers to its current position on the page, whereas the position of an absolutely positioned element can actually:

  • refer to the global viewport if there are no positioned ancestors
  • refer to the position of its ancestors if they're positioned

In other words, if you have a relatively positioned element which contains an absolutely positioned element, then the position of the child element refers to its parent, not to the global viewport. In technical terms, this is called contextual positioning.

One important thing to bear in mind is that the four auxiliary properties named above actually affect the overall computation of the final dimensions of an element. More precisely, top and bottom affect the height of the containing block, while left and right affect the width of the containing block.

This is important because if you have to move an element inside a container, you should always carefully calculate what the final dimensions of the element will be. Otherwise, this could lead to unexpected results.

jQuery content slider: the basics

First of all, there are many kinds of content sliders that you can implement with jQuery. Perhaps the easiest one is the call-to-action-driven content slider, that is, a content slider whose links determine the portion of content to be showed. This is and ideal type of implementation for beginners, because a tracking system for all the content slides is really easy to implement. More advanced content sliders are either those that handle galleries (for example, image galleries) or those that show some HTML elements in a sequential order, thus allowing the user to pick up the part that really interests him / her. Since I'm currently developing an advanced content slider for a client, this video tutorial that I'm going to present you here can actually be see as a nice introduction to a topic that I'm going to develop in further posts.

HTML5 and XHTML: syntax comparison

In this article we will take a comparative look at HTML 5 and XHTML trying to figure out where these two markup languages are different and how we can get the maximum benefit from both languages.

A new DOCTYPE

W3C DOCTYPEs have never been the simplest things to be committed to memory. In fact, they are quite long and hard to remember. For example, the following is the DOCTYPE of XHTML 1.0 Strict:

 
<!DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.0 Strict // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

What developers have always been forced to do is to copy and paste the DOCTYPE from existing documents or rely on their editors. With HTML5 these difficulties disappear, because all you need is:

<! DOCTYPE html>

Confused? In fact, the reflection to do is quite simple: the length of the XHTML DOCTYPE comes from the fact that there is also included the URL where a program that processes an XHTML document should identify the DTD to validate our pages. But as we have seen, this feature is used only by the W3C validator, because browsers do not validate our pages, but simply try to interpret them as best as possible. For example, an error like this:

 
<p>
 <blockquote> ...</blockquote>
</p>

is detected by the validator, not by browsers that at least will present a page with an unusual formatting. A paragraph cannot contain a quotation block because it would be considered as invalid, but browsers do not care! Hence it was decided that in HTML5 the DOCTYPE must be oversimplified.

Element writing and syntax

HTML5 introduces new elements but it supports all of the elements already present in XHTML. The rules for XHTML elements are strict: empty elements must always have a closing tag, and certain elements must necessarily have some default attributes. For example, an image must always be inserted as follows:

<img src="foo.png" alt="Foo" />

Note that there is the string '/>' to close the tag. In HTML5, however, empty elements can be written with both the old notation of HTML 4 and XHTML.

The treatment of the attributes is changed. XHTML wants all the attributes always have a value enclosed either in single or double quotes, as follows:

<input type="text" name="q" id="q" disabled="disabled" />

As you can see, the disabled attribute has always its value, although in this case we're merely repeating its name. In HTML5 you can also write it just as in HTML 4:

<input type="text" name="q" id="q" disabled>

Note that HTML5 the closing tag (slash preceded by a space) is not necessary. Moreover, in HTML5 you can omit some element attributes, such as with script and style. So if we had earlier:

 
<style type="text/css"> </ style>
<script type="text/javascript" src="script.js"> </ script>

Now we can simply write:

 
<style> </ style>
<script src="script.js"> </ script>

The explanation for this choice is that browsers are already able to identify the content of some items without having to specify additional attributes. However, as noted above, in HTML5 you can use both notations.

A final example of this simplification is the use of meta tags for specifying the encoding of the document. In XHTML we have:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

HTML5 also accepts

:
<meta charset="utf-8"/>

Return of the embed element

The embed element is deprecated in XHTML in favor of object. Instead, in HTML5 this element is valid. The reason behind that is pretty simple: at the time of this writing, this element is still required to make a media file work correctly across browsers. For that reason, HTML5 developers decided to bring the embed element to life again in order to take advantage of its cross-browser capabilities, especially for those user-agents that still don't fully support object.

Building an interactive catalog for industrial machineries

This is a guest post by Vincenzo Palumbo

Many times we have the need to create a catalog for industrial machineries or even for a simple expresso machine and then try to make it interactive for being used in a simple and clear way by our customers, either on the web or on digital devices such as CDs or DVDs.

I managed to build this kind of catalog by using my background on programming languages and animation softwares, such as PHP, MySQL, AS3, CSS, HTML and Flash. To start with, we need an image representing an expanded version of the components of our machine where we can create the numbering of our pieces (being a technical designer, I made it in 3D). Once chosen our image, we need to open Flash, import the image and create all the components that are going to interact with mouse gestures. Further, we also create the buttons for adjusting the zoom.

We create the AS3 script that will make appear the position, code and description of every single component when we hover with the mouse the components themselves, and also the events that will be attached on the buttons that adjust the zoom. Then when we click on a single component, a popup will be opened showing the component data and the quantity being added to the shopping cart.

All these data are sent to a PHP script that will then process them as if we were on a small e-commerce site, but without payment processing. With HTML and CSS I simply laid out everything and created the menu on the left of the Flash element.

The first menu item, the search engine itself, has been completely developed in PHP with MySQL as the underlying database so that we can search a product by inserting its code or a keyword. Finally, we can export our shopping cart in .doc format. This file can also be attached to the email sent with our order.

You can see a sample here in the DEMO section: http://www.vipastudio.it/manuale/foglio_1.html.

About the author

Vincenzo Palumbo is a tech designer and web developer.

jQuery: image effects

In this post I'm going to show you some nice effects that can be applied to images using jQuery. As you will see, the precess behind image effects requires only the animate() method and a couple of CSS properties to be passed to it. Suppose that we have an image and we want to animate it by adding some effects. The first thing to do is to set up the contextual environment where these effects should take place. In our case, just a few lines of CSS code:

#gallery {
    
    width: 615px;
    margin: 2em auto;
    height: 410px;
}



#gallery img {
    
    width: 300px;
    height: 205px;
    display: block;
    margin: 0 auto;
}

Our image has been centered inside its container and turned into a block-level element. Also notice that the container itself has its dimensions set to values that will fit the original dimensions of the image once our effect will be complete. Now we can add jQuery:

$(document).ready(function() {
    
   $('#run').click(function(e) {
    
    
        $('#gallery img').animate({
            
        
           width: '615px',
           height: '410px',
           opacity: '0.5'
            
            
        }, 'slow', function() {$(this).animate({width: '300px', height: '205px', opacity: 1}, 'slow');});
    
        e.preventDefault();    

   });
   
    
});

Our image will be first made larger and taller, and its opacity will be set to 0.5 (semi-transparent). Then, when this first effect is complete, we attach a callback function to the animate() method so that our image will return to its normal values.

Demo

Live demo

Introduction to Excel Data Validation

This is a guest post by Yoav Ezer

If you create spreadsheets for other people to use and input information into, you will know how problematic it can be when those people make mistakes and introduce bad data into your systems. Luckily we can reduce the amount of errors by using the Microsoft Excel validation feature.

What is Validation?

Validation was introduced by Microsoft in Excel 97. Wikipedia informs us that validation can be described as...

"In common usage, validation is the process of checking if something satisfies a certain criterion. Examples would include checking if a statement is true (validity), if an appliance works as intended, if a computer system is secure, or if computer data are compliant with an open standard."

Essentially by using validation we can get the spreadsheet to check the user input against some criteria that we select, and either allow it through or raise an error message asking the user to correct that input.

Using Validation in Excel

First you need to highlight the cells you wish to have validation applied to. Next find the validation options. Go to Data, Validation as shown below.

Next you need to set the validation rules that you wish to apply to those cells. So for example if we were creating a simple invoicing system then you would need to ensure only valid dates were entered in the invoice date column, and so on.

There are all the validation types that you would expect, from the types of values a user can enter, through to the length of the text you are allowed. In addition there is a "custom" criteria which allows you to enter your own rule.

As an example, if we wanted to prevent duplicate entries in our invoicing spreadsheet, we could use the custom option and a rule such as the following.

This roughly translates as "error if this entry appears twice".

To let the user correct their mistake we need to provide a meaningful error message. An alert tab is provided for us to enter this.

Summary

Unfortunately while it can help stop some inputting errors, Excel can only check against the criteria we think of setting.

In addition to this "human limitation", the user can wipe out our validation rules by copying and pasting whatever they like into the cells.

Those issues aside, if we can ask our users to avoid pasting, it is a remarkably useful addition to the package. Hopefully this article will give you the inspiration to use this feature in your own projects.

About the author

Yoav Ezer co-authors the technology and productivity blog Codswallop. He is also the CEO of a company that produces PDF to Excel conversion software.

For more Excel tips from Yoav, join him on Facebook or Twitter

CSS: advanced attribute selectors example

In this post I'm going to show you some practical examples of advanced CSS 2.1 attribute selectors. More specifically, the selectors in question are (1) the exact match attribute selector, (2) the partial match attribute selector in a dash-separated list of values and (3) the partial match attribute selector in the context of a space-separated list of values. For "values" I mean the values of the various HTML attributes that we're going to test, usually in the form attr="value(s)". To start with, let's sketch a basic HTML structure to stylize first.

<div id="container-main">
    
    
    <div id="main">Test</div>
    
    <div id="secondary" class="secondary box">Test</div>
    
    
</div>

The selectors we'll use are summarized below.

Advanced CSS 2.1 attribute selectors
Pattern Matches Meaning
div[id|="container"] <div id="container-main"> The first value inside a dash-separated list of values.
div[id="main"] <div id="main"> The exact value of the attribute.
div[class~="box"] <div id="secondary" class="secondary box">Test</div> A value in a space-separated list of values.

The CSS code:

div[id|="container"] {
    
    width: 400px;
    margin: 2em auto;
    height: 100px;
    border: thick solid teal;
}

div[id="main"] {
    
    float: left;
    width: 200px;
    height: 100%;
    background: orange;
    
}

div[class~="box"] {
    
    float: right;
    width: 150px;
    height: 100%;
    background: maroon;
    color: white;
    
}

Example

Live example

YouTube: changes to video embed code

Recently YouTube changed its HTML code to embed videos on your pages. Currently the object element has been replaced by an iframe element. This allows even more control over the final layout of the embedded video, though some inner controls are now delegated to the YouTube's engine itself. The good news is that now our markup is a lot cleaner and simpler, because we actually got rid of the annoying embed element contained in the object element. The final markup now looks like the following:

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/QVnRdCJLWX8" frameborder="0" allowFullScreen></iframe>

The most important changes are:

  • a class and title attribute attached to the iframe
  • the content type of the container element is now text/html
  • the URL of the src attribute is now in the form of http://www.youtube.com/embed/videoID, where videoID is the alphanumeric sequence contained at the end of a video's page URL (in this example is QVnRdCJLWX8
  • frameborder and allowFullScreen are not valid HTML attributes for this element, so you should bear this in mind when you want to pass the W3C validation.

iPhone dock with CSS and jQuery

In this post I'm going to show you how to create a nice dock layout that mimics the iPhone dock by using CSS and jQuery. All you need to do for this kind of layout is getting a collection of iPhone icons that you can freely download from the web. Done that, you need then a basic HTML structure to start with:

<div id="dock">
    
    <ul>
        <li id="safari"><a href="#"><span>Safari</span></a></li>
        <li id="mail"><a href="#"><span>Mail</span></a></li>
        <li id="settings"><a href="#"><span>Settings</span></a></li>
        <li id="phone"><a href="#"><span>Phone</span></a></li>
    </ul>
</div>

All these IDs will allow us to get a fine-grain control over the single items which, of course, will be replaced by icons. Now let's move to our CSS:

body {
    
    padding: 2em 0;
    margin: 0 auto;
    width: 320px;
    font: 62.5% Arial, sans-serif;
    
}

#dock {
    
    width: 100%;
    height: 91px;
    background: url(mac-dock/dock.png) no-repeat;
    
}

#dock ul {
    
    height: 100%;
    width: 300px;
    list-style: none;
    margin: 0 auto;
    padding: 0;
    
}

#dock li {
    
    
    width: 59px;
    height: 60px;
    float: left;
    margin-right: 15px;
    position: relative;
    left: 8px;
    background-repeat: no-repeat;
    text-align: center;
}

#dock li a {
    
    float: left;
    width: 100%;
    height: 100%;
    font-size: 1.2em;
    text-decoration: none;
    display: block;
    text-align: center;
    
}

#dock li a span {
    
    display: none;
    background: #fff;
    color: #000;
    color: rgba(0, 0, 0, 0.5);
    padding: 0.3em;
    -moz-border-radius: 6px;
    border-radius: 6px;
    font-weight: bold;
    position: relative;
    top: 65px;
    
}

#dock #safari {
    
    background-image: url(mac-dock/Safari.png);
    left: 4px;
}

#dock #mail {
    
    background-image: url(mac-dock/Mail.png);
}

#dock #settings {
    
    background-image: url(mac-dock/Settings.png);
    left: 12px;
}

#dock #phone {
    
    background-image: url(mac-dock/Phone.png);
    left: 15px;
}

We're using a tiled background image for our dock which has in it four black shadows for four icons. Now, since we want to place our icons exactly within each dock shadow, we use relative positioning to achieve this effect. Finally, jQuery adds a little animation to the previously hidden span elements:

$(document).ready(function() {
    
    
   $('#dock ul li').each(function() {
    
    
        var $li = $(this);
        
        $li.hover(function() {
            
          $li.find('span').fadeIn('slow');
            
            
        }, function() {
            
            
            $li.find('span').fadeOut('slow');            
        }
        
        );
    
    
    
   });
    
    
});

Demo

Live demo

JavaScript: V8 engine preprocessing

One of the main files used by the V8 engine during JavaScript preprocessing is located in the folder /v8/src of the Chromium source code and is called preparser.cc. This file has the task of recognizing and separate input tokens that will be later feed to the JavaScript processor. For example, a main goal of a JavaScript preprocessor is the ability of recognizing JavaScript statements (i.e. all the core statements defined by the current ECMAScript specifications). V8 does the following:

PreParser::SourceElements PreParser::ParseSourceElements(int end_token,
                                                         bool* ok) {
  // SourceElements ::
  //   (Statement)* <end_token>

  while (peek() != end_token) {
    ParseStatement(CHECK_OK);
  }
  return kUnknownSourceElements;
}

The ParseStatement() method, which does all the work, is defined later in the source:

PreParser::Statement PreParser::ParseStatement(bool* ok) {
  // Statement ::
  //   Block
  //   VariableStatement
  //   EmptyStatement
  //   ExpressionStatement
  //   IfStatement
  //   IterationStatement
  //   ContinueStatement
  //   BreakStatement
  //   ReturnStatement
  //   WithStatement
  //   LabelledStatement
  //   SwitchStatement
  //   ThrowStatement
  //   TryStatement
  //   DebuggerStatement

  // Note: Since labels can only be used by 'break' and 'continue'
  // statements, which themselves are only valid within blocks,
  // iterations or 'switch' statements (i.e., BreakableStatements),
  // labels can be simply ignored in all other cases; except for
  // trivial labeled break statements 'label: break label' which is
  // parsed into an empty statement.

  // Keep the source position of the statement
  switch (peek()) {
    case i::Token::LBRACE:
      return ParseBlock(ok);

    case i::Token::CONST:
    case i::Token::VAR:
      return ParseVariableStatement(ok);

    case i::Token::SEMICOLON:
      Next();
      return kUnknownStatement;

    case i::Token::IF:
      return  ParseIfStatement(ok);

    case i::Token::DO:
      return ParseDoWhileStatement(ok);

    case i::Token::WHILE:
      return ParseWhileStatement(ok);

    case i::Token::FOR:
      return ParseForStatement(ok);

    case i::Token::CONTINUE:
      return ParseContinueStatement(ok);

    case i::Token::BREAK:
      return ParseBreakStatement(ok);

    case i::Token::RETURN:
      return ParseReturnStatement(ok);

    case i::Token::WITH:
      return ParseWithStatement(ok);

    case i::Token::SWITCH:
      return ParseSwitchStatement(ok);

    case i::Token::THROW:
      return ParseThrowStatement(ok);

    case i::Token::TRY:
      return ParseTryStatement(ok);

    case i::Token::FUNCTION:
      return ParseFunctionDeclaration(ok);

    case i::Token::NATIVE:
      return ParseNativeDeclaration(ok);

    case i::Token::DEBUGGER:
      return ParseDebuggerStatement(ok);

    default:
      return ParseExpressionOrLabelledStatement(ok);
  }
}

As you can see, the above method performs a sequential check using a switch statement. On each step, which corresponds to a different input token, an appropriate method is called on each token, depending on the type of JavaScript component encountered. Note that this is a one-way check, because each case statement terminates with a return statement so that the break statement is not required.

HTML5: line breaks and CSS generated content

Today Ingo Chao wrote on CSS Discuss: "HTML5:Rendering:Punctuation and decorations says br { content: '\A'; white-space: pre; } But this doesn't seem to work in Safari and Chrome: http://www.satzansatz.de/w3/break.html Who is wrong?". I then made a test using XML, because in XML browsers tend to honor the specifications ad litteram. In this test, I've created a break element (empty), trying to add the following styles to it:

break {
    
    content: '\A';
    white-space: pre;
    
}

It didn't work, so I actually added the declaration display: block to the above style rule. This single declaration alone makes it work. Other declarations don't produce any effect. You can see the result here.

CSS: understanding the document flow

The document flow is the model by which elements are rendered by default in the CSS specifications. In this model, elements are rendered according by their default display rule. In other words, block-level elements are displayed on a new line and inline elements on the same line. Everything is stacked in an ordered way from top to bottom. For example, in a block-level formatting context elements are rendered in the way depicted by the following picture.

The document flow can be modified by CSS through the following properties:

  • float
  • position

Using these properties modifies the way elements are rendered by default. For example, if we use floating, then the document flow will appear as shown below.

The arrows represent the impact of floating on elements that are still in the normal flow. Bear in mind, however, that despite the fact that we can still recover the normal flow for floating by using clearing, there's no direct way to do the same for positioning.

JavaScript: turning an HTMLCollection into an array

In the DOM terminology, an HTMLCollection is a set of DOM nodes that behave in a way that lets developers think that they're dealing with a normal array. This is not the case, because this kind of DOM structure shares only the length property and the indexed access to elements with a normal JavaScript array object. Sometimes, however, it's preferable to turn this kind of collection into a normal JavaScript array, for example to use some of the most popular array methods. Here's an example:

function HTMLNodesToArray(reference, elems) {
    
    
    reference = document.getElementById(reference);
    elems = elems || '*';
    var nodes = [];
    
    var elements = reference.getElementsByTagName(elems);
    var i;
    var len = elements.length;
    
    for(i = 0; i< len; i += 1) {
        
        
        var node = elements[i];
        nodes.push(node);
        
        
    }
    
    return nodes;
}

This function simply iterates over an HTMLCollection and stores all its member nodes in an array for later use. A practical example would be the following:

unction showNodes() {
    
    var htmlNodes = HTMLNodesToArray('test', 'li');
    
    var reduced = htmlNodes.pop();
    
    var last = reduced;
    
    alert(last.firstChild.nodeValue);
    
    
}

window.onload = function() {
    
    
    showNodes();
    
};

In this case, we've been able to use the common array pop() method on our collection of nodes.

Demo

Live demo

CSS3: the background-rotate property (proposal)

A currently requested feature by web developers is the ability of applying rotations to background images. CSS3 specifications already allow for this kind of transformations in their transformations module, but only for page elements, not for their background image. In theory, a property that might fulfill this task could be called background-rotate. This property should accept as its value the same type of values allowed for the rotate() function used in the transformations module. A major problem that might be arise is where to place this property in the shorthand background notation. This property should look like this:


#test {
  background-image: url(foo.png);
  background-repeat: no-repeat;
  background-rotate: -10deg;
}

This image, positioned in the top left upper corner of the element, should be rotated by 10 degrees counterclockwise. Another problem for browsers is to establish an axis for the rotation. Finally, it should be carefully checked whether this transformation may actually be expensive in the context of background images.

Origin of HTML5 element names

The origin of HTML5 element names derives from a Google research on the most used element nomenclatures on the web. Google simply analyzed an impressive number of web documents and found out that many web authors used the same nomenclature for naming their page elements. Sadly, this nomenclature has more to do with page presentation than page semantics and structure. The original form of these elements used div elements together with ID or class attributes to convey a functional meaning to the elements in question. Some of these elements are reported in the following table, together with their corresponding HTML counterpart.

HTML5 and HTML elements
HTML5 element HTML element
article <div id="article"></div>
aside <div id="aside"></div>
footer <div id="footer"></div>
header <div id="header"></div>
nav <div id="nav"></div>
section <div id="section"></div>

JavaScript: cross-browser event handling

While waiting for the next release of Internet Explorer, which promises to normalize the W3C DOM event model, developers are forced to deal with the different implementations of event handling across browsers. One of the first developers who took care of this problem was actually Scott Andrew back in 2001. In his seminal article on the subject, Scott proposed two simple functions that normalize events across browser, thus allowing developers to attach event handlers without worrying about browser incompatibilities. These functions are the following:

function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

W3C DOM compliant browsers use add/removeEventListener, whereas IE implements attach/detachEvent. Both functions take care of this. A simple test:

var test = document.getElementById('test');
var enlarge = document.getElementById('enlarge');

function makeLarger(evt) {
    
    evt = event || window.event;
    
    test.style.width = '200px';
    test.style.height = '200px';

    if(evt.preventDefault) {
        
        evt.preventDefault();
        
        
    } else {
        
        
        evt.returnValue = false;
    }
}

addEvent(enlarge, 'click', makeLarger, true);

Test

Live test

CSS: valid and invalid color values

In CSS, valid color values actually fall into three categories: RGB (or RGBA) values, hexadecimal values and named color values (such as red). The CSS specifications don't allow for the use of named color values other than those listed in the aforementioned page. All other named color values, such as yellowgreen or darkred are considered invalid. Here are the validation results obtained from trying to use one of these invalid color names.

As you can see, these kind of values are invalid CSS.

jQuery: parsing a YouTube feed

Parsing a YouTube feed is very simple with jQuery. Since we're dealing with a remote resource, the first thing we need to do is to set up a server-side script that will fetch the feed for us. In this case we 're using the Most Viewed feed taken directly from the YouTube's home page (just follow the feed links that are linked from this page). However, there's a catch: this kind of feed mix up XML elements and HTML markup, so we need also to separate these two components. The server-side script, written in PHP, is the following:

header('Content-Type: text/html');
$youtube_rss = simplexml_load_file('http://gdata.youtube.com/feeds/base/standardfeeds/most_viewed?client=ytapi-youtube-index&time=today&v=2');

foreach($youtube_rss->entry as $entry) {


    echo '<div class="entry">' . $entry->content . '</div>' . "\n";


}

This script uses SimpleXML to fetch and parse the feed, returning a set of HTML elements containing the actual contents of the feed. Note that we're also serving our file as HTML. After this, the jQuery code is really straightforward to implement:

$(document).ready(function() {

    var htmlFeed = '';

    $.ajax({
    
    
        type: 'GET',
        url: 'youtube-feed.php',
        dataType: 'html',
        success: function(html) {
        
        
           htmlFeed = html;           
                      
           $(htmlFeed).appendTo('#youtube-feed');
        
        
        }
    
    
    
    
    });

We simply append the returned markup to our placeholder.

Demo

Live demo