Blog

  • CSS Getting Started

    Getting Started with CSS

    In this tutorial you’ll learn how easy it is to add style and formatting information to the web pages using CSS. But, before we begin, make sure that you have some working knowledge of HTML.

    If you’re just starting out in the world of web development, start learning from here »

    Without further ado, let’s get started with the Cascading Style Sheets (CSS).

    Including CSS in HTML Documents

    CSS can either be attached as a separate document or embedded in the HTML document itself. There are three methods of including CSS in an HTML document:

    • Inline styles — Using the style attribute in the HTML start tag.
    • Embedded styles — Using the <style> element in the head section of a document.
    • External style sheets — Using the <link> element, pointing to an external CSS file.

    In this tutorial we will cover all these three methods for inserting CSS one by one.

    Note: The inline styles have the highest priority, and the external style sheets have the lowest. It means if you specify styles for an element in both embedded and external style sheets, the conflicting style rules in the embedded style sheet would override the external style sheet.

    Inline Styles

    Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag. It can be attached to an element using the style attribute.

    The style attribute includes a series of CSS property and value pairs. Each "property: value" pair is separated by a semicolon (;), just as you would write into an embedded or external style sheets. But it needs to be all in one line i.e. no line break after the semicolon, as shown here:

    Example

    <h1 style="color:red; font-size:30px;">This is a heading</h1>
    <p style="color:green; font-size:22px;">This is a paragraph.</p>
    <div style="color:blue; font-size:14px;">This is some text content.</div>

    Using the inline styles are generally considered as a bad practice. As style rules are embedded directly inside the HTML tag, it causes the presentation to become mixed with the content of the document; which makes the code hard to maintain and negates the purpose of using CSS.

    Note: It’s become impossible to style pseudo-elements and pseudo-classes with inline styles. You should, therefore, avoid the use of style attributes in your code. Using external style sheets is the preferred way to add styles to the HTML documents.


    Embedded Style Sheets

    Embedded or internal style sheets only affect the document they are embedded in.

    Embedded style sheets are defined in the <head> section of an HTML document using the <style> element. You can define any number of <style> elements in an HTML document but they must appear between the <head> and </head> tags. Let’s take a look at an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>My HTML Document</title>
        <style>
            body { background-color: YellowGreen; }
            p { color: #fff; }
        </style>
    </head>
    <body>
        <h1>This is a heading</h1>
        <p>This is a paragraph of text.</p>
    </body>
    </html>

    Tip: The type attribute of the <style> and <link> tag (i.e. type="text/css") defines the language of the style sheet. This attribute is purely informative. You can omit this since CSS is the standard and default style sheet language in HTML5.


    External Style Sheets

    An external style sheet is ideal when the style is applied to many pages of the website.

    An external style sheet holds all the style rules in a separate document that you can link from any HTML file on your site. External style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by changing just one file.

    You can attach external style sheets in two ways — linking and importing.

    Linking External Style Sheets

    Before linking, we need to create a style sheet first. Let’s open your favorite code editor and create a new file. Now type the following CSS code inside this file and save it as “style.css”.

    Example

    body {
        background: lightyellow;
        font: 18px Arial, sans-serif;
    }
    h1 {
        color: orange;
    }

    An external style sheet can be linked to an HTML document using the <link> tag. The <link> tag goes inside the <head> section, as you can see in the following example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>My HTML Document</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <h1>This is a heading</h1>
        <p>This is a paragraph of text.</p>
    </body>
    </html>

    Tip: Among all the three methods, using external style sheet is the best method for defining and applying styles to the HTML documents. As you can clearly see with external style sheets, the affected HTML file require minimal changes in the markup.

    Importing External Style Sheets

    The @import rule is another way of loading an external style sheet. The @import statement instructs the browser to load an external style sheet and use its styles.

    You can use it in two ways. The simplest is within the header of your document. Note that, other CSS rules may still be included in the <style> element. Here’s an example:

    Example

    <style>
        @import url("css/style.css");
        p {
            color: blue;
            font-size: 16px;
        }
    </style>

    Similarly, you can use the @import rule to import a style sheet within another style sheet.

    Example

    @import url("css/layout.css");
    @import url("css/color.css");
    body {
        color: blue;
        font-size: 14px;
    }
  • CSS Tutorial

    CSS stands for Cascading Style Sheets. CSS is a standard style sheet language used for describing the presentation (i.e. the layout and formatting) of the web pages.

    Prior to CSS, nearly all of the presentational attributes of HTML documents were contained within the HTML markup (specifically inside the HTML tags); all the font colors, background styles, element alignments, borders and sizes had to be explicitly described within the HTML.

    As a result, development of the large websites became a long and expensive process, since the style information were repeatedly added to every single page of the website.

    To solve this problem CSS was introduced in 1996 by the World Wide Web Consortium (W3C), which also maintains its standard. CSS was designed to enable the separation of presentation and content. Now web designers can move the formatting information of the web pages to a separate style sheet which results in considerably simpler HTML markup, and better maintainability.

    CSS3 is the latest version of the CSS specification. CSS3 adds several new styling features and improvements to enhance the web presentation capabilities.

    Note: Our CSS tutorial will help you to learn the fundamentals of the latest CSS3 language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basic section and gradually move forward by learning a little bit every day.


    What You Can Do with CSS

    There are lot more things you can do with CSS.

    • You can easily apply same style rules on multiple elements.
    • You can control the presentation of multiple pages of a website with a single style sheet.
    • You can present the same page differently on different devices.
    • You can style dynamic states of elements such as hover, focus, etc. that isn’t possible otherwise.
    • You can change the position of an element on a web page without changing the markup.
    • You can alter the display of existing HTML elements.
    • You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
    • You can create animations and transitions effects without using any JavaScript.
    • You can create print friendly version of your web pages.

    The list does not end here, there are many other interesting things that you can do with CSS. You will learn about all of them in detail in upcoming chapters.


    Advantages of Using CSS

    The biggest advantage of CSS is that it allows the separation of style and layout from the content of the document. Here are some more advantages, why one should start using CSS?

    • CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an element. You can write CSS once; and then the same code can be applied to the groups of HTML elements, and can also be reused in multiple HTML pages.
    • Easy Maintenance — CSS provides an easy means to update the formatting of the documents, and to maintain the consistency across multiple documents. Because the content of the entire set of web pages can be easily controlled using one or more style sheets.
    • Pages Load Faster — CSS enables multiple pages to share the formatting information, which reduces complexity and repetition in the structural contents of the documents. It significantly reduces the file transfer size, which results in a faster page loading.
    • Superior Styles to HTML — CSS has much wider presentation capabilities than HTML and provide much better control over the layout of your web pages. So you can give far better look to your web pages in comparison to the HTML presentational elements and attributes.
    • Multiple Device Compatibility — CSS also allows web pages to be optimized for more than one type of device or media. Using CSS the same HTML document can be presented in different viewing styles for different rendering devices such as desktop, cell phones, etc.

    Tip: Now most of the HTML attributes are being deprecated and it’s not recommended to use. So it’s a good idea to use as much CSS as possible to increase the adaptability your website and make them compatible to future browsers, as well.


    What This Tutorial Covers

    This CSS tutorial series covers all the fundamentals of CSS, including the idea of selectors, methods of setting colors and backgrounds, way of formatting fonts and text, styling UI elements such as hyperlinks, lists, tables, etc. as well as the concept of CSS box model, and so on.

    Once you’re comfortable with the basics, you’ll move on to next level that explains the way of setting dimension and alignment of elements, methods for positioning elements on a web page, using image sprites, as well as the concept of relative and absolute units, visual formatting model, display and visibility, layers, pseudo classes and elements, media dependent style sheets, and so on.

    Finally, you’ll explore some advanced features introduced in CSS3 like gradient colors, drop shadow effect, 2D and 3D transforms, alpha transparency, as well as the method of creating transition and animation effect, flex layouts, filter effect, the concept of media queries, and more.

    Tip: Every chapter in this tutorial contains lots of real-world examples that you can try and test using an online editor. These examples will help you to better understand the concept or topic. It also contains smart workarounds as well as useful tips and important notes.

  • HTML5 Examples

    HTML Basic

    HTML Text

    HTML Links

    HTML Images

    HTML Tables

    HTML Lists

    HTML Forms

    HTML Styles

    HTML iFrame

    HTML Scripts

    HTML5 New Input Types

    HTML5 Canvas

    HTML5 SVG

    HTML5 Audio

    HTML5 Video

    HTML5 Web Storage

    HTML5 Web Workers

    HTML5 Geolocation

  • HTML5 Drag and Drop

    Drag and Drop an Element

    The HTML5 drag and drop feature allows the user to drag and drop an element to another location. The drop location may be a different application. While dragging an element a translucent representation of the element is follow the mouse pointer.

    Let’s try out the following example to understand how it basically works:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Using Drag and Drop</title>
    <script>
        function dragStart(e) {
            // Sets the operation allowed for a drag source
            e.dataTransfer.effectAllowed = "move";
        
            // Sets the value and type of the dragged data
            e.dataTransfer.setData("Text", e.target.getAttribute("id"));
        }
        function dragOver(e) {
            // Prevent the browser default handling of the data
            e.preventDefault();
            e.stopPropagation();
        }
        function drop(e) {
            // Cancel this event for everyone else
            e.stopPropagation();
            e.preventDefault();
        
            // Retrieve the dragged data by type
            var data = e.dataTransfer.getData("Text");
        
            // Append image to the drop box
            e.target.appendChild(document.getElementById(data));
        }
    </script>
    <style>
        #dropBox {
            width: 300px;
            height: 300px;
            border: 5px dashed gray;
            background: lightyellow;
            text-align: center;
            margin: 20px 0;
            color: orange;
        }
        #dropBox img {
            margin: 25px;
        }
    </style>
    </head>
    <body>
        <h2>Drag and Drop Demo</h2>
        <p>Drag and drop the image into the drop box:</p>
        <div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);">
            <!--Dropped image will be inserted here-->
        </div>
        <img src="../images/kites.jpg" id="dragA" draggable="true" ondragstart="dragStart(event);" width="250" height="250" alt="Flying Kites">
    </body>
    </html>

    Tip: You can make an element draggable by setting the draggable attribute to true, like draggable="true". However, in most web browsers, text selections, images, and anchor elements with an href attribute are draggable by default.


    Drag and Drop Events

    A number of events are fired during the various stages of the drag and drop operation. But mouse events such as mousemove are not fired during a drag operation.

    The following table provides you a brief overview of all the drag and drop events.

    EventDescription
    ondragstartFires when the user starts dragging an element.
    ondragenterFires when a draggable element is first moved into a drop listener.
    ondragoverFires when the user drags an element over a drop listener.
    ondragleaveFires when the user drags an element out of drop listener.
    ondragFires when the user drags an element anywhere; fires constantly but can give X and Y coordinates of the mouse cursor.
    ondropFires when the user drops an element into a drop listener successfully.
    ondragendFires when the drag action is complete, whether it was successful or not. This event is not fired when dragging a file to the browser from the desktop.
  • HTML5 Geolocation

    What is Geolocation?

    The HTML5 geolocation feature lets you find out the geographic coordinates (latitude and longitude numbers) of the current location of your website’s visitor.

    This feature is helpful for providing better browsing experience to the site visitor. For example, you can return the search results that are physically close to the user’s location.

    Finding a Visitor’s Coordinates

    Getting the position information of the site visitor using the HTML5 geolocation API is fairly simple. It utilizes the three methods that are packed into the navigator.geolocation object — getCurrentPosition()watchPosition() and clearWatch().

    The following is a simple example of geolocation that displays your current position. But, first you need to agree to let the browser tell the web server about your position.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Current Position</title>
    <script>
        function showPosition() {
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
                    document.getElementById("result").innerHTML = positionInfo;
                });
            } else {
                alert("Sorry, your browser does not support HTML5 geolocation.");
            }
        }
    </script>
    </head>
    <body>
        <div id="result">
            <!--Position information will be inserted here-->
        </div>
        <button type="button" onclick="showPosition();">Show Position</button>
    </body>
    </html>

    Note: The web browsers won’t share the visitor location with a web page unless the visitor gives it explicit permission. The geolocation standard makes it an official rule to get user permission for every website that wants location data.


    Dealing with Errors and Rejections

    There may be a situation when a user does not want to share his location data with you. To deal with such situations, you can supply two functions when you call the getCurrentLocation() function.

    The first function is called if your geolocation attempt is successful, while the second is called if your geolocation attempt ends in failure. Let’s check out an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Handling Geolocation Errors</title>
    <script>
        // Set up global variable
        var result;
        
        function showPosition() {
            // Store the element where the page displays the result
            result = document.getElementById("result");
            
            // If geolocation is available, try to get the visitor's position
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
                result.innerHTML = "Getting the position information...";
            } else {
                alert("Sorry, your browser does not support HTML5 geolocation.");
            }
        };
        
        // Define callback function for successful attempt
        function successCallback(position) {
            result.innerHTML = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
        }
        
        // Define callback function for failed attempt
        function errorCallback(error) {
            if(error.code == 1) {
                result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
            } else if(error.code == 2) {
                result.innerHTML = "The network is down or the positioning service can't be reached.";
            } else if(error.code == 3) {
                result.innerHTML = "The attempt timed out before it could get the location data.";
            } else {
                result.innerHTML = "Geolocation failed due to unknown error.";
            }
        }
    </script>
    </head>
    <body>
        <div id="result">
            <!--Position information will be inserted here-->
        </div>
        <button type="button" onclick="showPosition();">Show Position</button>
    </body>
    </html>

    Showing Location on Google Map

    You can do very interesting things with geolocation data, like showing the user location on Google map. The following example will show your current location on Google map based the latitude and longitude data retrieved through the HTML5 geolocation feature.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Using the Google Maps</title>
    <script>
        function showPosition() {
            navigator.geolocation.getCurrentPosition(showMap);
        }
        
        function showMap(position) {
            // Get location data
            var latlong = position.coords.latitude + "," + position.coords.longitude;
            
            // Set Google map source url
            var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
            
            // Create and insert Google map
            document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='"+ mapLink +"'>";
        }
    </script>
    </head>
    <body>
        <button type="button" onclick="showPosition();">Show My Position on Google Map</button>
        <div id="embedMap">
            <!--Google map will be embedded here-->
        </div>
    </body>
    </html>

    The above example will simply show the location on the Google map using a static image. However, you can also create interactive Google maps with dragging, zoom in/out and other features that you have come across in your real life. Let’s take a look at the following example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Using the Google Maps</title>
    <script src="https://maps.google.com/maps/api/js?sensor=false"></script>
    <script>
    function showPosition() {
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showMap, showError);
        } else {
            alert("Sorry, your browser does not support HTML5 geolocation.");
        }
    }
     
    // Define callback function for successful attempt
    function showMap(position) {
        // Get location data
        lat = position.coords.latitude;
        long = position.coords.longitude;
        var latlong = new google.maps.LatLng(lat, long);
        
        var myOptions = {
            center: latlong,
            zoom: 16,
            mapTypeControl: true,
            navigationControlOptions: {
                style:google.maps.NavigationControlStyle.SMALL
            }
        }
        
        var map = new google.maps.Map(document.getElementById("embedMap"), myOptions);
        var marker = new google.maps.Marker({ position:latlong, map:map, title:"You are here!" });
    }
     
    // Define callback function for failed attempt
    function showError(error) {
        if(error.code == 1) {
            result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
        } else if(error.code == 2) {
            result.innerHTML = "The network is down or the positioning service can't be reached.";
        } else if(error.code == 3) {
            result.innerHTML = "The attempt timed out before it could get the location data.";
        } else {
            result.innerHTML = "Geolocation failed due to unknown error.";
        }
    }
    </script>
    </head>
    <body>
        <button type="button" onclick="showPosition();">Show My Position on Google Map</button>
        <div id="embedMap" style="width: 400px; height: 300px;">
            <!--Google map will be embedded here-->
        </div>
    </body>
    </html>

    Please check out the following URL to learn more about the Google Maps Javascript API: https://developers.google.com/maps/documentation/javascript/reference.


    Monitoring the Visitor’s Movement

    All the examples we’ve used so far have relied on the getCurrentPosition() method. However, the geolocation object has another method watchPosition() that allow you to track the visitor’s movement by returning the updated position as the location changes.

    The watchPosition() has the same input parameters as getCurrentPosition(). However, watchPosition() may trigger the success function multiple times — when it gets the location for the first time, and again, whenever it detects a new position. Let’s see how this works:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Watching Position</title>
    <script>
        // Set global variable
        var watchID;
    
        function showPosition() {
            if(navigator.geolocation) {
                watchID = navigator.geolocation.watchPosition(successCallback);
            } else {
                alert("Sorry, your browser does not support HTML5 geolocation.");
            }
        }
    
        function successCallback(position) {
            toggleWatchBtn.innerHTML = "Stop Watching";
            
            // Check position has been changed or not before doing anything
            if(prevLat != position.coords.latitude || prevLong != position.coords.longitude){
                
                // Set previous location
                var prevLat = position.coords.latitude;
                var prevLong = position.coords.longitude;
                
                // Get current position
                var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
                document.getElementById("result").innerHTML = positionInfo;
                
            }
            
        }
    
        function startWatch() {
            var result = document.getElementById("result");
            
            var toggleWatchBtn = document.getElementById("toggleWatchBtn");
            
            toggleWatchBtn.onclick = function() {
                if(watchID) {
                    toggleWatchBtn.innerHTML = "Start Watching";
                    navigator.geolocation.clearWatch(watchID);
                    watchID = false;
                } else {
                    toggleWatchBtn.innerHTML = "Aquiring Geo Location...";
                    showPosition();
                }
            }
        }
        
        // Initialise the whole system (above)
        window.onload = startWatch;
    </script>
    </head>
    <body>
        <button type="button" id="toggleWatchBtn">Start Watching</button>
        <div id="result">
            <!--Position information will be inserted here-->
        </div>   
    </body>
    </html>
  • HTML5 Server-Sent Events

    What is Server-Sent Event?

    HTML5 server-sent event is a new way for the web pages to communicating with the web server. It is also possible with the XMLHttpRequest object that lets your JavaScript code make a request to the web server, but it’s a one-for-one exchange — that means once the web server provides its response, the communication is over. XMLHttpRequest object is the core of all Ajax operations.

    However, there are some situations where web pages require a longer-term connection to the web server. A typical example is stock quotes on finance websites where price updated automatically. Another example is a news ticker running on various media websites.

    You can create such things with the HTML5 server-sent events. It allows a web page to hold an open connection to a web server so that the web server can send a new response automatically at any time, there’s no need to reconnect, and run the same server script from scratch over and over again.

    Note: Server-Sent Events (SSE) are unidirectional that means data are delivered in one direction from the server to client. A client typically is a web browser.

    Tip: The HTML5’s server-sent events feature is supported in all major modern web browsers like Firefox, Chrome, Safari and Opera except Internet Explorer.

    Sending Messages with a Server Script

    Let’s create a PHP file named “server_time.php” and type the following script into it. It will simply report the current time of the web server’s built-in clock in regular intervals. We will retrieve this time and update the web page accordingly later in this tutorial.

    Example

    <?php
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
     
    // Get the current time on server
    $currentTime = date("h:i:s", time());
     
    // Send it in a message
    echo "data: " . $currentTime . "\n\n";
    flush();
    ?>

    The first two line of the PHP script sets two important headers. First, it sets the MIME type to text/event-stream, which is required by the server-side event standard. The second line tells the web server to turn off caching otherwise the output of your script may be cached.

    Every message send through HTML5 server-sent events must start with the text data: followed by the actual message text and the new line character sequence (\n\n).

    And finally, we have used the PHP flush() function to make sure that the data is sent right away, rather than buffered until the PHP code is complete.


    Processing Messages in a Web Page

    The EventSource object is used to receive server-sent event messages.

    Now let’s create an HTML document named “demo_sse.html” and place it in the same project directory where the “server_time.php” file is located. This HTML document simply receives the current time reported by the web server and display it to the user.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Using Server-Sent Events</title>
    <script>
        window.onload = function() {
            var source = new EventSource("server_time.php");
            source.onmessage = function(event) {
                document.getElementById("result").innerHTML += "New time received from web server: " + event.data + "<br>";
            };
        };
    </script>
    </head>
    <body>
        <div id="result">
            <!--Server response will be inserted here-->
        </div>
    </body>
    </html>
  • HTML5 Web Workers

    What is Web Worker?

    If you try to do intensive task with JavaScript that is time-consuming and require hefty calculations browser will freeze up the web page and prevent the user from doing anything until the job is completed. It happens because JavaScript code always runs in the foreground.

    HTML5 introduces a new technology called web worker that is specifically designed to do background work independently of other user-interface scripts, without affecting the performance of the page. Unlike normal JavaScript operations, web worker doesn’t interrupt the user and the web page remains responsive because they are running the tasks in the background.

    Tip: The HTML5’s web worker feature is supported in all major modern web browsers like Firefox, Chrome, Opera, Safari and Internet Explorer 10 and above.


    Create a Web Worker File

    The simplest use of web workers is for performing a time-consuming task. So here we are going to create a simple JavaScript task that counts from zero to 100,000.

    Let’s create an external JavaScript file named “worker.js” and type the following code.

    Example

    var i = 0;
    function countNumbers() {
        if(i < 100000) {
            i = i + 1;
            postMessage(i);
        }
     
        // Wait for sometime before running this script again
        setTimeout("countNumbers()", 500);
    }
    countNumbers();

    Note: Web workers have no access to the DOM. That means you can’t access any DOM elements in the JavaScript code that you intend to run using web workers.

    Tip: The worker object’s postMessage() method is used to send a message (like the numbers in the example above) back to the web page from the web worker file.


    Doing Work in the Background with Web Worker

    Now that we have created our web worker file. In this section we are going to initiate the web worker from an HTML document that runs the code inside the file named “worker.js” in the background and progressively displays the result on the web page. Let’s see how it works:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Using Web Worker</title>
    <script>
        if(window.Worker) {
            // Create a new web worker
            var worker = new Worker("worker.js");
            
            // Fire onMessage event handler
            worker.onmessage = function(event) {
                document.getElementById("result").innerHTML = event.data;
            };
        } else {
            alert("Sorry, your browser do not support web worker.");
        }
    </script>
    </head>
    <body>
        <div id="result">
            <!--Received messages will be inserted here-->
        </div>
    </body>
    </html>

    Example explained:

    The JavaScript code in the above example has the following meaning:

    • The statement var worker = new Worker(“worker.js”); creates a new web worker object, which is used to communicate with the web worker.
    • When the worker posts a message, it fires the onmessage event handler (line no-14) that allows the code to receive messages from the web worker.
    • The event.data element contains the message sent from the web worker.

    Note: The code that a worker runs is always stored in a separate JavaScript file. This is to prevent web developer from writing the web worker code that attempts to use global variables or directly access the elements on the web page.


    Terminate a Web Worker

    So far you have learnt how to create worker and start receiving messages. However, you can also terminate a running worker in the middle of the execution.

    The following example will show you how to start and stop worker from a web page through clicking the HTML buttons. It utilizes the same JavaScript file ‘worker.js’ what we have used in the previous example to count the numbers from zero to 100000. Let’s try it out:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Start/Stop Web Worker</title>
    <script>
        // Set up global variable
        var worker;
        
        function startWorker() {
            // Initialize web worker
            worker = new Worker("worker.js");
            
            // Run update function, when we get a message from worker
            worker.onmessage = update;
            
            // Tell worker to get started
            worker.postMessage("start");
        }
        
        function update(event) {
            // Update the page with current message from worker
            document.getElementById("result").innerHTML = event.data;
        }
        
        function stopWorker() {
            // Stop the worker
            worker.terminate();
        }
    </script>
    </head>
    <body>
        <h1>Web Worker Demo</h1>
        <button onclick="startWorker();" type="button">Start web worker</button>
        <button type="button" onclick="stopWorker();">Stop web worker</button>
        <div id="result">
            <!--Received messages will be inserted here-->
        </div>
    </body>
    </html>
  • HTML5 Application Cache

    What is Application Cache?

    Typically most web-based applications will work only if you’re online. But HTML5 introduces an application cache mechanism that allows the browser to automatically save the HTML file and all the other resources that needs to display it properly on the local machine, so that the browser can still access the web page and its resources without an internet connection.

    Here are some advantages of using the HTML5 application cache feature:

    • Offline browsing — Users can use the application even when they’re offline or there are unexpected disruptions in the network connection.
    • Improve performance — Cached resources load directly from the user’s machine rather than the remote server hence web pages load faster and performing better.
    • Reduce HTTP request and server load — The browser will only have to download the updated/changed resources from the remote server that minimize the HTTP requests and saves precious bandwidth as well as reduce the load on the web server.

    Tip: The HTML5’s application cache feature is supported in all major modern web browsers like Firefox, Chrome, Opera, Safari and Internet Explorer 10 and above.


    Caching Files with a Manifest

    To cache the files for offline uses, you need to complete the following steps:

    Step 1: Create a Cache Manifest File

    A manifest is a special text file that tells the browsers what files to store, what files not to store, and what files to replace with something else. The manifest file always starts with the words CACHE MANIFEST (in uppercase). Here is an example of a simple manifest file:

    Example

    CACHE MANIFEST
    # v1.0 : 10-08-2014
     
    CACHE:
    # pages
    index.html
     
    # styles & scripts
    css/theme.css
    js/jquery.min.js
    js/default.js
     
    # images
    /favicon.ico
    images/logo.png
     
    NETWORK:
    login.php
     
    FALLBACK:
    / /offline.html

    Explanation of code

    You might think what that code was all about. OK, let’s get straight into it. A manifest file can have three distinct sections: CACHE, NETWORK, and FALLBACK.

    • Files listed under the CACHE: section header (or immediately after the CACHE MANIFEST line) are explicitly cached after they’re downloaded for the first time.
    • Files listed under the NETWORK: section header are white-listed resources that are never cached and aren’t available offline. It means users can only access login.php page when they’r online.
    • The FALLBACK: section specifies fallback pages the browser should use in case the connection to the server cannot be established. Each entry in this section lists two URIs — first is the primary resource, the second is the fallback. For example, in our case offline.html page will be displayed if the user is offline. Also, both URIs must be from the same origin as the manifest file.
    • Lines starting with a hash symbol (#) are comment lines.

    Note: If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. After that browser checks to see whether the manifest file has been updated on the server, and if it has been updated, the browser downloads the new version of the manifest and the resources listed in it.

    Warning: Do not specify the manifest file itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.


    Step 2: Using Your Cache Manifest File

    After creating, upload your cache manifest file on the web server — make sure the web server is configured to serve the manifest files with the MIME type text/cache-manifest.

    Now to put your cache manifest into effect, you need enable it in your web pages, by adding the manifest attribute to the root <html> element, as shown below:

    Example

    <!DOCTYPE html>
    <html lang="en" manifest="example.appcache">
    <head>
        <title>Using the Application Cache</title>
    </head>
    <body>
        <!--The document content will be inserted here-->
    </body>
    </html>
  • HTML5 Web Storage

    What is Web Storage?

    The HTML5’s web storage feature lets you store some information locally on the user’s computer, similar to cookies, but it is faster and much better than cookies. However, web storage is no more secure than cookies. Please check out the tutorial on PHP cookies to learn more about cookies.

    The information stored in the web storage isn’t sent to the web server as opposed to the cookies where data sent to the server with every request. Also, where cookies let you store a small amount of data (nearly 4KB), the web storage allows you to store up to 5MB of data.

    There are two types of web storage, which differ in scope and lifetime:

    • Local storage — The local storage uses the localStorage object to store data for your entire website on a permanent basis. That means the stored local data will be available on the next day, the next week, or the next year unless you remove it.
    • Session storage — The session storage uses the sessionStorage object to store data on a temporary basis, for a single browser window or tab. The data disappears when session ends i.e. when the user closes that browser window or tab.

    Tip: The HTML5’s web storage feature is supported in all major modern web browsers like Firefox, Chrome, Opera, Safari and Internet Explorer 8 and above.


    The localStorage Object

    As stated earlier, the localStorage object stores the data with no expiration date. Each piece of data is stored in a key/value pair. The key identifies the name of the information (like ‘first_name’), and the value is the value associated with that key (say ‘Peter’). Here’s an example:

    Example

    <script>
    // Check if the localStorage object exists
    if(localStorage) {
        // Store data
        localStorage.setItem("first_name", "Peter");
        
        // Retrieve data
        alert("Hi, " + localStorage.getItem("first_name"));
    } else {
        alert("Sorry, your browser do not support local storage.");
    }
    </script>

    Example explained:

    The above JavaScript code has the following meaning:

    • localStorage.setItem(key, value) stores the value associated with a key.
    • localStorage.getItem(key) retrieves the value associated with the key.

    You can also remove a particular item from the storage if it exists, by passing the key name to the removeItem() method, like localStorage.removeItem("first_name").

    However, if you want to remove the complete storage use the clear() method, like localStorage.clear(). The clear() method takes no arguments, and simply clears all key/value pairs from localStorage at once, so think carefully before you using it.

    Note: The web storage data (both localStorage and sessionStorage) will not be available between different browsers, for example the data stored in Firefox browser will not available in Google Chrome, Safari, Internet Explorer or other browsers.


    The sessionStorage Object

    The sessionStorage object work in the same way as localStorage, except that it stores the data only for one session i.e. the data remains until the user closes that window or tab.

    Let’s try out the following example to understand how it basically works:

    Example

    <script>
    // Check if the sessionStorage object exists
    if(sessionStorage) {
        // Store data
        sessionStorage.setItem("last_name", "Parker");
        
        // Retrieve data
        alert("Hi, " + localStorage.getItem("first_name") + " " + sessionStorage.getItem("last_name"));
    } else {
        alert("Sorry, your browser do not support session storage.");
    }
    </script>
  • HTML5 Video

    Embedding Video in HTML Document

    Inserting video onto a web page was not relatively easy, because web browsers did not have a uniform standard for defining embedded media files like video.

    In this chapter we’ll demonstrates some of the many ways of adding videos on web pages, from the latest HTML5 <video> element to the popular YouTube videos.

    Using the HTML5 video Element

    The newly introduced HTML5 <video> element provides a standard way to embed video in web pages. However, the video element is relatively new, but it works in most of the modern web browsers.

    The following example simply inserts a video into the HTML document, using the browser default set of controls, with one source defined by the src attribute.

    Example

    <video controls="controls" src="media/shuttle.mp4">
        Your browser does not support the HTML5 Video element.
    </video>

    A video, using the browser default set of controls, with alternative sources.

    Example

    <video controls="controls">
        <source src="media/shuttle.mp4" type="video/mp4">
        <source src="media/shuttle.ogv" type="video/ogg">
        Your browser does not support the HTML5 Video element.
    </video>

    Using the object Element

    The <object> element is used to embed different kinds of media files into an HTML document. Initially, this element was used to insert ActiveX controls, but according to the specification, an object can be any media object such as video, audio, PDF files, Flash animations or even images.

    The following code fragment embeds a Flash video into a web page.

    Example

    <object data="media/blur.swf" width="400px" height="200px"></object>

    Only browsers or applications that support Flash will play this video.

    Warning: The <object> element is not supported widely and very much depends on the type of the object that’s being embedded. Other methods could be a better choice in many cases. iPad and iPhone device cannot display Flash videos.


    Using the embed Element

    The <embed> element is used to embed multimedia content into an HTML document.

    The following code fragment embeds a Flash video into a web page.

    Example

    <embed src="media/blur.swf" width="400px" height="200px">

    Warning: However, the <embed> element is very well supported in current web browsers and it is also defined as standard in HTML5, but your video might not played due to lack of browser support for Flash or unavailability of plugins.


    Embedding the YouTube Videos

    This is the easiest and popular way to embed videos files in the web pages. Just upload the video on YouTube and insert HTML code to display that video in your web page.

    Here’s a live example followed by the explanation of whole process:

    Step 1: Upload video

    Go to YouTube upload video page and follow the instructions to upload your video.

    Step 2: Creating the HTML Code to embed the video

    When you open your uploaded video in YouTube you will see something like the following figure at the bottom of the video. Browse and open your uploaded video in YouTube. Now look for the share button which is located just below the video as shown in the figure.

    Share YouTube Videos

    When you click the share button, a share panel will open displaying some more buttons. Now click on the Embed button, it will generate the HTML code to directly embed the video into the web pages. Just copy and paste that code into your HTML document where you want to display the video and you’re all set. By default video embedded inside an iframe.

    Share YouTube Videos

    You can further customize this embed code such as changing the video size by selecting the customization option given just below the embed-code input box.

    The following example simply embeds a video from the YouTube. Let’s try it out:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>YouTube Video</title>
    </head>
    <body>
        <iframe width="560" height="315" src="//www.youtube.com/embed/YE7VzlLtp-4" frameborder="0" allowfullscreen></iframe>
    </body>
    </html>