HTML – Web Storage ”; Previous Next HTML Web Storage is a mechanism that helps web applications to stores data locally in users browsers. Types of Web Storage HTML introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the client side, without sending it to the server. Session Storage Local Storage To use session storage or local storage in web application, we can access them through the window.sessionStorage and window.localStorage properties respectively. Examples of HTML Web Storage Here are some example that shows different ways of web storage in HTML. Session Storage The Session Storage is temporary and it gets cleared when the page session ends, which happens when the browser tab or window is closed. The data stored in session storage is specific to each tab or window. HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window, i.e., session and as soon as you close the window, the session would be lost. Example Following is the code which would set a session variable and access that variable. <!DOCTYPE html> <html> <body> <script type=”text/javascript”> if( sessionStorage.hits ){ sessionStorage.hits = Number(sessionStorage.hits) +1; } else { sessionStorage.hits = 1; } document.write(“Total Hits :” + sessionStorage.hits ); </script> <p> Refresh the page to increase number of hits. </p> <p> Close the window and open it again and check the result. </p> </body> </html> Local Storage The Local Storage is designed for storage that spans multiple windows, and lasts beyond the current session. It does not expire and remains in the browser until it is manually deleted by the user or by the web application. In particular, web applications may wish to store megabytes of user data, such as entire user-authored documents or a user”s mailbox, on the client side for performance reasons. Again, cookies do not handle this case well, because they are transmitted with every request. HTML5 introduces the localStorage attribute which would be used to access a page”s local storage area without no time limit and this local storage will be available whenever you would use that page. Example Following is the code which would set a local storage variable and access that variable every time this page is accessed, even next time, when you open the window; <!DOCTYPE html> <html> <body> <script type=”text/javascript”> if( localStorage.hits ){ localStorage.hits = Number(localStorage.hits) +1; } else { localStorage.hits = 1; } document.write(“Total Hits :” + localStorage.hits ); </script> <p> Refresh the page to increase number of hits. </p> <p> Close the window and open it again and check the result. </p> </body> </html> Delete Web Storage Storing sensitive data on local machine could be dangerous and could leave a security hole. The Session Storage Data would be deleted by the browsers immediately after the session gets terminated. However, to clear a local storage setting, we need to call localStorage.remove(”key”); where ”key” is the key of the value we want to remove. If we want to clear all settings, the localStorage.clear() method can be called. Example Following is the code which would clear complete local storage; <!DOCTYPE html> <html> <body> <script type=”text/javascript”> localStorage.clear(); // Reset number of hits. if( localStorage.hits ){ localStorage.hits = Number(localStorage.hits) +1; } else { localStorage.hits = 1; } document.write(“Total Hits :” + localStorage.hits ); </script> <p> Refreshing the page would not to increase hit counter. </p> <p> Close the window and open it again and check the result. </p> </body> </html> Reson to birng Web Storage over Cookies The web storage is introduced to overcome the following drawbacks of cookies. Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data. Cookies are included with every HTTP request, thereby sending data unencrypted over the internet. Cookies are limited to about 4 KB of data. Not enough to store required data. Print Page Previous Next Advertisements ”;
Category: html5
HTML5 – Web RTC
HTML – Web RTC ”; Previous Next Web RTC introduced by World Wide Web Consortium (W3C) that supports browser-to-browser applications for voice calling, video chat, and P2P file sharing. The web RTC implements three API”s as shown below − MediaStream − get access to the user”s camera and microphone. RTCPeerConnection − get access to audio or video calling facility. RTCDataChannel − get access to peer-to-peer communication. MediaStream The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here. The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone. Sample code of MediaStream function gotStream(stream) { window.AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContext(); // Create an AudioNode from the stream var mediaStreamSource = audioContext.createMediaStreamSource(stream); // Connect it to destination to hear yourself // or any other node for processing! mediaStreamSource.connect(audioContext.destination); } navigator.getUserMedia({audio:true}, gotStream); Session Control, Network & Media Information Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. Sample code of createSignalingChannel() var signalingChannel = createSignalingChannel(); var pc; var configuration = …; // run start(true) to initiate a call function start(isCaller) { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = function (evt) { signalingChannel.send(JSON.stringify({ “candidate”: evt.candidate })); }; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) { remoteView.src = URL.createObjectURL(evt.stream); }; // get the local stream, show it in the local video element and send it navigator.getUserMedia({ “audio”: true, “video”: true }, function (stream) { selfView.src = URL.createObjectURL(stream); pc.addStream(stream); if (isCaller) pc.createOffer(gotDescription); else pc.createAnswer(pc.remoteDescription, gotDescription); function gotDescription(desc) { pc.setLocalDescription(desc); signalingChannel.send(JSON.stringify({ “sdp”: desc })); } }); } signalingChannel.onmessage = function (evt) { if (!pc) start(false); var signal = JSON.parse(evt.data); if (signal.sdp) pc.setRemoteDescription(new RTCSessionDescription(signal.sdp)); else pc.addIceCandidate(new RTCIceCandidate(signal.candidate)); }; Print Page Previous Next Advertisements ”;
HTML5 – Web SQL Database
HTML – Web SQL Database ”; Previous Next The Web SQL Database API isn”t actually part of the HTML specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL. I”m assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial. Web SQL Database will work in latest version of Safari, Chrome and Opera. The Core Methods There are following three core methods defined in the spec that I am going to cover in this tutorial − openDatabase − This method creates the database object either using existing database or creating new one. transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation. executeSql − This method is used to execute actual SQL query. Opening Database The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist. To create and open a database, use the following code − var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); The above method took the following five parameters − Database name Version number Text description Size of database Creation callback The last and 5th argument, creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned. Executing queries To execute a query you use the database.transaction() function. This function needs a single argument, which is a function that takes care of actually executing the query as follows − var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(”CREATE TABLE IF NOT EXISTS LOGS (id unique, log)”); }); The above query will create a table called LOGS in ”mydb” database. INSERT Operation To create enteries into the table we add simple SQL query in the above example as follows − var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(”CREATE TABLE IF NOT EXISTS LOGS (id unique, log)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (1, “foobar”)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (2, “logmsg”)”); }); We can pass dynamic values while creating entering as follows − var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(”CREATE TABLE IF NOT EXISTS LOGS (id unique, log)”); tx.executeSql(”INSERT INTO LOGS (id,log) VALUES (?, ?”), [e_id, e_log]; }); Here e_id and e_log are external variables, and executeSql maps each item in the array argument to the “?”s. READ Operation To read already existing records we use a callback to capture the results as follows − var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(”CREATE TABLE IF NOT EXISTS LOGS (id unique, log)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (1, “foobar”)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (2, “logmsg”)”); }); db.transaction(function (tx) { tx.executeSql(”SELECT * FROM LOGS”, [], function (tx, results) { var len = results.rows.length, i; msg = “<p>Found rows: ” + len + “</p>”; document.querySelector(”#status”).innerHTML += msg; for (i = 0; i < len; i++) { alert(results.rows.item(i).log ); } }, null); }); Complete Example So finally, let us keep this example in a full-fledged HTML document as follows and try to run it with Safari browser. <!DOCTYPE HTML> <html> <head> <script type = “text/javascript”> var db = openDatabase(”mydb”, ”1.0”, ”Test DB”, 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql(”CREATE TABLE IF NOT EXISTS LOGS (id unique, log)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (1, “foobar”)”); tx.executeSql(”INSERT INTO LOGS (id, log) VALUES (2, “logmsg”)”); msg = ”<p>Log message created and row inserted.</p>”; document.querySelector(”#status”).innerHTML = msg; }) db.transaction(function (tx) { tx.executeSql(”SELECT * FROM LOGS”, [], function (tx, results) { var len = results.rows.length, i; msg = “<p>Found rows: ” + len + “</p>”; document.querySelector(”#status”).innerHTML += msg; for (i = 0; i < len; i++) { msg = “<p><b>” + results.rows.item(i).log + “</b></p>”; document.querySelector(”#status”).innerHTML += msg; } }, null); }); </script> </head> <body> <div id = “status” name = “status”>Status Message</div> </body> </html> When we run the above code, it will generate an output consisting of the text displayed on the webpage. html_deprecated_tags.htm Print Page Previous Next Advertisements ”;
HTML5 – Audio & Video
HTML – <audio> Tag ”; Previous Next HTML <audio> tag is used to embed audio files on a website. It enables the direct playback of audio files within a web browser without the requirement for extra plugins. The audio file should be encoded using certain codes because all web browsers do not support all audio formats. Syntax <audio> <source src=” ” type=” “> </audio> Attribute HTML audio tag supports Global and Event attributes of HTML. And some specific attributes as well which are listed bellow. Attribute Value Description autoplay autoplay This Boolean attribute if specified, the audio will automatically begin to play back as soon as it can do so without stopping to finish loading the data. muted muted Specifies that the audio should be muted. controls controls If this attribute is present, it will allow the user to control audio playback, including volume, seeking, and pause/resume playback. loop loop This Boolean attribute if specified, will allow audio automatically seek back to the start after reaching at the end. preload autometadatanone This attribute specifies that the audio will be loaded at page load, and ready to run. Ignored if autoplay is present. src URL The URL of the audio to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed. Examples of HTML audio Tag Bellow examples will illustrate the usage of audio tag. Where, when and how to use it to render audio player and how we can manipulate audio player using CSS. Embedding Audio Element Following is an example where we are going to use the <audio> tag to add a music file to the webpage. <!DOCTYPE html> <html> <body style=”background-color:#D5F5E3”> <audio controls> <source src= “https://samplelib.com/lib/preview/mp3/sample-3s.mp3″ type=”audio/mpeg”> </audio> </body> </html> Autoplay Audio after Page load Consider another scenario where we are going to add the autoplay attribute to the <audio> tag. <!DOCTYPE html> <html> <body style=”background-color:#E8DAEF”> <audio controls autoplay> <source src= “https://samplelib.com/lib/preview/mp3/sample-3s.mp3″ type=”audio/mpeg”> </audio> </body> </html> Muted Audio element with Autoplay Let’s look at another example where we are going to use the muted attribute to the <audio> tag along with the autoplay. <!DOCTYPE html> <html> <body style=”background-color:#CCCCFF”> <audio controls autoplay muted> <source src= “https://samplelib.com/lib/preview/mp3/sample-3s.mp3″ type=”audio/mpeg”> </audio> </body> </html> Audio playing on a loop In the following example, we are going to use the <audio> tag along with the loop attribute. <!DOCTYPE html> <html> <body style=”background-color:#FCF3CF “> <audio controls autoplay loop> <source src= “https://samplelib.com/lib/preview/mp3/sample-3s.mp3″ type=”audio/mpeg”> </audio> </body> </html> Supported Browsers Tag audio Yes 4.0 Yes 9.0 Yes 3.5 Yes 3.1 Yes 11.5 html_tags_reference.htm Print Page Previous Next Advertisements ”;
HTML5 – Web Forms 2.0
HTML5 – Web Forms 2.0 ”; Previous Next Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free us from a great deal of tedious scripting and styling that was required in HTML4. The <input> element in HTML4 HTML4 input elements use the type attribute to specify the data type.HTML4 provides following types − Sr.No. Type & Description 1 text A free-form text field, nominally free of line breaks. 2 password A free-form text field for sensitive information, nominally free of line breaks. 3 checkbox A set of zero or more values from a predefined list. 4 radio An enumerated value. 5 submit A free form of button initiates form submission. 6 file An arbitrary file with a MIME type and optionally a file name. 7 image A coordinate, relative to a particular image”s size, with the extra semantic that it must be the last value selected and initiates form submission. 8 hidden An arbitrary string that is not normally displayed to the user. 9 select An enumerated value, much like the radio type. 10 textarea A free-form text field, nominally with no line break restrictions. 11 button A free form of button which can initiates any event related to button. Following is the simple example of using labels, radio buttons, and submit buttons − … <form action = “http://example.com/cgiscript.pl” method = “post”> <p> <label for = “firstname”>first name: </label> <input type = “text” id = “firstname”><br /> <label for = “lastname”>last name: </label> <input type = “text” id = “lastname”><br /> <label for = “email”>email: </label> <input type = “text” id = “email”><br> <input type = “radio” name = “sex” value = “male”> Male<br> <input type = “radio” name = “sex” value = “female”> Female<br> <input type = “submit” value = “send”> <input type = “reset”> </p> </form> … The <input> element in HTML5 Apart from the above-mentioned attributes, HTML5 input elements introduced several new values for the type attribute. These are listed below. NOTE − Try all the following example using latest version of Opera browser. Sr.No. Type & Description 1 datetime A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC. 2 datetime-local A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information. 3 date A date (year, month, day) encoded according to ISO 8601. 4 month A date consisting of a year and a month encoded according to ISO 8601. 5 week A date consisting of a year and a week number encoded according to ISO 8601. 6 time A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601. 7 number It accepts only numerical value. The step attribute specifies the precision, defaulting to 1. 8 range The range type is used for input fields that should contain a value from a range of numbers. 9 email It accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in [email protected] format. 10 url It accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format. The <output> element HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script. You can use the for attribute to specify a relationship between the output element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the for attribute is a space-separated list of IDs of other elements. Live Demo <!DOCTYPE HTML> <html> <head> <script type = “text/javascript”> function showResult() { x = document.forms[“myform”][“newinput”].value; document.forms[“myform”][“result”].value = x; } </script> </head> <body> <form action = “/cgi-bin/html5.cgi” method = “get” name = “myform”> Enter a value : <input type = “text” name = “newinput” /> <input type = “button” value = “Result” onclick = “showResult();” /> <output name = “result”></output> </form> </body> </html> It will produce the following result − The placeholder attribute HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provide a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds. Here is the simple syntax for placeholder attribute − <input type = “text” name = “search” placeholder = “search the web”/> This attribute is supported by latest versions of Mozilla, Safari and Crome browsers only. Live Demo <!DOCTYPE HTML> <html> <body> <form action = “/cgi-bin/html5.cgi” method = “get”> Enter email : <input type = “email” name = “newinput” placeholder = “[email protected]”/> <input type = “submit” value = “submit” /> </form> </body> </html> This will produce the following result − The autofocus attribute This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field. HTML5 introduced a new attribute called autofocus which would be used as follows − <input type = “text” name = “search” autofocus/> This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only. <!DOCTYPE HTML> <html> <body> <form action = “/cgi-bin/html5.cgi” method = “get”> Enter email : <input type = “text” name = “newinput” autofocus/> <p>Try to submit using Submit button</p> <input type = “submit” value = “submit” /> </form> </body> </html> The required attribute Now you do not need to have JavaScript for client-side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have
HTML5 – Home
HTML5 Tutorial PDF Version Quick Guide Resources Job Search Discussion HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a markup language. In this tutorial, we will discuss the features of HTML5 and how to use it in practice. Audience This tutorial has been designed for beginners in HTML5 to make them understand the basic-to-advanced concepts of the subject. Prerequisites Before starting this tutorial, you should have a basic understanding of HTML and its tags. Print Page Previous Next Advertisements ”;
HTML5 – Web CORS
HTML – CORS ”; Previous Next Cross-origin resource sharing (CORS) is a mechanism to allows to load the restricted resources from another domain in web browser For example, suppose we click on HTML5 video player in HTML5 demo section. First, it will ask camera permission, if user allow the permission then only it will open the camera otherwise not. Making a CORS request The modern browsers like Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object. function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if (“withCredentials” in xhr) { // Check if the XMLHttpRequest object has a “withCredentials” property. // “withCredentials” only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != “undefined”) { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE”s way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; } var xhr = createCORSRequest(”GET”, url); if (!xhr) { throw new Error(”CORS not supported”); } Event handles in CORS Sr.No. Event Handler & Description 1 onloadstart Starts the request 2 onprogress Loads the data and send the data 3 onabort Abort the request 4 onerror request has failed 5 onload request load successfully 6 ontimeout time out has happened before request could complete 7 onloadend When the request is complete either successful or failure Example of onload or onerror event xhr.onload = function() { var responseText = xhr.responseText; // process the response. console.log(responseText); }; xhr.onerror = function() { console.log(”There was an error!”); }; Example of CORS with handler Below example will show the example of makeCorsRequest() and onload handler // Create the XHR object. function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if (“withCredentials” in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, true); } else if (typeof XDomainRequest != “undefined”) { // XDomainRequest for IE. xhr = new XDomainRequest(); xhr.open(method, url); } else { // CORS not supported. xhr = null; } return xhr; } // Helper method to parse the title tag from the response. function getTitle(text) { return text.match(”<title>(.*)?</title>”)[1]; } // Make the actual CORS request. function makeCorsRequest() { // All HTML5 Rocks properties support CORS. var url = ”http://www.tutorialspoint.com”; var xhr = createCORSRequest(”GET”, url); if (!xhr) { alert(”CORS not supported”); return; } // Response handlers. xhr.onload = function() { var text = xhr.responseText; var title = getTitle(text); alert(”Response from CORS request to ” + url + ”: ” + title); }; xhr.onerror = function() { alert(”Woops, there was an error making the request.”); }; xhr.send(); } Print Page Previous Next Advertisements ”;
HTML5 – Attributes
HTML5 – Attributes ”; Previous Next As explained in the previous chapter, elements may contain attributes that are used to set various properties of an element. Some attributes are defined globally and can be used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown below in the example. Following is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named class using a value of “example” − <div class = “example”>…</div> Attributes may only be specified within start tags and must never be used in end tags. HTML5 attributes are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase. Standard Attributes The attributes listed below are supported by almost all the HTML 5 tags. Attribute Options Function accesskey User Defined Specifies a keyboard shortcut to access an element. align right, left, center Horizontally aligns tags background URL Places an background image behind an element bgcolor numeric, hexidecimal, RGB values Places a background color behind an element class User Defined Classifies an element for use with Cascading Style Sheets. contenteditable true, false Specifies if the user can edit the element”s content or not. contextmenu Menu id Specifies the context menu for an element. data-XXXX User Defined Custom attributes. Authors of a HTML document can define their own attributes. Must start with “data-“. draggable true,false, auto Specifies whether or not a user is allowed to drag an element. height Numeric Value Specifies the height of tables, images, or table cells. hidden hidden Specifies whether element should be visible or not. id User Defined Names an element for use with Cascading Style Sheets. item List of elements Used to group elements. itemprop List of items Used to group items. spellcheck true, false Specifies if the element must have it”s spelling or grammar checked. style CSS Style sheet Specifies an inline style for an element. subject User define id Specifies the element”s corresponding item. tabindex Tab number Specifies the tab order of an element. title User Defined “Pop-up” title for your elements. valign top, middle, bottom Vertically aligns tags within an HTML element. width Numeric Value Specifies the width of tables, images, or table cells. For a complete list of HTML5 Tags and related attributes, please check our reference to HTML5 Tags. Custom Attributes A new feature being introduced in HTML 5 is the addition of custom data attributes. A custom data attribute starts with data- and would be named based on your requirement. Here is a simple example − <div class = “example” data-subject = “physics” data-level = “complex”> … </div> The above code will be perfectly valid HTML5 with two custom attributes called datasubject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes. Print Page Previous Next Advertisements ”;
HTML5 – MathML
HTML – MathML ”; Previous Next HTML MathML (Mathematical Markup Language) is used to embed mathematical equations and chemical reaction equations into HTML document. Mathematical Markup Language (MathML) Mathematical Markup Language is a XML based markup language introduced in 2015. It helps to represent complex mathematical formula in human readable format. This representation also helps software to understand context of the equation. To embed MathML elements inside a web page, we can use the HTML <math> tag. HTML MathML Elements The following table contains a list of MathML elements used in HTML: Element Description <math> It is the top level tag (root) of all MathML elements. <mrow> It indicates row of a given table or matrix. <msqrt> It displays square roots symbol in an expression. <msub> It is used for adding subscript in a given expression. <msup> It is used for adding superscript in a given expression. <mo> It represents operators such as equal to, comma and so on. <mi> It represents identifiers such as variable or constant. <mtable> It is used for creating table or matrix. <mtr> It is used for table row or matrix row. <mtd> It is used to enter data in a cell of a table or a matrix. Purpose of HTML MathML MathML is helpful to display formula in technical and mathematical webpages. This ensures clear math content in e-learning materials, scientific papers and complex algorithms. MathML is only supported in Google Chrome and Mozilla Firefox browsers. Please make sure that your browser supports MathML before testing it. Examples MathML in HTML Following are some examples that illustrates how to use MathML elements in HTML. Pythagorean theorem Using MathML In this example, we will make Pythagorean Equation using HTML code. <!DOCTYPE html> <html> <head> <meta charset=”UTF-8″> <title>Pythagorean theorem</title> </head> <body> <math> <mrow> <msup> <mi>a</mi> <mn>2</mn> </msup> <mo>+</mo> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo>=</mo> <msup> <mi>c</mi> <mn>2</mn> </msup> </mrow> </math> </body> </html> Quadratic Equation using MathML In this example we will make a Quadratic Equation using HTML code. <!DOCTYPE html> <html> <head> <title>MathML Examples</title> </head> <body> <math> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <mn>4</mn> <!– Invisible times operator –> <mo></mo> <mi>x</mi> <mo>+</mo> <mn>4</mn> <mo>=</mo> <mn>0</mn> </mrow> </math> </body> </html> Make Matrix in MathML Consider the following example which would be used to represent a simple 2×2 matrix: <!DOCTYPE html> <html> <head> <title>MathML Examples</title> </head> <body> <math> <mrow> <mi>A</mi> <mo>=</mo> <mfenced open=”[” close=”]”> <mtable> <mtr> <mtd><mi>x</mi></mtd> <mtd><mi>y</mi></mtd> </mtr> <mtr> <mtd><mi>z</mi></mtd> <mtd><mi>w</mi></mtd> </mtr> </mtable> </mfenced> </mrow> </math> </body> </html> Redox Equation in MathML Below is an example of a redox chemical equation using MathML. <!DOCTYPE html> <html> <head> <title>MathML Examples</title> </head> <body> <math> <mrow> <msub> <mtext>Zn</mtext> </msub> <mo>+</mo> <msub> <mrow> <mtext>CuSO</mtext> <mn>4</mn> </mrow> </msub> <!– Arrow Symbol –> <mo>→</mo> <msub> <mrow> <mtext>ZnSO</mtext> <mn>4</mn> </mrow> </msub> <mo>+</mo> <msub> <mtext>Cu</mtext> </msub> </mrow> </math> </body> </html> Print Page Previous Next Advertisements ”;
HTML5 – WebSocket
HTML – WebSockets ”; Previous Next WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket. WebSockets allow bidirectional communication which means both client and server can send data to eachother independently and simultaneously After establishing a Web Socket connection with the web server, we can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. Syntax Following is the API which creates a new WebSocket object. var Socket = new WebSocket(url, [protocol] ); Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful. Attributes of WebSocket Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above. Attribute Description Socket.readyState The readonly attribute readyState represents the state of the connection. It can have the following values. A value of 0 indicates that the connection has not yet been established. A value of 1 indicates that the connection is established and communication is possible. A value of 2 indicates that the connection is going through the closing handshake. A value of 3 indicates that the connection has been closed or could not be opened. Socket.bufferedAmount The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. WebSocket Events Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above Event Values & Event Handler Values & Description open Socket.onopen This event occurs when socket connection is established. message Socket.onmessage This event occurs when client receives data from server. error Socket.onerror This event occurs when there is any error in communication. close Socket.onclose This event occurs when connection is closed. WebSocket Methods Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above − Method Description Socket.send() The send(data) method transmits data using the connection. Socket.close() The close() method would be used to terminate any existing connection. Setting Up the WebSocket Server with Python Step 1. Install Python If you don”t have python installed on your device, Download and install it from Python.org Step 2. Install WebSocket library After installing python create a folder for your project, And open that folder in command prompt or terminal. Then run this prompt. pip install websockets Step 3. Create the websocket server Open any text editor and write the below python code. Then save that as a file in the folder with name ”server.py” import asyncio import websockets async def echo(websocket, path): async for message in websocket: print(f”Received message: {message}”) await websocket.send(f”Server: You said “{message}””) start_server = websockets.serve(echo, “localhost”, 8080) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() Step 4. Run the server In the terminal navigate to your project folder, and run this command to start server. python server.py Setting up HTML client for the server So far we setup a python server for websocket. The server will be running on your terminal, so any messages sent to server will be visible at terminal. Here we will see how to setup a client that can receive message from server and also send message to server using HTML and JavaScript. Create a HTML file ”index.html” in the folder <!DOCTYPE html> <html lang=”en”> <head> <title>WebSocket Example</title> </head> <body> <h1>WebSocket Client</h1> <input type=”text” id=”messageInput” placeholder=”Type a message…” /> <button id=”sendButton”> Send </button> <div id=”messages”> </div> <script> const socket = new WebSocket(”ws://localhost:8080”); socket.addEventListener(”open”, () => { console.log(”Connected to server”); }); socket.addEventListener(”message”, (event) => { const messageDiv = document.createElement(”div”); messageDiv.textContent = event.data; document.getElementById(”messages”).appendChild(messageDiv); }); document.getElementById(”sendButton”).addEventListener(”click”, () => { const messageInput = document.getElementById(”messageInput”); const message = messageInput.value; socket.send(message); messageInput.value = ””; }); </script> </body> </html> Print Page Previous Next Advertisements ”;