Introduction
- What is HTML?
HTML is the standard markup language for creating Web pages.
- A Simple HTML Document
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
- Tags
HTML tags are element names surrounded by angle brackets:
<tagname>content goes here...</tagname>
- Web Browsers
The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and display them. The browser does not display the HTML tags, but uses them to determine how to display the document.
- The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration represents the document type, and helps browsers to display web pages correctly. It must only appear once, at the top of the page (before any HTML tags). The <!DOCTYPE> declaration is not case sensitive. The <!DOCTYPE> declaration for HTML5 is:
<!DOCTYPE html>
- Versions
Since the early days of the web, there have been many versions of HTML:
Basic
- Documents
All HTML documents must start with a document type declaration: <!DOCTYPE html>. The HTML document itself begins with <html> and ends with </html>. The visible part of the HTML document is between <body> and </body>.
- Headings
HTML headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading. <h6> defines the least important heading:
<h1>This is heading 1</h1> <h2>This is heading 2</h2> <h3>This is heading 3</h3>
- Paragraphs
HTML paragraphs are defined with the <p> tag:
<p>This is a paragraph.</p>
The HTML <pre> element defines preformatted text.
The text inside a <pre> element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks:
<pre> My Bonnie lies over the ocean. My Bonnie lies over the sea. My Bonnie lies over the ocean. Oh, bring back my Bonnie to me. </pre>
- Links
HTML links are defined with the <a> tag:
<a href="https://alishoff.com/">This is a link</a>
The link's destination is specified in the href attribute. Attributes are used to provide additional information about HTML elements.
- Images
HTML images are defined with the <img> tag. The source file (src), alternative text (alt), width, and height are provided as attributes:
<img src="https://alishoff.com/uploads/5dc0fc8dca83a.png" alt="HTML" width="100" height="150">
- Buttons
HTML buttons are defined with the <button> tag:
<button>Click me</button>
- Lists
HTML lists are defined with the <ul> (unordered/bullet list) or the <ol> (ordered/numbered list) tag, followed by <li> tags (list items):
<ul> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <ol> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol>
Attributes
Attributes provide additional information about HTML elements.
Styles
Formatting
Formatting elements were designed to display special types of text:
Quotation and citation
Colors
HTML colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
- Color names
- RGB
In HTML, a color can be specified as an RGB value, using this formula:
rgb(red, green, blue)
Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.
For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0.
- HEX
In HTML, a color can be specified using a hexadecimal value in the form:
#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff (same as decimal 0-255).
For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and the others are set to the lowest value (00).
- HSL
In HTML, a color can be specified using hue, saturation, and lightness (HSL) in the form:
hsl(hue, saturation, lightness)
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.
Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.
Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white.
- RGBA
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color.
An RGBA color value is specified with:
rgba(red, green, blue, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).
- HSLA
HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity for a color.
An HSLA color value is specified with:
hsla(hue, saturation, lightness, alpha)
The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (not transparent at all).
CSS
CSS stands for Cascading Style Sheets.
CSS describes how HTML elements are to be displayed on screen, paper, or in other media.
Links
Links are found in nearly all web pages. Links allow users to click their way from page to page.
- The target Attribute
The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
Summary
Images
Image maps
The <map> tag defines an image-map. An image-map is an image with clickable areas.
<img src="workplace.jpg" alt="Workplace" usemap="#workmap"> <map name="workmap"> <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.html"> <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.html"> <area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.html"> </map>
- Shape
You must define the shape of the area, and you can choose one of these values:
- Coordinates
You must define some coordinates to be able to place the clickable area onto the image.
The coordinates come in pairs, one for the x-axis and one for the y-axis.
The coordinates 34, 44 is located 34 pixels from the left margin and 44 pixels from the top.
Picture element
The picture element allows us to display different pictures for different devices or screen sizes.
The <picture> element contains a number of <source> elements, each referring to different image sources. This way the browser can choose the image that best fits the current view and/or device.
Each <source> element have attributes describing when their image is the most suitable.
Show different images on different screen sizes:
<picture> <source media="(min-width: 650px)" srcset="img_food.jpg"> <source media="(min-width: 465px)" srcset="img_car.jpg"> <img src="img_girl.jpg"> </picture>
Always specify an <img> element as the last child element of the <picture> element. The <img> element is used by browsers that do not support the <picture> element, or if none of the <source> tags matched.
Tables
Lists
Blocks
Every HTML element has a default display value depending on what type of element it is.
The two display values are: block and inline.
- Block-level elements
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
The <div> element is a block-level element.
- Inline elements
An inline element does not start on a new line and only takes up as much width as necessary.
The <span> element is a inline element.
File paths
A file path describes the location of a file in a web site's folder structure.
File paths are used when linking to external files like:
- Absolute file paths
An absolute file path is the full URL to an internet file.
- Relative file paths
A relative file path points to a file relative to the current page.
- Best practice
It is best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.
Head
The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag.
HTML metadata is data about the HTML document. Metadata is not displayed.
Metadata typically define the document title, character set, styles, scripts, and other meta information.
The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.
- <meta> element
The <meta> element is used to specify which character set is used, page description, keywords, author, and other metadata.
Metadata is used by browsers (how to display content), by search engines (keywords), and other web services.
Define the character set used:
<meta charset="UTF-8">
Define a description of your web page:
<meta name="description" content="Free Web tutorials">
Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, JavaScript">
Define the author of a page:
<meta name="author" content="John Doe">
Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">
Example of <meta> tags:
<meta charset="UTF-8"> <meta name="description" content="Free Web tutorials"> <meta name="keywords" content="HTML,CSS,XML,JavaScript"> <meta name="author" content="John Doe">
- Setting the viewport
HTML5 introduced a method to let web designers take control over the viewport, through the <meta> tag.
The viewport is the user's visible area of a web page. It varies with the device, and will be smaller on a mobile phone than on a computer screen.
You should include the following <meta> viewport element in all your web pages:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
A <meta> viewport element gives the browser instructions on how to control the page's dimensions and scaling.
The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.
- <base> element
The <base> element specifies the base URL and base target for all relative URLs in a page.
<base href="https://alishoff.com/images/" target="_blank">
Layout
There are five different ways to create multicolumn layouts. Each way has its pros and cons:
Computer code elements
URL encode
A URL is another word for a web address.
A URL can be composed of words (w3schools.com), or an Internet Protocol (IP) address (192.68.20.50).
Most people enter the name when surfing, because names are easier to remember than numbers.
Web browsers request pages from web servers by using a URL.
A Uniform Resource Locator (URL) is used to address a document (or other data) on the web.
A web address like https://www.w3schools.com/html/default.asp follows these syntax rules:
scheme://prefix.domain:port/path/filename
Explanation:
- Common URL schemes
XHTML
XHTML is HTML written as XML.
- The most important differences from HTML:
Document structure
XHTML elements
XHTML attributes
- How to convert from HTML to XHTML
Forms
The HTML <form> element defines a form that is used to collect user input.
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
- The method attribute
The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data.
When to use GET?
The default method when submitting form data is GET.
However, when GET is used, the submitted form data will be visible in the page address field:
/action_page.php?firstname=Mickey&lastname=Mouse
Notes on GET:
When to use POST?
Always use POST if the form data contains sensitive or personal information. The POST method does not display the submitted form data in the page address field.
Notes on POST:
- Here is the list of all <form> attributes:
- Form elements
- Here are the different input types you can use in HTML
- Here is a list of some common input restrictions:
HTML5
- What is new in HTML5?
The DOCTYPE declaration for HTML5 is very simple:
<!DOCTYPE html>
The character encoding (charset) declaration is also very simple:
<meta charset="UTF-8">
- New HTML5 elements
The most interesting new HTML5 elements are:
New semantic elements like <header>, <footer>, <article>, and <section>.
New attributes of form elements like number, date, time, calendar, and range.
New graphic elements: <svg> and <canvas>.
New multimedia elements: <audio> and <video>.
- New HTML5 APIs (Application Programming Interfaces)
The most interesting new APIs in HTML5 are:
- Removed elements in HTML5
The following HTML4 elements have been removed in HTML5:
History
Since the early days of the World Wide Web, there have been many versions of HTML:
From 1991 to 1999, HTML developed from version 1 to version 4.
In year 2000, the World Wide Web Consortium (W3C) recommended XHTML 1.0. The XHTML syntax was strict, and the developers were forced to write valid and "well-formed" code.
In 2004, W3C's decided to close down the development of HTML, in favor of XHTML.
In 2004, WHATWG (Web Hypertext Application Technology Working Group) was formed. The WHATWG wanted to develop HTML, consistent with how the web was used, while being backward compatible with older versions of HTML.
In 2004 - 2006, the WHATWG gained support by the major browser vendors.
In 2006, W3C announced that they would support WHATWG.
In 2008, the first HTML5 public draft was released.
In 2012, WHATWG and W3C decided on a separation:
WHATWG wanted to develop HTML as a "Living Standard". A living standard is always updated and improved. New features can be added, but old functionality cannot be removed.
The WHATWG HTML5 Living Standard was published in 2012, and is continuously updated.
The W3C HTML5 Recommendation was released 28 October 2014.
The W3C HTML5.1 2nd Edition Recommendation was released 3 October 2017.
The W3C HTML5.2 Recommendation was released 14 December 2017.
HTML5 browser support
HTML5 is supported in all modern browsers.
In addition, all browsers, old and new, automatically handle unrecognized elements as inline elements.
Because of this, you can "teach" older browsers to handle "unknown" HTML elements.
- Define semantic elements as block elements
HTML5 defines eight new semantic elements. All these are block-level elements.
To secure correct behavior in older browsers, you can set the CSS display property for these HTML elements to block:
header, section, footer, aside, nav, main, article, figure { display: block; }
- Add new elements to HTML
You can also add new elements to an HTML page with a browser trick.
This example adds a new element called <myHero> to an HTML page, and defines a style for it:
<!DOCTYPE html> <html> <head> <script>document.createElement("myHero")</script> <style> myHero { display: block; background-color: #dddddd; padding: 50px; font-size: 30px; } </style> </head> <body> <h1>A Heading</h1> <myHero>My Hero Element</myHero> </body> </html>
The JavaScript statement document.createElement("myHero") is needed to create a new element in IE 9, and earlier.
- Problem with Internet Explorer 8
You could use the solution described above for all new HTML5 elements.
However, IE8 (and earlier) does not allow styling of unknown elements!
Thankfully, Sjoerd Visscher created the HTML5Shiv! The HTML5Shiv is a JavaScript workaround to enable styling of HTML5 elements in versions of Internet Explorer prior to version 9.
You will require the HTML5Shiv to provide compatibility for IE Browsers older than IE 9.
- Syntax for HTML5Shiv
The HTML5Shiv is placed within the <head> tag.
The HTML5Shiv is a javascript file that is referenced in a <script> tag.
You should use the HTML5Shiv when you are using the new HTML5 elements such as: <article>, <section>, <aside>, <nav>, <footer>.
You can download the latest version of HTML5shiv from github.
Syntax
<head> <!--[if lt IE 9]> <script src="/js/html5shiv.js"></script> <![endif]--> </head>
- HTML5Shiv example
If you do not want to download and store the HTML5Shiv on your site, you could reference the version found on the CDN site.
The HTML5Shiv script must be placed in the <head> element, after any stylesheets:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <![endif]--> </head> <body> <section> <h1>Famous Cities</h1> <article> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </article> <article> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </article> <article> <h2>Tokyo</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </article> </section> </body> </html>
HTML5 new elements
Below is a list of the new HTML5 elements, and a description of what they are used for.
- New semantic/structural elements
HTML5 offers new elements for better document structure:
- New form elements
- New input types
- New input attributes
- New attribute syntax
HTML5 allows four different syntaxes for attributes.
This example demonstrates the different syntaxes used in an <input> tag:
- HTML5 graphics
- New media elements
Canvas
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
- Canvas examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.
The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.
- Draw a line
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.moveTo(0,0); ctx.lineTo(200,100); ctx.stroke(); </script> </body> </html>
- Draw a circle
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(95,50,40,0,2*Math.PI); ctx.stroke(); </script> </body> </html>
- Draw a Text
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font = "30px Arial"; ctx.fillText("Hello World",10,50); </script> </body> </html>
SVG
The HTML <svg> element is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
- Circle
<!DOCTYPE html> <html> <body> <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> Sorry, your browser does not support inline SVG. </svg> </body> </html>
- Rectangle
<!DOCTYPE html> <html> <body> <svg width="400" height="100"> <rect width="400" height="100" style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" /> Sorry, your browser does not support inline SVG. </svg> </body> </html>
- Differences between SVG and Canvas
SVG is a language for describing 2D graphics in XML.
Canvas draws 2D graphics, on the fly (with a JavaScript).
SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.
In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.
Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.
- Comparison of Canvas and SVG
Canvas
SVG
Multimedia
Multimedia on the web is sound, music, videos, movies, and animations.
- Browser support
The first web browsers had support for text only, limited to a single font in a single color.
Later came browsers with support for colors and fonts, and images!
Audio, video, and animation have been handled differently by the major browsers. Different formats have been supported, and some formats require extra helper programs (plug-ins) to work.
Hopefully this will become history. HTML5 multimedia promises an easier future for multimedia.
- Multimedia formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file extension.
Multimedia files have formats and different extensions like: .swf, .wav, .mp3, .mp4, .mpg, .wmv, and .avi.
- Video formats:
Only MP4, WebM, and Ogg video are supported by the HTML5 standard.
- Audio formats:
Only MP3, WAV, and Ogg audio are supported by the HTML5 standard.
Video
Before HTML5, a video could only be played in a browser with a plug-in (like flash).
The HTML5 <video> element specifies a standard way to embed a video in a web page.
To show a video in HTML, use the <video> element:
<!DOCTYPE html> <html> <body> <video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> </body> </html>
The controls attribute adds video controls, like play, pause, and volume.
It is a good idea to always include width and height attributes. If height and width are not set, the page might flicker while the video loads.
The <source> element allows you to specify alternative video files which the browser may choose from. The browser will use the first recognized format.
The text between the <video> and </video> tags will only be displayed in browsers that do not support the <video> element.
To start a video automatically use the autoplay attribute:
<!DOCTYPE html> <html> <body> <video width="320" height="240" autoplay> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> <p><b>Note:</b> The autoplay attribute does not work on some mobile devices.</p> </body> </html>
- Media types
- Methods, Properties, and Events
HTML5 defines DOM methods, properties, and events for the <video> element.
This allows you to load, play, and pause videos, as well as setting duration and volume.
There are also DOM events that can notify you when a video begins to play, is paused, etc.
<!DOCTYPE html> <html> <body> <div style="text-align:center"> <button onclick="playPause()">Play/Pause</button> <button onclick="makeBig()">Big</button> <button onclick="makeSmall()">Small</button> <button onclick="makeNormal()">Normal</button> <br><br> <video id="video" width="420"> <source src="mov_bbb.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> Your browser does not support HTML5 video. </video> </div> <script> var myVideo = document.getElementById("video"); function playPause() { if (myVideo.paused) { myVideo.play(); } else { myVideo.pause(); } } function makeBig() { myVideo.width = 560; } function makeSmall() { myVideo.width = 320; } function makeNormal() { myVideo.width = 420; } </script> </body> </html>
Audio
Before HTML5, audio files could only be played in a browser with a plug-in (like flash).
The HTML5 <audio> element specifies a standard way to embed audio in a web page.
To play an audio file in HTML, use the <audio> element:
<!DOCTYPE html> <html> <body> <audio controls> <source src="horse.ogg" type="audio/ogg"> <source src="horse.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html>
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.
The text between the <audio> and </audio> tags will only be displayed in browsers that do not support the <audio> element.
- Media types
- Methods, Properties, and Events
HTML5 defines DOM methods, properties, and events for the <audio> element.
This allows you to load, play, and pause audios, as well as set duration and volume.
There are also DOM events that can notify you when an audio begins to play, is paused, etc.
Geolocation
The HTML Geolocation API is used to get the geographical position of a user.
Since this can compromise privacy, the position is not available unless the user approves it.
Note: Geolocation is most accurate for devices with GPS, like smartphone.
- Using HTML Geolocation
The getCurrentPosition() method is used to return the user's position.
The example below returns the latitude and longitude of the user's position:
<!DOCTYPE html> <html> <body> <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button> <p id="demo"></p> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script> </body> </html>
Example explained:
The example above is a very basic Geolocation script, with no error handling.
- Handling Errors and Rejections
The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:
<!DOCTYPE html> <html> <body> <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button> <p id="demo"></p> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; } } </script> </body> </html>
- Displaying the result in a map
To display the result in a map, you need access to a map service, like Google Maps.
In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):
function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY"; document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>"; }
- The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:
- Geolocation Object - other interesting methods
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.
In HTML5, drag and drop is part of the standard: Any element can be draggable.
The example below is a simple drag and drop example:
<!DOCTYPE HTML> <html> <head> <style> #div1 { width: 350px; height: 70px; padding: 10px; border: 1px solid #aaaaaa; } </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <p>Drag the W3Schools image into the rectangle:</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br> <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </body> </html>
- Make an element draggable
First of all: To make an element draggable, set the draggable attribute to true:
<img draggable="true">
- What to drag - ondragstart and setData()
Then, specify what should happen when the element is dragged.
In the example above, the ondragstart attribute calls a function, drag(event), that specifies what data to be dragged.
The dataTransfer.setData() method sets the data type and the value of the dragged data:
function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
In this case, the data type is "text" and the value is the id of the draggable element ("drag1").
- Where to drop - ondragover
The ondragover event specifies where the dragged data can be dropped.
By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event:
event.preventDefault()
- Do the drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); }
Code explained:
Web storage
With web storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
HTML web storage provides two objects for storing data on the client:
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") { // Code for localStorage/sessionStorage. } else { // Sorry! No Web Storage support.. }
- The localStorage object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
<!DOCTYPE html> <html> <body> <div id="result"></div> <script> // Check browser support if (typeof(Storage) !== "undefined") { // Store localStorage.setItem("lastname", "Smith"); // Retrieve document.getElementById("result").innerHTML = localStorage.getItem("lastname"); } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage..."; } </script> </body> </html>
Example explained:
The example above could also be written like this:
// Store localStorage.lastname = "Smith"; // Retrieve document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!
<!DOCTYPE html> <html> <head> <script> function clickCounter() { if (typeof(Storage) !== "undefined") { if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount)+1; } else { localStorage.clickcount = 1; } document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s)."; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; } } </script> </head> <body> <p><button onclick="clickCounter()" type="button">Click me!</button></p> <div id="result"></div> <p>Click the button to see the counter increase.</p> <p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p> </body> </html>
- The sessionStorage object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current session:
<!DOCTYPE html> <html> <head> <script> function clickCounter() { if (typeof(Storage) !== "undefined") { if (sessionStorage.clickcount) { sessionStorage.clickcount = Number(sessionStorage.clickcount)+1; } else { sessionStorage.clickcount = 1; } document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; } } </script> </head> <body> <p><button onclick="clickCounter()" type="button">Click me!</button></p> <div id="result"></div> <p>Click the button to see the counter increase.</p> <p>Close the browser tab (or window), and try again, and the counter is reset.</p> </body> </html>
Web workers
A web worker is a JavaScript running in the background, without affecting the performance of the page.
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
The example below creates a simple web worker that count numbers in the background:
<!DOCTYPE html> <html> <body> <p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p> <script> var w; function startWorker() { if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers..."; } } function stopWorker() { w.terminate(); w = undefined; } </script> </body> </html>
- Check web worker support
Before creating a web worker, check whether the user's browser supports it:
if (typeof(Worker) !== "undefined") { // Yes! Web worker support! // Some code..... } else { // Sorry! No Web Worker support.. }
- Create a web worker file
Now, let's create our web worker in an external JavaScript.
Here, we create a script that counts. The script is stored in the "demo_workers.js" file:
var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()", 500); } timedCount();
The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.
Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.
- Create a web worker object
Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "demo_workers.js":
if (typeof(w) == "undefined") { w = new Worker("demo_workers.js"); }
Then we can send and receive messages from the web worker.
Add an "onmessage" event listener to the web worker.
w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; };
When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.
- Terminate a web worker
When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.
To terminate a web worker, and free browser/computer resources, use the terminate() method:
w.terminate();
- Reuse the web worker
If you set the worker variable to undefined, after it has been terminated, you can reuse the code:
w = undefined;
- Web workers and the DOM
Since web workers are in external files, they do not have access to the following JavaScript objects:
SSE - Server-Sent Events
Server-Sent Events allow a web page to get updates from a server.
A server-sent event is when a web page automatically gets updates from a server.
This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.
- Receive Server-Sent Event notifications
The EventSource object is used to receive server-sent event notifications:
<!DOCTYPE html> <html> <body> <h1>Getting server updates</h1> <div id="result"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html>
Example explained:
- Check Server-Sent Events support
if(typeof(EventSource) !== "undefined") { // Yes! Server-sent events support! // Some code..... } else { // Sorry! No server-sent events support.. }
- Server-Side code example
For the example above to work, you need a server capable of sending data updates (like PHP).
The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.
Code in PHP (demo_sse.php):
header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n"; flush();
Code explained:
- The EventSource object
In the examples above we used the onmessage event to get messages. But other events are also available: