</CANVAS> <BODY> <SCRIPT> <CANVAS ID=\"myCanvas\" width=\"300\" var c=document.getElementById height=\"300\" style=\"border:1px solid (\"myCanvas\"); black\"> var ctx=c.getContext(\"2d\"); </CANVAS> ctx.rect(30,40,120,120); <SCRIPT> ctx.stroke(); var c=document.getElementById ctx.fillRect(160,40,120,120); (\"myCanvas\"); ctx.stroke(); var ctx=c.getContext(\"2d\"); ctx.strokeRect(300,40,120,120); ctx.fillStyle=\"red\"; ctx.fillRect(460,40,120,120); ctx.fillRect(20,20,150,100); ctx.clearRect(500,60,40,40); </SCRIPT> </SCRIPT> </BODY> </BODY> </HTML> </HTML> The preceding code creates a rectangle of size 150 x 100 The preceding code creates rectangles on the canvas, as filled with red color at the position, (20, 20), on the shown in the following figure. canvas, as shown in the following figure. The Rectangles Created on the Canvas A Rectangle Filled with the Red Color Working with Colors strokeStyle The strokeStyle property is used to set the outline The graphic objects on a canvas are created by using the color of a shape drawn on the canvas. The default value of default stroke and fill color. However, you can use colors the strokeStyle property is solid black. The following other than the default color for creating the graphic syntax can be used to apply stroke style on a graphic objects. The following properties can be used to apply object: colors on the canvas objects: strokeStyle=\"color\"; In the preceding syntax, color specifies the name or fillStyle hexadecimal value of the color. strokeStyle Consider the following code for applying the stroke style shadowColor on a rectangle: <!DOCTYPE HTML> fillStyle <HTML> The fillStyle property is used to define a color that <BODY> will be used to fill any closed shape drawn on the canvas. The default value of the fillStyle property is solid black. The following syntax is used to apply fill style on a graphic object: fillStyle=\"color\"; In the preceding syntax, you can specify the color as red, green, or blue. In addition, you can also specify the hexadecimal value of the color ranging from 000000 to FFFFFF. Consider the following code for applying fill style on a rectangle drawn on the canvas having ID, myCanvas: <!DOCTYPE HTML> <HTML>
<CANVAS ID=\"myCanvas\" width=\"300\" shadowColor property is solid black. height=\"300\" style=\"border:1px solid black\"> You can use the following syntax to define the </CANVAS> shadowBlur property: <SCRIPT> shadowBlur=number; var c=document.getElementById In the preceding syntax, number specifies the blur level (\"myCanvas\"); of the shadow. It can accept the integer values, such as 1, var ctx=c.getContext(\"2d\"); 2, and 20. Its default value is 0. ctx.strokeStyle=\"blue\"; ctx.strokeRect(20,20,150,100); Consider the following code for applying shadows on a </SCRIPT> rectangle: </BODY> <!DOCTYPE HTML> </HTML> <HTML> The preceding code will create a rectangle of size 150 x <BODY> 100 with its outline colored in blue at the position, (20, <CANVAS ID=\"myCanvas\" width=\"300\" 20), on the canvas, as shown in the following figure. height=\"300\" style=\"border:1px solid black\"> </CANVAS> <SCRIPT> var c=document.getElementById (\"myCanvas\"); var ctx=c.getContext(\"2d\"); ctx.shadowBlur=40; ctx.fillStyle=\"pink\"; ctx.shadowColor=\"black\"; ctx.fillRect(20,20,100,80); ctx.shadowColor=\"blue\"; ctx.fillRect(140,20,100,80); </SCRIPT> </BODY> </HTML> In the preceding code, the blur level of the shadow of graphic objects is set to 40. In addition, the shadow color for the first rectangle is set to black and the shadow color for the second rectangle is set to blue. The output derived by using the shadowBlur and shadowColor properties is displayed in the following figure. The Rectangle with Strokes Colored in Blue shadowColor Once you have drawn a shape on the canvas, you may want to make it more stylish by casting a shadow on it. To cast a shadow of a graphic object on the canvas, you need to specify the color of the shadow. In addition, you need to specify how blurred you want your shadow to be. The shadowColor property is used to set the color for the shadows appearing on the graphic objects and the shadowBlur property is used to set the blur level for the shadows. You can use the following syntax to use the shadowColor property: shadowColor=\"color\"; In the preceding syntax, color specifies the color that will be applied on shadows. The default value of the
The Output Derived by Using the shadowBlur and createRadialGradient() method to display the shadowColor Properties gradients. Working with Styles createLinearGradient() The createLinearGradient() method is used to Apart from creating simple shapes on the canvas, you can return a gradient object that represents a linear gradient for painting the specified color along a line. The following also apply styles, such as gradients, on them. A gradient is syntax can be used to apply a linear gradient: createLinearGradient(x0,y0,x1,y1); an object that provides smooth transition between two or In the preceding syntax: more colors. To work with gradient styles, you can use the x0: Specifies the x-coordinate of the start point of the gradient. following methods: y0: Specifies the y-coordinate of the start point of the gradient. addColorStop() x1: Specifies the x-coordinate of the end point of the gradient. createLinearGradient() y1: Specifies the y-coordinate of the end point of the gradient. createRadialGradient() After creating the linear gradient object, you need to create createPattern() the gradients by using the addColorStop() method. Once you have created the linear gradient, you need to addColorStop() apply it on a graphic object by using the following ways: To create gradients, you need to first specify the colors Fill the graphic object with the linear gradient by using the fillStyle property. and their position in a gradient object. This is because the Apply the linear gradient on the outline of the graphic object by using the strokeStyle gradients are not visible until the colors are added to the property. Consider the following code for applying a linear gradient objects. Therefore, to actually make the gradient effects on a rectangle: <!DOCTYPE HTML> visible on a graphic object, you need to add colors. You <HTML> <BODY> can add one or more colors on a gradient object by using <CANVAS ID=\"myCanvas\" width=\"300\" height=\"300\" style=\"border:1px solid the addColorStop() method. The addColorStop black\"> </CANVAS> () method is used to specify the colors and their <SCRIPT> var c=document.getElementById corresponding positions in a gradient object. The (\"myCanvas\"); var ctx=c.getContext(\"2d\"); following syntax can be used to define the var grad=ctx.createLinearGradient (0,0,170,0); addColorStop() method: grad.addColorStop(0,\"blue\"); grad.addColorStop(\"0.5\",\"yellow\"); addColorStop(position,color); grad.addColorStop(1,\"red\"); ctx.fillStyle=grad; In the preceding syntax: ctx.fillRect(20,20,180,180); </SCRIPT> position: Specifies a value between 0.0 to 1.0 </BODY> </HTML> to represent the position from where to start and In the preceding code, a gradient object is created by end the gradient color. using the createLinearGradient() method. color: Specifies the color that needs to be Further, the addColorStop() method is used to specify different colors to the gradient object, and then, applied on the respective position. the gradient object is passed to the fillStyle property The addColorStop() method is used along with the createLinearGradient() or
to shade the rectangle in three different colors from left to Fill the graphic object with the radial gradient by right. The output derived by using the using the fillStyle property. createLinearGradient() method is displayed, as Apply the radial gradient on the outline of the shown in the following figure. graphic object by using the strokeStyle property. The Output Derived by Using the createLinearGradient() Consider the following code snippet for applying a radial Method gradient on a rectangle: <!DOCTYPE HTML> createRadialGradient() <HTML> The createRadialGradient() method is used to <BODY> return a gradient object that represents a radial or a <CANVAS ID=\"myCanvas\" width=\"300\" circular gradient to be applied on a graphic object. A height=\"300\"style=\"border:1px solid circular gradient paints colors along a cone specified by black\"> two circles, inner and outer. The following syntax can be </CANVAS> used to apply a radial gradient: <SCRIPT> createRadialGradient var c=document.getElementById (x0,y0,r0,x1,y1,r1); (\"myCanvas\"); In the preceding syntax: var ctx=c.getContext(\"2d\"); var grad=ctx.createRadialGradient x0: Specifies the x-coordinate of the start point of (75,50,5,90,60,100); the gradient. grad.addColorStop(0,\"blue\"); y0: Specifies the y-coordinate of the start point of grad.addColorStop(\"0.5\",\"yellow\"); the gradient. (x0,y0) specifies the center grad.addColorStop(1,\"red\"); coordinate of the first circle of the cone. ctx.fillStyle=grad; r0: Specifies the radius of the starting circle. ctx.fillRect(20,20,180,180); x1: Specifies the x-coordinate of the end point of </SCRIPT> the gradient. </BODY> y1: Specifies the y-coordinate of the end point of </HTML> the gradient. (x1,y1) specifies the center In the preceding code, a gradient object is created using coordinate of the second circle of the cone. the createRadialGradient() method. Further, the r1: Specifies the radius of the ending circle. addColorStop() method is used to specify different After creating the radial gradient object, you need to create colors to the gradient object and then, the gradient object the gradients by using the addColorStop() method. is passed to the fillStyle property to shade the Once you have created the radial gradient, you need to rectangle in three different colors along the radius given apply it on a graphic object by using the following ways: for the circle. The output derived by using the createRadialGradient() method is displayed in the following figure.
The Output Derived by Using the createRadialGradient() A Pattern Method The following syntax can be used to create a pattern: createPattern(img, \"repeat|repeat-x| createPattern() repeat-y|no-repeat\"); The createPattern() method is used to create a In the preceding syntax: pattern by displaying an image repeatedly on a canvas in the specified direction. For example, consider the img: Specifies the image or video to be used to following image. create a pattern. repeat: Specifies that the pattern should be The Image repeated horizontally and vertically. If the preceding image is repeated vertically and repeat-x: Specifies that the pattern should be horizontally, you can create a pattern, as shown in the repeated horizontally. following figure. repeat-y: Specifies that the pattern should be repeated vertically. no-repeat: Specifies that the pattern should be displayed only once. Consider the following code snippet for repeating an image horizontally and vertically: <P>Image to use:</P> <IMG src=\"pattern.png\" ID=\"pattern\"> <P>Canvas:</P> <BUTTON onclick=\"draw ('repeat')\">Repeat</BUTTON> <CANVAS ID=\"myCanvas\" width=\"300\" height=\"150\" style=\"border:1px solid #d3d3d3;\"> Your browser does not support the HTML5 canvas tag.</CANVAS> <SCRIPT> function draw(direction) { var c=document.getElementById (\"myCanvas\"); var ctx=c.getContext(\"2d\");
var img=document.getElementById Further, to insert the caption for the pie chart, you need to (\"pattern\") insert text. You can insert text in canvas by using the text var pat=ctx.createPattern properties and methods. In addition, you can also add (img,direction); images to the canvas. ctx.rect(0,0,300,150); ctx.fillStyle=pat; Working with Path ctx.fill(); } A path is a series of points joined together to create lines </SCRIPT> or shapes. In canvas, you can use lines or paths to draw The preceding code snippet repeats the pattern.png shapes other than rectangles or squares. Using paths or image horizontally and vertically in the rectangular area lines, you can create shapes such as circles, polygon, or on the canvas, when the user clicks the Repeat button, as triangles. However, to create a path, you need to first start shown in the following figure. or begin the path. Next, you need to call methods, such as moveTo() and lineTo(), to actually draw the path. Finally, you need to end or close the path so that the shape gets created. To create shapes by using paths, you can use various methods. These methods are described in the following table. Method Description fill() Is used to fill the path on the canvas. The default color is black. You can change the fill color by using the fillStyle property. stroke() Is used to draw the outlines Repeating Image on the Canvas of the path. The default Working with Path, Text, and Images color is black. You can LearnGraphs Ltd offers tutorials on creating pie charts. change the outline color by For this, a pie chart along with its caption, needs to be drawn. However, a pie chart is a circular chart that is using the strokeStyle divided into various sectors. To create such a pie chart, you need to draw a circle. In addition, to divide the circle property. into various sectors, you need to draw lines. In canvas, you can create such shapes, such as circles, lines, arcs, and beginPath() Is used to begin a path or triangles, by using path methods and properties. resets the current path. moveTo(x,y) Is used to move the path to the (x,y) coordinates on the canvas. closePath() Is used to create a path from the current position back to the starting position. lineTo(x,y) Is used to create a line from the starting position to the ending position specified by (x,y) coordinates. The starting position is defined by the (x,y) coordinates specified in the moveTo() method. clip() Is used to clip a specified area from the canvas. arc(x,y,r,sAngle, Is used to create an arc or a eAngle,counterclock curve on the coordinate wise) points (x,y) with the radius, r from the starting angle, sAngle to the end angle, eAngle on the canvas. The
arcTo last parameter specifies (x1,y1,x2,y2,r) whether the drawing should be counterclockwise or clockwise. The false value specifies clockwise and true value specifies counter- clockwise. Is used to create an arc between two coordinate points, (x1,y1) and (x2,y2) with radius r on the canvas. The Path Methods The Line Drawn on a Canvas Consider the following code for creating a line on a Consider the following code for creating a circle on a canvas: canvas: <!DOCTYPE HTML> <!DOCTYPE HTML> <HTML> <HTML> <BODY> <BODY> <CANVAS ID=\"myCanvas\" width=\"300\" <CANVAS ID=\"myCanvas\" width=\"300\" height=\"300\" style=\"border:1px solid height=\"300\" style=\"border:1px solid black\"> black\"> </CANVAS> </CANVAS> <SCRIPT> <SCRIPT> var c=document.getElementById var c=document.getElementById (\"myCanvas\"); (\"myCanvas\"); var ctx=c.getContext(\"2d\"); var ctx=c.getContext(\"2d\"); ctx.beginPath(); ctx.beginPath(); ctx.arc(80, 90, 50, 0, Math.PI*2, ctx.moveTo(40, 40); false); ctx.lineTo(240, 40); ctx.closePath(); ctx.stroke(); </SCRIPT> ctx.fillStyle=\"green\"; </BODY> ctx.fill(); </HTML> </SCRIPT> In the preceding code , the beginPath() method will </BODY> begin the path on the canvas. Further, the lineTo() </HTML> method will draw a straight line from the canvas In the preceding code, a circle of the radius, 50, filled with coordinates, (40,40), specified in the moveTo() the green color is drawn on the canvas at the coordinates, method upto the coordinates, (240,40), as shown in the (80, 90), as shown in the following figure. following figure.
The Output Derived by Using the arc() Method height=\"300\" style=\"border:1px solid black\"> In addition to drawing lines, arcs, or circles, you can also </CANVAS> draw more complex curvatures, such as the bezier curves. <SCRIPT> A bezier curve is defined with a context or starting point, var c=document.getElementById two control points, and an ending point, as shown in the ('myCanvas'); following figure. var ctx=c.getContext('2d'); ctx.beginPath(); ctx.moveTo(200,20); ctx.bezierCurveTo (80,20,80,100,150,100); ctx.stroke(); </SCRIPT> </BODY> </HTML> In the preceding code, a bezier curve is drawn starting from the point, (200, 20), to the point, (150, 100), as shown in the following figure. The Bezier Curve The Bezier Curve You can create the bezier curves by using the path method, bezierCurveTo(). The following syntax can be used Working with Text to create a bezier curve: bezierCurveTo In addition to drawing shapes or lines on the canvas, you (cp1x,cp1y,cp2x,cp2y,x,y); can also draw text on it. You can also apply different styles on the text. For this, you can use the various text In the preceding syntax: properties. The following table lists the text properties. cp1x: Specifies the x-coordinate of the first control point. Property Value Description cp1y: Specifies the y-coordinate of the first control point. font font-style| Is used to set the cp2x: Specifies the x-coordinate of the second Bezier control point. font- font for the text on cp2y: Specifies the y-coordinate of the second Bezier control point. variant| the canvas. x: Specifies the x-coordinate of the ending point. y: Specifies the y-coordinate of the ending point. font-weight| Consider the following code: font-size| <!DOCTYPE HTML> <HTML> font-family <BODY> <CANVAS ID=\"myCanvas\" width=\"300\" textAlign start|end| Is used to set the center|left| alignments for the right text. textBaseLine top|hanging| Is used to set the
middle| baseline for the px Georgia by using the font property and draws the bottom| text where it will text, Fill Text, at the canvas coordinates, (10,60), alphabetic be drawn relative on the canvas. Similarly, it draws the text, Fill Text to its starting with Gradient, at the canvas coordinates, (10, point. 90), and applies the gradient on it by using the createLinearGradient() method and the The Text Properties fillStyle property, as shown in the following figure. The preceding properties can be used to decorate the text. However, you need to use the following methods to The Output Derived by Using the fillText() Property actually draw a text on a canvas: strokeText() fillText() The strokeText() method is used to draw a text at the strokeText() specified position on the canvas by using the current font style and color. The default outline color used by this fillText() method to draw a text on the canvas is black. The syntax The fillText() method is used to draw a text filled to use the strokeText() method is: with solid color on a canvas. The default value for strokeText(text,x,y,width); fillText() is black. The following syntax can be used In the preceding syntax: to draw a filled text: fillText(text,x,y,width); text: Specifies the text to be written on the In the preceding syntax: canvas. x: Specifies the x-coordinate of the starting point text: Specifies the text to be written on the of the text. canvas. y: Specifies the y-coordinate of the starting point x: Specifies the x-coordinate of the starting point of text. of the text. width: Specifies the width of the text. y: Specifies the y-coordinate of the starting point Consider the following code: of the text. <!DOCTYPE HTML> width: Specifies the width of the text. <HTML> Consider the following code for drawing a filled text on <BODY> the canvas: <CANVAS ID=\"myCanvas\" width=\"300\" <!DOCTYPE HTML> height=\"300\" style=\"border:1px solid <HTML> black\"> <BODY> </CANVAS> <CANVAS ID=\"myCanvas\" width=\"200\" <SCRIPT> height=\"200\" style=\"border:1px solid var c=document.getElementById black\"> (\"myCanvas\"); </CANVAS> var ctx=c.getContext(\"2d\"); <SCRIPT> ctx.font=\"25px Georgia\"; var c=document.getElementById ctx.strokeText(\"Stroke (\"myCanvas\"); Text\",10,60,120); var ctx=c.getContext(\"2d\"); ctx.font=\"25x Verdana\"; ctx.font=\"15px Georgia\"; var gradient=ctx.createLinearGradient ctx.fillText(\"Fill Text\",10,60,120); (0,0,170,0); ctx.font=\"15x Verdana\"; var gradient=ctx.createLinearGradient (0,0,170,0); gradient.addColorStop(\"0\",\"magenta\"); gradient.addColorStop(\"0.5\",\"blue\"); gradient.addColorStop(\"1.0\",\"red\"); ctx.fillStyle=gradient; ctx.fillText(\"Fill Text with Gradient\",10,90,120); </SCRIPT> </BODY> </HTML> The preceding code sets the font style of the text to 15
gradient.addColorStop(\"0\",\"magenta\"); width of the image is taken by default. gradient.addColorStop(\"0.5\",\"blue\"); height: Specifies the height of the image. If not gradient.addColorStop(\"1.0\",\"red\"); specified, the actual height of the image is taken ctx.strokeStyle=gradient; by default. ctx.strokeText(\"Stroke Text with sx: Specifies the x-coordinate where to start the Gradient\",10,90,200); clipping of the image. </SCRIPT> sy: Specifies the y-coordinate where to start the </BODY> clipping of the image. </HTML> swidth: Specifies the width of the clipped The preceding code sets the font style of the text to 25px image. Georgia by using the font property and draws the text, sheight: Specifies the height of the clipped Stroke text, at the canvas coordinates, (10,60), on image. the canvas. Similarly, it draws another text, Stroke Consider the following code to draw an image on a Text with Gradient, at the canvas coordinates, canvas: (10,90), and applies the gradient on it by using the <!DOCTYPE HTML> createLinearGradient() method and the <HTML> strokeStyle property, as shown in the following <BODY onload=setImage()> figure. <CANVAS ID=\"myCanvas\" width=\"250\" height=\"300\" The Output Derived by Using the strokeText() Method style=\"border:1px solid #d3d3d3;\"> Your browser does not support the Working with Images HTML5 canvas tag.</CANVAS> <SCRIPT> In canvas, you can also draw images, image clips, or function setImage(){ render videos. For this, you can use the drawImage() var c=document.getElementById method. The drawImage() method is used to draw an (\"myCanvas\"); image or a video on the canvas. In addition, it enables you var ctx=c.getContext(\"2d\"); to draw a part of an image on the canvas. To define the var img=new Image(); drawImage() method, you can use the following img.src=\"orchid.jpg\"; syntaxes: img.onload = function() { drawImage(img,x,y); ctx.drawImage(img,10,10,150,150); drawImage(img,x,y,width,height); } drawImage } (img,sx,sy,swidth,sheight,x,y,width,he </SCRIPT> ight); </BODY> In the preceding syntax: </HTML> In the preceding code, the image is drawn on the canvas at img: Specifies an image that needs to be drawn the point, (10, 10), and of size 150 x 150, as shown in the on the canvas. following figure. x: Specifies the x-coordinate for the starting point of the image. y: Specifies the y-coordinate for the starting point of the image. width: Specifies the width of the image. It is an optional argument. If not specified, the actual
Drawing an Image on the Canvas document, only the name of the library can be given. However, if the JavaScript library and the Working with Graphs HTML document are stored at different locations, then you have to specify the complete path of the A graph is a way of representing relationships among a JavaScript library. For example, you want to create a bar graph on a Web collection of items. A graph consists of a set of objects, page. For this, you need to download the RGraph.common.core.js and RGraph.bar.js files. called nodes, which are connected by links called edges. Consider the following code to create a bar graph on a Web page: In a canvas, you can create graphs, such as bar graph or <!DOCTYPE HTML> <HTML> pie chart, to represent relationships. These graphs can be <HEAD> <SCRIPT type=\"text/javascript\" created by using methods provided to draw the shapes. src=\"RGraph.common.core.js\" ></SCRIPT> <SCRIPT type=\"text/javascript\" However, to draw graphs by using these methods is a src=\"RGraph.bar.js\" ></SCRIPT> <TITLE>Bar chart</TITLE> tedious task. To simplify this task, you can use the various </HEAD> <BODY> freely-downloadable JavaScript libraries. One such library <CANVAS width=\"500\" height=\"250\" is RGraph. To create graphs by using the RGraph library, ID=\"test\" style=\"border:1px solid black\"></CANVAS> you need to download this light-weight JavaScript library <SCRIPT type=\"text/javascript\" and save it in your system. RGraph allows you to create charset=\"utf-8\"> var bar = new RGraph.Bar('test', different types of graphs on a Web page. [10,30,20,10]); bar.Set('chart.colors', ['red']); Once the JavaScript library is downloaded, it can be bar.Set('chart.title', \"Sales Report\" ); referred to in a Web page by using the <SCRIPT> tag in bar.Set('chart.labels', [\"10\" , \"20\" , \"30\" , \"40\" ]); the head section of the Web document. The following bar.Draw(); </SCRIPT> syntax is used to specify the jQuery library: </BODY> </HTML> <SCRIPT type=\"text/javascript\" The preceding code creates a graph on the canvas, as shown in the following figure. src=\"<RGraph_file_name>\" ></SCRIPT> A Bar Graph In the preceding syntax: To create various different graphs on a Web page, you The <SCRIPT> tag instructs the browser that the need to download different JavaScript files. For this, you can HTML document uses a script. The type attribute specifies the type of scripting used. The src attribute specifies the name of the JavaScript library used. If the JavaScript library is stored at the same location as the HTML
refer to the http://www.rgraph.net/demos link. Activity 6.1: Introducing Canvas The Resetting the Origin of the Canvas In the preceding figure, the origin of the canvas is shifted Transforming and Animating Canvas to the (x,y) coordinate. The translate() method Elements enables you to move all the graphic objects on the canvas by using just one method. For example, you have drawn a LearnGraphs Ltd. wants to make the graphics eye-catching complex drawing onto the canvas and you need to move visually appealing to the users. For this, they need to the drawing around on the canvas. To perform such a task, animate or transform the shapes, such as scaling or you need to adjust the x and y positions of all the graphic rotating the line drawn on the canvas. To apply such objects involved in the drawing. It is a time-consuming animations, you need to apply animation effects on the and error-prone task. You can simplify this task by just shapes. With canvas, you can transform, rotate, or scale translating the context or the origin of the canvas to the graphic objects. new position and then, using the original x and y positions of all the graphic objects, redraw them on the canvas. This Transforming Canvas Elements way, the graphic objects will be redrawn by taking into account the position of the new origin. Therefore, the With CSS, you can move HTML elements from one graphic objects will be moved to the desired location on position to another easily. However, while working with a the canvas by using just one method call. canvas, you may want to shift the graphics objects from The syntax of the translate() method is: one position to another and increase or decrease their size. This can be done by transforming the canvas elements. To translate(x,y); transform the canvas elements, you can use the following methods: In the preceding syntax: x: Specifies the value to be added to the existing translate() value of the x coordinate. scale() y: Specifies the value to be added to the existing rotate() value of the y coordinate. Translate For example, you have created a rectangle by using the following code snippet: The translate() method is used to reset the origin of var c=document.getElementById the canvas to the specified position, as shown in the (\"myCanvas\"); following figure. var ctx=c.getContext(\"2d\"); ctx.fillStyle=\"red\"; ctx.fillRect(10,10,100,100); The preceding code snippet will draw a rectangle at the coordinate, (10, 10), as shown in the following figure.
The Rectangle The Output Derived by Using the translate() Method Now, you want that the rectangle should be redrawn starting from coordinate, (60, 35). For this, you can use the Scale translate() method, as shown in the following code snippet: The scale() method is used to increase or decrease the var c=document.getElementById units in the canvas grid. This will allow you to draw scaled (\"myCanvas\"); down or enlarged graphic objects. The following syntax var ctx=c.getContext(\"2d\"); can be used to scale the graphic objects: ctx.fillStyle=\"red\"; scale(scalewidth,scaleheight); ctx.fillRect(10,10,100,100); In the preceding syntax: ctx.translate(50,25); ctx.fillStyle=\"blue\"; scalewidth: Specifies the width (in ctx.fillRect(10,10,100,100); percentage), a graphic object should be scaled to. scaleheight: Specifies the length (in In the preceding code snippet, the first rectangle is drawn percentage), a graphic object should be scaled to. in the red color at the point, (10, 10) from the origin of the Consider the following code for scaling a rectangle on canvas. The translate() method then resets the origin canvas: of the canvas at the point, (50, 25). The second rectangle is <!DOCTYPE HTML> drawn in blue color at the point, (10, 10) from the new <HTML> origin, (50, 25). Therefore, the second rectangle will be <BODY> drawn at the point, (60, 35) from the point, (0, 0) of the <CANVAS ID=\"myCanvas\" width=\"300\" canvas, as shown in the following figure. height=\"300\" style=\"border:1px solid black\"> </CANVAS> <SCRIPT> var c=document.getElementById (\"myCanvas\"); var ctx=c.getContext(\"2d\"); ctx.fillStyle=\"red\"; ctx.fillRect(10,10,100,100); ctx.translate(50,25); ctx.scale(2,2); ctx.fillStyle=\"blue\"; ctx.fillRect(10,10,100,100); </SCRIPT> </BODY>
</HTML> ctx.fillRect(10,10,100,100); ctx.rotate(25); In the preceding code, the red colored rectangle of size ctx.fillStyle=\"blue\"; 100 x 100 is created starting from the canvas coordinates, ctx.fillRect(40,40,100,100); (10, 10). The origin of the canvas is reset at the point, (50, </SCRIPT> 25), by using the translate() method. Then, the width </BODY> and height of the rectangle are scaled by the factor of 2 by </HTML> using the scale() method. Therefore, the width and In the preceding code, a red colored rectangle is drawn at height of the blue colored rectangle gets doubled and is the coordinate, (10, 10). Further, the angle to rotate the redrawn from the canvas coordinates, (60, 35), as shown canvas element is specified as 25. Therefore, the rectangle in the following figure. will be redrawn in the blue color starting from the coordinate, (40, 40), and rotated at the 25 degree angle, as shown in the following figure. The Output Derived by Using the scale() Method The Output Derived by Using the rotate() Method Rotate The rotate() method is used to rotate the graphic object to a specified degree in the clockwise direction. The following syntax can be used to apply rotation: rotate(angle); In the preceding syntax, angle specifies the degree a graphic object should be rotated to. Consider the following code for applying rotations on canvas: <!DOCTYPE HTML> <HTML> <BODY> <CANVAS ID=\"myCanvas\" width=\"300\" height=\"300\" style=\"border:1px solid black\"> </CANVAS> <SCRIPT> var c=document.getElementById (\"myCanvas\"); var ctx=c.getContext(\"2d\"); ctx.fillStyle=\"red\";
Animating Canvas Elements for drawing a ball on the canvas: function circle() { An animation is a visual technique that provides the ctx.beginPath(); illusion that an object is moving by displaying graphic ctx.fillStyle=\"red\"; objects in rapid sequence. In an animation, the object is ctx.arc(x, y, 10, 0, Math.PI*2, true); drawn first, next the canvas is cleared, and then the frame ctx.fill(); is drawn again with slight changes in its properties. The ctx.closePath(); process is repeated very fast to create an illusion. For } example, you want to represent a moving ball on the function clear() { canvas. You have applied a single rotation on a ball that ctx.clearRect(0, 0, WIDTH, HEIGHT); shows transformation. However, an animation is created if } you apply multiple rotations on that ball. function init() { To create such animations, you need to perform the canvas = document.getElementById following steps: (\"canvas\"); ctx = canvas.getContext(\"2d\"); 1. Create variables for the animation state. return setInterval(draw, 10); 2. Draw the animation. } 3. Redraw the objects. The preceding code snippet defines the following The following figure depicts the process of creating functions: animations on the canvas. init() function: In this function, the element The Process of Creating Animations on the Canvas ID for the canvas element is stored in the variable, canvas. Further, the context for the Creating Variables for the Animation canvas element is retrieved in the variable, ctx. State The context, ctx, can now be used to draw the graphic objects on the canvas. It is the first Variables are created to store the initial properties of the function that will be called in the code. In the graphic objects, such as width or height. Further, they can next line of the code, the setInterval() be used to store the updated values of the graphic objects. function is used to call the draw() function Therefore, whenever a new position is calculated for a every 10 milliseconds. The draw() function is a graphic object, the new values will get stored in the user-defined function that is created to redraw the variables. ball on the canvas. Consider an example of creating a ball moving on a canvas surface. To create such an animation, you need to You will study the code for the draw() define the variables first. Consider the following code function in the next topic. snippet for defining variables in JavaScript: var canvas; circle() function: In this function, the var ctx; beginpath() method is called to start a new var x = 400; path. The arc() method is used to define the var y = 300; size and shape of the circle. Further, the fill() var dx = 2; method is used to fill the entire circle with the var dy = 4; specified color. var WIDTH = 400; clear() function: In this function, the var HEIGHT = 300; clearRect() method is called to erase the In the preceding code snippet, the variables have been graphic objects from the canvas. created that can be used to draw an animation on the canvas. Redrawing the Objects Drawing the Animation Now, to create the animation effects, you need to repeatedly keep drawing the graphic objects with the After creating the variables, you need to draw the graphic updated properties. object on the screen. Consider the following code snippet Consider the following code snippet for redrawing a ball on the canvas: function draw() { clear(); circle(); if (x> WIDTH || x< 0)
dx = -dx; (\"canvas\"); if (y> HEIGHT || y< 0) ctx = canvas.getContext(\"2d\"); return setInterval(draw, 10); dy = -dy; x += dx; } y += dy; function draw() { } clear(); In the preceding code snippet, the clear() function is circle(); first called to clear the canvas. Further, the circle() if (x> WIDTH || x< 0) function is called to create a circle on the canvas. The circle has a radius, 10, and its origin is at (x,y). To dx = -dx; move the circle, you need to change the values of if (y> HEIGHT || y< 0) variables, x and y. Whenever the draw() function is executed, the variables, dx and dy, will determine the dy = -dy; values for the variables, x and y. If the value of x is not x += dx; greater than the width of the canvas or if it is less than y += dy; zero, the value of x will get changed by dx. However, if } the value exceeds the width size, then the variable, dx will init(); be set to -dx, and the process continues. The same </SCRIPT> condition is applied for the variable, y. </BODY> </HTML> The following lines show the entire code for rotating a The following file displays the output of the preceding ball: code. <!DOCTYPE HTML> <HTML> Activity 6.2: Creating a Game <HEAD> <TITLE>Rotating Ball</TITLE> Summary </HEAD> <BODY> In this lesson, you learned that: <DIV> Canvas provides an easy and a powerful way to <CANVAS ID=\"canvas\" width=\"400\" create graphics on a Web page. height=\"300\" style=\"border:2px solid A canvas is defined by using the <CANVAS> tag. black\"> This tag is defined in the body section of the </CANVAS> HTML document. </DIV> Defining the canvas element only creates a blank <SCRIPT type=\"text/javascript\"> drawing surface. However, to actually draw var canvas; graphic objects on the canvas, you need to access var ctx; the canvas in the JavaScript code. var x = 400; var y = 300; var dx = 2; var dy = 4; var WIDTH = 400; var HEIGHT = 300; function circle() { ctx.beginPath(); ctx.fillStyle=\"red\"; ctx.arc(x, y, 10, 0, Math.PI*2, true); ctx.fill(); ctx.closePath(); } function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); } function init() { canvas = document.getElementById
You can use the following methods to draw and Jeff Foltun AudioVideo/Conceptual/ shapes on canvas: HTML-canvas-guide/ Translation,Rotation,andSca rect() ling/ fillRect() Translation,Rotation,andSca strokeRect() ling.html http://tutorials.jenkov.com/ clearRect() html5-canvas/ transformation.html The following properties can be used to apply colors on the canvas objects: fillStyle strokeStyle shadowColor Apart from creating simple shapes on the canvas, you can also apply styles, such as gradients, on them. A path is a series of points joined together to create lines or shapes. In a canvas, you can use lines or paths to draw shapes other than rectangles or squares. In addition to drawing shapes or lines on the canvas, you can also draw text on it. You can also apply different styles on the text. The drawImage() method is used to draw an image or a video on the canvas. In a canvas, you can create graphs, such as bar graph or pie chart, to represent relationships. To transform the canvas elements, you can use the following methods: translate() scale() rotate() To create such animations, you need to perform the following steps: Create a variable for the animation state. Draw the animation. Redraw the objects. Reference Reading Introducing Canvas Reference Reading: Books Reference Reading: URLs HTML5 Canvas Native http://sixrevisions.com/html/ Interactivity and Animation canvas-element/ for the Web By Steve Foltun http://www.w3schools.com/ and Jeff Foltun html/html5_canvas.asp Transforming and Animating Canvas Elements Reference Reading: Books Reference Reading: URLs HTML5 Canvas Native http://developer.apple.com/ Interactivity and Animation library/safari/ for the Web By Steve Foltun #documentation/
Chapter 7 JavaScript codes that was created to make the JavaScript programming simpler. jQuery can be used by all levels of Adding Visual Effects to Web Pages programmers to enhance the look and feel of the Web page. jQuery supports events and can be bound to the Today, almost every Web developer wants to add visual HTML elements on the Web page. jQuery bridges the gap effects to websites. However, adding complex visual between extensive coding and Web designing as it is easy effects to Web pages requires writing many lines of to understand and provides many predefined special JavaScript code, which is a time-consuming activity. To effects. With jQuery, a Web designer can add a plethora of overcome this issue, jQuery was introduced. It is the impressive visual effects and also extend interactivity on a JavaScript library supported by HTML that wraps several Web page. lines of code into methods that can be called by using a single statement. Manipulating HTML Elements by This chapter introduces you to jQuery. Further, it discusses Using jQuery jQuery selectors, events, and effects. Also, it discusses how to add the image rollover effect to an image and how You can make use of jQuery in a Web page to manipulate to create an image gallery, thereby, making the website HTML elements by downloading the light-weight jQuery more attractive and enhancing the browsing experience of JavaScript library and saving it to your system. Once the the users. jQuery JavaScript library is downloaded, it can be referred to in a Web page by using the <SCRIPT> tag in the head Objectives section of the Web document. The following syntax is used to specify the jQuery library: In this chapter, you will learn to: <SCRIPT type=\"text/javascript\" Explore jQuery src=\"<path>/jquery-1.8.3.js\"> </ Add visual effects using jQuery SCRIPT> Implement image rollover In the preceding syntax: Create image gallery The SCRIPT tag instructs the browser that the Exploring jQuery HTML document uses a script. The type attribute specifies the type of scripting Consider a scenario of the online shopping website, used. ShopForYou.com. The website should be designed in such The src attribute specifies the name of the a way that it displays the product categories and items in jQuery library used. If the jQuery library is stored the sliding and collapsible menu and submenu format, as at the same location as the HTML document, only shown in the following figure. the name of the library can be given. However, if the jQuery library and the HTML document are The Sample Web Page stored at different locations, you have to specify For this, the Web designer has been asked to complete the the complete path of the jQuery library. task quickly and keep the code simple. For this situation, The execution of jQuery code should occur only after the the designer can use the prewritten JavaScript library Web page has been fully loaded. To ensure that a Web known as jQuery. page is fully loaded before the jQuery code is executed on jQuery is an open source and cross-browser library of it, jQuery provides the document.ready() function. This function contains the jQuery code to be executed on HTML elements after the Web page has been fully loaded in the browser. The following syntax is used to specify the document.ready() function: <SCRIPT type=\"text/javascript\"> $(document).ready(function(){ // jquery code... }); </SCRIPT> In the preceding syntax, the dollar sign ($) represents start of the jQuery code block and jQuery code is the code to be implemented for the rendering of the HTML
elements in the browser window. The element or a group of elements. You can select an HTML document.ready() function is useful for preventing element by: failure of actions that should be performed on an HTML element. For example, if the jQuery code for hiding an Using element name image executes before the document is ready, it will lead Using attribute name to failure. Therefore, to allow execution of the jQuery Using CSS selectors code only when the document is ready to be displayed in the browser window, all the jQuery methods and code Using Element Name should be declared and defined inside the jQuery can be used to select an HTML element or a group document.ready()function. of HTML elements by using its name. Using jQuery, HTML elements can be selected by referring to their The keyword, jQuery, can be used in place of the $ name, ID, or class to which they belong. sign while writing jQuery code. For example, the preceding Consider the following code snippet to select all the <H1> syntax can also be written as: elements in a document: jQuery(document).ready(function(){ $(\"h1\") //jQuery code... In the preceding code snippet, the <H1> elements are }); referred to by the name, h1. However, HTML elements can also be selected by using class or ID. To select an As jQuery is used to manipulate HTML elements, the element with a specific ID by using jQuery, you can use elements should be selected first in order to implement the the following syntax: jQuery code on them. $(\"#Element_ID\") The following jQuery syntax is used to select the HTML In the preceding syntax, Element_ID represents ID of elements and perform the required action on them: the element to be selected. For example, to select an $(selector).action(); element having the ID, header, you can use the In the preceding syntax, selector is the element to be following code snippet: manipulated and action represents action to be taken on $(\"#header\") the selected element. jQuery provides many built-in To select elements with a specific class, you can use the actions that can be applied to the HTML elements, such as following syntax: hide, fadeout, show, and slideup. Consider the following $(\".Element_class\") code to hide all the <H1> elements in an HTML document: In the preceding syntax, .Element_class represents <!DOCTYPE HTML> the class of the elements to be selected. For example, to <HTML> select elements having the value of the class attribute as <HEAD> header, you can use the following code snippet: <SCRIPT type=\"text/javascript\" $(\".header\") src=\"jquery-1.8.3.js\"> </SCRIPT> For example, you have created the class selector named <SCRIPT> exClass and the ID selector named exId on the <H1> $(document).ready(function(){ tag, as shown below: $(\"h1\").hide(); <H1 class=\"exClass\"> }); <H1 ID=\"exId\"> </SCRIPT> </HEAD> Now, you want to manipulate the <H1> tag with the <BODY> specified class and ID. You need to use the following ... code: </BODY> $(\"h1.exClass\") </HTML> $(\"h1#exId\") In the preceding code snippet, all the <H1> elements will Here, by using the $(\"h1.exClass\") statement, only be hidden in the Web page. the <H1> header elements specified with the exClass value for the class attribute will be selected and by using jQuery code is written in the <HEAD> section of the the $(\"h1#exId\") statement, only the <H1> header document. elements that are specified with the exId value for the ID attribute will be selected. Using jQuery Selectors jQuery also supports nesting of elements. This allows applying an action on the elements that are nested within jQuery uses selectors to select and manipulate an HTML other elements. For example, a list item is nested inside a list. Consider the example of the ShopForYou online shopping website where the Web designer wants to implement a menu and submenu. The submenu items must
be linked to display their details in a new document. $(document).ready(function(){ A menu comprises a list and list items that are denoted by $(\"button\").click(function(){ the <UL> and <LI> tags, respectively. Consider the $('#menu ul').hide(); following code snippet to build a button, menu, and }); submenu, and to attach links to the submenu items: }); <BODY> </SCRIPT> <P> Product Menu</P> </HEAD> <H4>Product Categories</H4> In the preceding code snippet, #menu is used to select the <UL ID=\"menu\"> HTML element for which the value of the ID attribute is <LI><A>Laptops</A> menu. #menu ul selects all the <UL> items nested <UL> inside the HTML element for which the ID is specified as <LI><A href=\"\">L-150</A></LI> menu. When the user clicks on the button, all the nested <LI><A href=\"\">L-160</A></LI> list items will get hidden, and the menu with items at the <LI><a href=\"\">L-180</A></LI> first level: Laptops, Phones, Cameras, and Music Players <LI><A href=\"\">L-260</A></LI> will be visible. <LI><A href=\"\">L-678</A></LI> </UL> Using Attribute Name </LI> The HTML elements can also be selected by using the <LI><A>Phones</A> name of an attribute. The following syntax is used to <UL> select elements by using an attribute name: <LI><A href=\"\">P-1150</A></LI> $(\"[attribute-name]\") <LI><A href=\"\">P-1260</A></LI> In the preceding syntax, attribute-name specifies the <LI><A href=\"\">P-1180</A></LI> name of the attribute. <LI><A href=\"\">P-2260</A></LI> Consider the following code snippet: <LI><A href=\"\">P-6708</A></LI> $(\"[src]\") </UL> In the preceding code snippet, all the elements with the </LI> src attribute are selected. <LI><A>Cameras</A> <UL> Consider the following code snippet: <LI><A href=\"\">C-50</A></LI> $(\"[src='movie.jpg']\") <LI><A href=\"\">C-60</A></LI> In the preceding code snippet, all the elements that have <LI><A href=\"\">C-80</A></LI> the src attribute as movie.jpg are selected. <LI><A href=\"\">C-60</A></LI> <LI><A href=\"\">C-08</A></LI> Using CSS Selectors </UL> jQuery provides CSS selectors to modify the CSS </LI> properties of an HTML element or document. <LI><A>Music Players</A> The following syntax is used to apply CSS selectors to <UL> modify the document or element properties: <LI><A href=\"\">MP-1150</A></LI> selector.css( PropertyName, <LI><A href=\"\">MP-1260</A></LI> PropertyValue ); <LI><A href=\"\">MP-1180</A></LI> Consider the following code snippet to change the color of <LI><A href=\"\">MP-2260</A></LI> the text of the <DIV> element to green: <LI><A href=\"\">MP-6708</A></LI> $(\"div\").css(\"color\",\"green\"); </UL> In the preceding code snippet, all the div elements are </LI> selected in the document, and the css color property </UL> value is modified to green. <BUTTON>Hide List</BUTTON> With CSS selectors, you can set multiple properties on an </BODY> HTML element. The following syntax is used to set Consider the following code snippet to hide all the nested multiple CSS properties: <UL> items on the button click of a user, for which menu css is specified as the ID attribute value: ({\"propertyname\":\"value\",\"propertyname <HEAD> \":\"value\",...}); <SCRIPT src=\"jquery-1.8.3.js\"> Consider the following code snippet to change the color </SCRIPT> and font size of the text of the <DIV> element: <SCRIPT> $(\"div\").css(\"color\":\"green\", \"font- size\":\"200%\"); In the preceding code snippet, all the div elements are
selected in the document, and the css color property value selected elements. alue) is modified to green and font-size is set to 200%. The jQuery HTML Functions jQuery HTML Consider the following code for modifying the inner content of HTML elements: The jQuery library provides predefined functions to <!DOCTYPE HTML><HTML> perform modifications on the content of HTML elements. <HEAD> The following table lists the most commonly-used <SCRIPT type=\"text/javascript\" functions to modify the content of HTML elements. src=\"jquery-1.8.3.js\"></SCRIPT> <SCRIPT type=\"text/javascript\"> Function Description Syntax $(document).ready(function(){ html() $(\"button\").click(function(){ Changes the $(selector). append() $(\"#para\").prepend(\" <B>jQuery </ content of HTML html B>\"); prepend() elements, such as (content) $(\"#para\").append(\" <B>append() remove() function</B>.\"); text in the <P> empty() $(\"#para\").after('<H3> This is the and <DIV> tags. newly inserted heading.</H3>'); after() before() Enables a user to $(selector). $(\"#newhead\").remove(); text() append content append }); val() after the inside (content) }); attr() </SCRIPT> content in the </HEAD> <BODY> selected element. <DIV align=\"center\"> </DIV> Enables a user to $(selector). <H3>Complete the sentence:</H3> append content prepend <P ID=\"para\">is a javascript library before the inner (content) that enables the content to be appended after the inner content of selected content in the selected element using the</P><BR> elements. <H2 ID=\"newhead\">This heading would be removed.</H2> Removes the $(selector). <BUTTON ID=\"b\">Click here</BUTTON> </BODY> selected element remove() </HTML> In the preceding code, when a user clicks the Click here including all the button, the content, jQuery, is appended before the <P> tag having the ID, para, by using the prepend() text and nested function. Similarly, the content, append() function, is appended after the same <P> tag by using the append() elements inside it. function. In addition, a new <H3> tag is inserted after the <P> tag Removes all the $(selector). having the ID, para, by using the after() function. text and nested empty() Finally, the heading having the ID, newhead, is removed by using the remove() function. elements of Before the Click here button is clicked, the Web page appears, as shown in the following figure. selected elements. However, this method does not remove the element. Inserts the content $(selector). after the selected after elements. (content) Inserts the content $(selector). before the selected before elements. (content) Sets or returns the $(selector). content of selected text elements. (content) Sets or returns the $(selector). values of the val(value) attributes of selected elements. Sets or returns the $(selector). values and attr attributes of (attribute,v
(function) when the selected element gets focus. $(selector).blur Used to execute a function (function) when the selected element loses focus. $(selector).resize Used to execute a function The Web Page Before the Button is Clicked (function) when the browser window After the Click here button is clicked, the Web page appears, as shown in the following figure. changes size. The Web Page After the Button is Clicked $(selector).unload Used to execute a function The jQuery events are covered in the following topic. (function) when the user navigates away from the page. $(selector).mousedo Used to execute a function wn(function) when the left mouse button is pressed down on the selected element. $(selector).mouseup Used to execute a function (function) when the left mouse button is released from the selected element. Handling jQuery Events The Event Methods in jQuery Consider the following code to handle jQuery events: In jQuery, events are handled by using functions or <!DOCTYPE HTML><HTML> predefined event methods. An event method is used to <HEAD> detect an event and trigger a function when that event <SCRIPT type=\"text/javascript\" occurs. You can manipulate an element with a function or src=\"jquery-1.8.3.js\"></SCRIPT> an event method. <SCRIPT type=\"text/javascript\"> The following table lists some of the event methods $(document).ready(function(){ provided by jQuery. $(\"#hide_header\").click(function(){ /* selects the hide_header button and Event Method Description binds it to the click function */ $(\"h1\").hide(); //hides the <h1> $(document).load Used to execute a function header }); (function) after the document has }); </SCRIPT> finished loading. </HEAD> <BODY> $(selector).click Used to execute a function <H1>I am the header</H1> <HR> (function) on the click event of the <INPUT type=\"button\" ID=\"hide_header\" value='Hide the header'/> selected element. </BODY> </HTML> $(selector).dblclic Used to execute a function In the preceding code, jQuery recognizes a click event when the user clicks the Hide the header button. After the k(function) on the double-click event of event is recognized by jQuery, the function associated the selected element. with the button is executed and the <H1> element is hidden. $(selector).mouseen Used to execute a function There are some predefined functions that can be attached to event methods in jQuery to enrich the visual appearance ter(function) when the mouse pointer is of a Web document. These functions are referred to as jQuery effects. moved over the selected element. $(selector).mousele Used to execute a function ave(function) when the mouse pointer is moved out of the selected element. $(selector).keydown Used to execute a function (function) when a key is pressed on the selected element. $(selector).submit Used to execute a function (function) when a form is submitted. $(selector).focus Used to execute a function
</SCRIPT> </HEAD> <BODY> <H1>I am the header</H1> <BUTTON>Hide the header</BUTTON> </BODY> </HTML> In the preceding code, the text, I am the header, is displayed above the Hide the header button. When the Hide the header button is clicked, the text, I am the header, slowly disappears from the browser window. Implementing Show Effect Adding Visual Effects Using jQuery The show() function is used to make a hidden element visible when an event occurs. The following syntax is used With the help of jQuery, amazing visual effects can be to show the selected elements, if they are already hidden: applied to the elements of a Web document. These visual $(selector).show(speed) effects help to enrich the browsing experience of a user. In the preceding syntax, speed is an optional parameter. Some of the predefined jQuery effects that can be used to This parameter is used to specify the speed with the add visual appeal to a Web page are: values, slow, normal, and fast, or the duration in milliseconds at which an element reappears. Hide Consider the following code snippet to implement the Show show effect: Toggle <!DOCTYPE HTML><HTML><HEAD> Slide <SCRIPT type=\"text/javascript\" Fade src=\"jquery-1.8.3.js\"></SCRIPT> Animate <SCRIPT type=\"text/javascript\"> $(document).ready(function(){ Implementing Hide Effect $(\".view\").click(function(){ $(\"h3\").show(2000); The hide() function is used to make an element }); disappear when an event, such as click or double-click, $(\".conceal\").click(function(){ occurs. $(\"h3\").hide(); The following syntax is used to hide the selected elements: }); $(selector).hide(speed) }); In the preceding syntax, speed is an optional parameter </SCRIPT> that denotes speed with the values, slow, normal, and fast, </HEAD> or the duration in milliseconds at which an element <BODY> disappears. Consider the following code to implement the <H3> This text can be hidden and hide effect: shown. </H3> <BR> <!DOCTYPE HTML><HTML> <BUTTON class=\"view\">Click to view</ <HEAD> BUTTON> <SCRIPT type=\"text/javascript\" <BUTTON class=\"conceal\">Click to src=\"jquery-1.8.3.js\"></SCRIPT> hide</BUTTON> <SCRIPT type=\"text/javascript\"> </BODY> $(document).ready(function(){ </HTML> $(\"button\").click(function(){ In the preceding code snippet, the <H3> tag gets hidden in $(\"h1\").hide(\"slow\"); the browser window when the Click to hide button is }); clicked. When the Click to view button is clicked, the }); <H3> tag is shown again in 2000 milliseconds (or 2 seconds).
Implementing Toggle Effect direction. The toggle () function can be used to switch between slideUp() Produces the effect $(selector). the show and hide effects of an element. This event can be used to hide or show the element, alternatively, when an slideToggle of sliding selected slideUp event occurs. () The following syntax is used to show or hide the selected elements in the (speed) elements: $(selector).toggle(speed) upward direction. In the preceding syntax, speed is an optional parameter. It is used to specify the speed with the values, slow, Performs the $(selector). normal, and fast, or the duration in milliseconds at which an element disappears and reappears. slideup and slideToggle Consider the following code snippet to implement the toggle effect: slidedown (speed) <!DOCTYPE HTML><HTML> <HEAD> functions, <SCRIPT type=\"text/javascript\" src=\"jquery-1.8.3.js\"></SCRIPT> respectively, on <SCRIPT type=\"text/javascript\"> $(document).ready(function(){ alternate clicks. $(\".view\").click(function(){ $(\"h3\").toggle('fast'); The Slide Effect Functions }); Consider the following code to implement the slide effect: }); <!DOCTYPE HTML><HTML> </SCRIPT> <HEAD> </HEAD> <SCRIPT type=\"text/javascript\" <BODY> src=\"jquery-1.8.3.js\"></SCRIPT> <H3> Show and Hide me Quickly</H3> <SCRIPT type=\"text/javascript\"> <HR> $(document).ready(function(){ <BUTTON class=\"view\">Click here</ $(\".flipbut\").click(function(){ BUTTON> </BODY> $(\".thought\").slideToggle(); </HTML> }); In the preceding code snippet, the toggle() function }); hides and shows the <H3> tag, alternately. </SCRIPT> <STYLE type=\"text/css\"> Implementing Slide Effect div.thought,.flipbut{ /*stylizing the div element with the class The slide effect can be used to produce a sliding effect on the selected elements. There are three slide functions, attribute specified as slideDown(), slideUp( ), and slideToggle(), \"thought\", which can be applied on the selected elements. These functions apply a gradual modification on the height of the and the button with the selected elements to create the slide animation effect on a class attribute Web page. The following table lists the slide effect functions. specified as \"flipbut\" */} margin:0px; Function Description Syntax padding:5px; slideDown() text-align:center; Produces the effect $(selector). background:beige; border:solid 1px; of sliding selected slideDown } div.thought elements in the (speed) { height:120px; downward display:none; } </STYLE> </HEAD> <BODY> <BR><BR> <BUTTON style=\"background-color:beige\" class=\"flipbut\" text- align=\"center\">Show/Hide the thought of the day</BUTTON> <DIV class=\"thought\"> <P>The thought of the day is:</P> <P> Where there is a will, there is a
way!</P> width: 10em; </DIV> } </BODY> ul#menu a { /* stylizing the <a> </HTML> elements nested in the menu */ In the preceding code, when the Show/Hide the thought of the day button is clicked, toggle display: inline; functionality is implemented between slide up and slide text-decoration: none; down on the <DIV> element along with the thought } class. ul#menu li { /* stylizing the list For the online shopping website, ShopForYou.com, the items nested in the menu */ menu and submenu must be sliding. When the user clicks margin-top: 1px; a product category, the detailed products for that category } should be displayed by using the slide toggle effect. ul#menu li a { /* stylizing the <a> To implement this functionality in the ShopForYou.com elements nested in list items of the website, you need to write the following code in a file and menu */ save the file as menu.html: background: darkcyan; <!DOCTYPE HTML><HTML> color: #fff; <HEAD> padding: 0.5em; <SCRIPT type=\"text/javascript\" } src=\"jquery-1.8.3.js\"></SCRIPT> ul#menu li a:hover { /* stylizing the <SCRIPT type=\"text/javascript\"> <a> elements nested in list items of $(document).ready(function(){ the menu when mouse is placed or moved $('#menu ul').hide(); over them */ background: black; $('#menu li a').mouseenter(function } () { ul#menu li ul li a { background: grey; $(this).next().slideToggle color: white; ('slow'); padding-left: 20px; } } ul#menu li ul li a:hover { ); background: #aaa; }); color: white; </SCRIPT> border-left: 5px grey solid; <STYLE type=\"text/css\"> padding-left: 15px; body{ } background-image:url .st ('background.jpg'); { } display:inline; li a } { </STYLE> display:inline; </HEAD> } <BODY> body { <H3>Product Categories</H3> font-family: Arial, sans-serif; <UL ID=\"menu\"> font-size: 0.9em; <LI class=\".st\"><A>Computers</A> background-color:silver; <UL> } p <LI><A href=\"\">e-Book Readers</A></ { LI> line-height: 1.5em; } <LI><A href=\"\">Tablets and i-Pads</ #menu, ul#menu ul { /* stylizing the A></LI> menu and the list nested in the menu <LI><A href=\"\">Laptops</A></LI> */ list-style-type:none; </UL> margin: 0; </LI> padding: 0; <LI class=\".st\"><A>Entertainment</A> <UL>
<LI><A href=\"\">LED-TVs</A></LI> <LI><A href=\"\">LCD-TVs</A></LI> </UL> </LI> <LI class=\".st\"><A>Cameras</A> <UL> <LI><A href=\"\">Digital Cameras</ A></LI> <LI><A href=\"\">Digital SLR Cameras</A></LI> </UL> </LI> </UL> </BODY> </HTML> In the preceding code, a menu that displays the Computers, Entertainment, and Cameras product categories is created and stylized by using CSS. A product category contains different product items under it. All product items are hidden and only the Computers, Entertainment, and Cameras product categories are visible, as shown in the following figure. The Product Menu The Submenu for the Computers Product Category When a product category is clicked, the product items that When the product category is clicked again, the product belong to that specific product category appear to slide items appear to slide up. down by using the slide toggle effect provided by jQuery. After clicking the Entertainment product category, a submenu is displayed, as shown in the following figure. Implementing Fade Effect The jQuery fade effect is used to gradually reduce the opacity of the selected elements. You can fade an HTML element in and out of visibility. The following table lists
the four functions to produce the fade effect. FADE ME AWAY!, fades away. When the Restore button is clicked, the text, FADE ME AWAY!, reappears. Function Description Syntax Implementing Animate Effect fadeOut() Is used to fade the $(selector). appearance of the fadeOut The jQuery animate effect is used to create custom selected elements. (speed) animations. You can create an animate function by using the following syntax: fadeIn() Is used to restore $(selector). animate({params},speed,callback); where, the appearance of fadeIn params specifies the CSS properties to be animated. speed specifies the duration of the animation effect. the faded, selected (speed) callback specifies the function that will be executed after completing the animation. It is an optional parameter. element. Consider the following code snippet for applying animation effects on the <DIV> element: fadeTo() Is used to specify $(selector). <!DOCTYPE HTML> <HTML> the opacity for fadeTo <HEAD> <SCRIPT src=\"jquery-1.8.3.js\"> fading the selected (speed,opaci </SCRIPT> <SCRIPT> element. ty) $(document).ready(function(){ fadeToggle() Is used to fade the $(selector). $(\"div\").mouseenter(function(){ $(\"div\").animate({ appearance of the fadeToggle center:'250px', selected elements, (speed) opacity:'0.5', height:'250px', when they are width:'250px' }); faded out, and }); $(\"div\").mouseleave(function(){ restore the $(\"div\").animate({ opacity:'1', appearance of the height:'100px', width:'100px' selected elements, }); }); when they are }); </SCRIPT> faded in. </HEAD> <BODY> The Fade Effect Functions <DIV Consider the following code for implementing the fade style=\"background:#98bf21;height:100px effect: ;width:100px;position:absolute;\"> <!DOCTYPE HTML><HTML> </DIV> <HEAD> </BODY> <SCRIPT type=\"text/javascript\" </HTML> src=\"jquery-1.8.3.js\"></SCRIPT> The preceding code will increase the size of the <DIV> <SCRIPT type=\"text/javascript\"> element according to its specified width and height when $(document).ready(function(){ the mouse is moved over it and will reduce the size of the <DIV> element according to its specified width and $(\"div\").click(function(){ height when the mouse is left over it. $(this).fadeOut(1200); }); $(\"button\").click(function(){ $(\"div\").fadeIn(1200); }); }); </SCRIPT> </HEAD> <BODY> <DIV style=\"background:yellow;width:200px\"> FADE ME AWAY!</DIV><BR> <BUTTON>Restore</BUTTON> </BODY> </HTML> In the preceding code, the div tag is referred by using its name. In the click event handler of the div tag, the this keyword refers to the current HTML element, that is, the div tag. When the user clicks on the div tag, the text,
Activity 7.1: Exploring jQuery add the image rollover effect on Web pages. Image rollover is an effect in which the appearance of an Implementing Image Rollover image changes when the mouse pointer is placed or moved on it. The change in the appearance can be achieved by Consider the scenario of the ShopForYou.com website that replacing the original image with another image by using sells products of various categories, such as phones and JavaScript. laptops. To give customers a preview of the appearance of In the ShopForYou.com website, the Product1.png these products, their images are displayed on the product andProduct2.png images display images of the laptop and page. To make the preview of these products appealing to mobile, respectively, on the product page. You need to add the customers, you may want to add effects to the images a feature on the website so that when a customer moves or displayed, such as when a customer places or moves the places the mouse pointer over the image of the laptop or mouse pointer on an image, it appears enlarged or appears mobile, its details are displayed. To accomplish this task, along with some information about that product. This can you need to add the image rollover effect to the be achieved by replacing the image with a larger image of Product1.png andProduct2.png images. the same product or information about that product as To implement the rollover effect, you need to write the plain text, as shown in the following figure. following code in a file and save it as imagerollover.html: <!DOCTYPE HTML><HTML> The Sample Web Page <HEAD> <STYLE> Creating Image Rollover body{ background-color:white; The images can be replaced by other images at runtime by } creating the image rollover effect. JavaScript helps you to h2 { font-family:verdana; font-size:30px; color:darkcyan; text-align:center; } h3 { text-align:center; font-family:verdana; color:darkcyan; font-size:20px; } #para1 { font-family:verdana; font-size:18px; text-align:center; color:darkcyan; } </STYLE> <SCRIPT> function over(img,imgsrc) { img.src=imgsrc; } function out(img,imgsrc) { img.src=imgsrc; } </SCRIPT> </HEAD>
<BODY> The Web Page Displaying the Images of Products <H2> Product Details </H2> In the preceding Product Details Web page, if the mouse <HR><HR> pointer is moved on the image of the laptop, it is replaced <H3> Check out the latest products on by another image that contains information of the product, our website. Exciting Discounts, as shown in the following figure. Hurry !!</H3> <DIV style=\"position:absolute; The Web Page Displaying the Image Rollover Effect top:180px; left:400px;\"> <P ID=\"para1\"> Move the mouse over the Creating Backward Compatible product image </P> Rollover <IMG ID=\"productImage1\" src=\"Product1.png\" height=\"150\" In most of the browsers, such as Firefox and Internet onmouseover=\"over Explorer, the rollover effect can be created on images by (this,'Product1Details.jpg')\" using mouse events. However, in the earlier versions of onmouseout=\"out browsers, mouse events on images cannot be captured. (this,'Product1.png')\"/> Therefore, the rollover effect cannot be added by using the <IMG ID=\"productImage2\" mouse events on images in these browsers. To overcome src=\"Product2.png\" height=\"150\" this limitation, you need to create a backward compatible onmouseover=\"over rollover. (this,'Product2Details.jpg')\" For example, in the ShopForYou.com website, you need to onmouseout=\"out add the rollover effect compatible for all browsers so that (this,'Product2.png')\"/> it can produce the desired output for all the customers, </DIV> irrespective of the browser they are using. </BODY> The backward compatible rollover effect helps capture </HTML> mouse events on images in all the browsers. To implement In the preceding code, two functions, over() and out this effect, you need to use the <A> tag and place all the (), are invoked on the onmouseover and images by using the <IMG> tag within it. The <A> tag can onmouseout events of the <IMG> tag, respectively. The capture mouse events, such as onmouseover and Product1.png and Product2.png images are added to the onmouseout, on the images. Web page by using the <IMG> tag. When the customer Consider the following code snippet that creates the moves the mouse pointer on the Product1.png image, the backward compatible rollover effect: over() function is invoked, which changes the value of <A href=\"#\" onmouseover=\"over()\" the src attribute of the image in the Web page to onmouseout=\"out()\" > Product1Details.jpg. As a result, the Product1.png <IMG ID=\"image1\" image is replaced with the Product1Details.jpg image. src=\"SampleImage1.gif\"> However, when the customer moves the mouse away from </A> the Product1Details.jpg image, the out()function is In the preceding code snippet, the <IMG> tag is placed in invoked, which changes the value of the src attribute of the <A> tag. The <A> tag captures the mouse events on the image in the document to the Product1.png image. the SampleImage1.gif image. The captured events can be Therefore, the Product1.png image is redisplayed on the used to create the rollover effect. page. Similarly, the Product2.png image is replaced with In the preceding examples, you have used only the ID of the Product2Details.jpg image. the image with the src attribute to refer to a single image The following figure shows the output of the preceding and replaced it with another image. However, to code. implement the rollover effect on multiple images, you can
use the document.images array for easy } implementation. The document.images array stores function out(img,imgsrc) reference of all the images in the current document. If a { reference of any image exists in the document.images if (document.images) array, the document.images array returns true. { Therefore, the document.images array can be used to document.images[img].src = imgsrc; check if the images exist or not. } The various images in the document.images array can } be referenced by using either the ID or the index of the </SCRIPT> image as a subscript of the array. For example, the first </HEAD> image in the document can be referred to by using the <BODY> index of the image, as shown in the following code <H2> Product Categories </H2> snippet: <HR><HR> document.images[0] <H3> Check out the latest products on Similarly, the second image is referred to as our website. Exciting Discounts, document.images[1] and so on. Hurry !! </H3> The images in an array can also be referenced by using the <DIV style=\"position:absolute; ID attribute of the image as a subscript of the array, as top:180px; left:450px;\"> shown in the following syntax: <P ID=\"para1\"> Choose the desired document.images [ID]; product image to view the product For example, in the ShopForYou.com website, to details implement the rollover effect on multiple images and to </P> ensure compatibility with all the browsers, you can use the <A href=\"#\" onmouseover=\"over following code on the product page of the ('productImage1','Product1Details.jpg' ShopForYou.com website: );\" onmouseout=\"out <!DOCTYPE HTML><HTML> ('productImage1','Product1.png');\"> <HEAD> <IMG ID=\"productImage1\" <STYLE> src=\"Product1.png\" border=\"0\"/> h2 </A> { <A href=\"#\" onmouseover=\"over font-family:verdana; ('productImage2','Product2Details.jpg' font-size:30px; );\" onmouseout=\"out text-align:center; ('productImage2','Product2.png');\"> } <IMG ID=\"productImage2\" h3 src=\"Product2.png\" border=\"0\"/> { </A> font-family:verdana; </DIV> color:orange; </BODY> font-size:20px; </HTML> text-align:center; In the preceding code, the <IMG> tag defines the image } source of the laptop and mobile, which are Product1.png #para1 and Product2.png, respectively. This tag is placed within { the <A> tag. Therefore, the <A> tag enables you to font-family:verdana; capture mouse events on the Product1.png and font-size:14px; Product2.png images. The over() and out() color:blue; functions are invoked by using the <A> tag. The over() } function is invoked when the user moves the mouse on an </STYLE> image. The out() function is invoked when the customer <SCRIPT> moves the mouse away from an image. Both these function over(img,imgsrc) functions take two parameters, ID and name, of the image { to be replaced. The over() and out() functions check if(document.images) the images in the document by using an array called { document.images. document.images[img].src = imgsrc; } When the customer moves the mouse pointer on the
Product1.png image, the over() function is invoked. Imagename: Is an instance of the Image This function replaces the Product1.png image with the object. Product1Details.jpg image by changing the value of the ImageURL: Is the URL of the image. src attribute to the Product1Details.jpg image. Consider the following code snippet that attaches an image When the customer moves the mouse away from the with the Image object: image, the out() function is called to reset the value of img.src= SampleImage1.gif; the src attribute to the Product1.png image. Similarly, In the preceding code snippet, the src attribute of the the Product2.png image can be replaced with the Image object is used to attach the Product2Details.jpg image. SampleImage1.gif image with the img object. Preloading Images If an HTML document contains multiple images, you need to refer to all the images of the document while preloading Preloading images is a technique to load images in the images. browser cache before the script on the Web page is For example, in the ShopForYou.com website, you can use executed and the Web page is rendered in the browser the Image object to preload the images and implement window. This helps to avoid any delay in loading images the rollover effect. For this, you can use the following from their respective locations, and then displaying these code: images on the Web page. The Image object can be used <!DOCTYPE HTML><HTML> to preload images in an application. To use the Image <HEAD> object, an instance of the Image object needs to be <STYLE> created and the actual images need to be attached to the table{ Image object in the head section. It ensures that the text-align:center; images are loaded in memory before the body of the page } gets loaded. h2 { The browser cache is used to store the downloaded font-family:verdana; files so that the files are not required to be downloaded again font-size:30px; and instead can be used from the browser cache when the text-align:center; user revisits a page. } h3 The following syntax is used to create an instance of the { Image object: font-family:verdana; var Imagename= new Image([Width], color:orange; [Height]); font-size:20px; In the preceding syntax: text-align:center; } Imagename: Is the name of the new instance of #para1 the Image object. { [Width]: Is the width of the image in pixels. font-family:verdana; [Height]: Is the height of the image in pixels. font-size:14px; While instantiating the Image object, both, the [Width] color:blue; and [Height] parameters, are optional. text-align:center; Consider the following code snippet that creates an } instance of the Image object: </STYLE> var img = new Image(40,30); <SCRIPT> In the preceding code snippet, img is the name of the var images; instance of the image object. The width and height of the function preloadimages() image are assigned the values, 40 and 30, respectively. { After instantiating an image object, you need to associate images = new Array the image with the Image object. For this, the src ('product1.png','product2.png','produc attribute of the Image object is used. The syntax for t1details.jpg','product2details.jpg'); attaching an image to an instance of the Image object is: } Imagename.src=\"ImageURL\" function over(a) In the preceding syntax: { document.images[a].src=images[a+2]; }
function out(a) page. For this, you need to use jQuery plugins to create the { image gallery. The jQuery plugins are prewritten and easy to use programs to enhance the jQuery code. By using document.images[a].src=images[a]; jQuery plugins, you can create the image gallery by } displaying the images dynamically at runtime on the same </SCRIPT> Web page. The jQuery plugins can be used to create an </HEAD> image gallery by: <BODY onLoad=preloadimages()> <H2> Product Categories </H2> Using colorbox plugin <HR><HR> Using galleria plugin <H3> Check out the latest products on The light-weight, colorbox plugin enables displaying a our website. Exciting Discounts, collection of images one by one by using the previous and Hurry !!</H3> next buttons. The colorbox plugin can be used to display <DIV style=\"position:absolute; an image with a variety of transition effects, such as fade top:180px; left:400px;\"> or elastic, in the middle of an elegant frame. This frame is <P ID=\"para1\"> Move the mouse cursor known as lightbox and is created at the center of the Web over the product image to view the page over a translucent film surrounding it. The colorbox product details plugin can be used effectively for creating and displaying </P> an image gallery or a slideshow of images on the Web <TABLE border=\"0\"> page where the image sequence can be controlled by using <TR> the previous and next buttons. To create an elegant image <TD> gallery or a slideshow on a Web page, you can download <IMG src=\"product1.png\" the colorbox.zip file that contains the necessary folders onmouseover=\"over(0)\" onmouseout=\"out and files to implement the colorbox plugin functionalities. (0)\" /> Then, you can extract the colorbox folder from the </TD> colorbox.zip file. The colorbox folder comprises the <TD> following folders: <IMG src=\"product2.png\" onmouseover=\"over(1)\" onmouseout=\"out colorbox: This folder comprises the (1)\" /> jquery.colorbox.js file, which is the colorbox </TD> plugin file. This colorbox plugin file is used to </TR> implement the lightbox, slideshow, and the </BODY> transition effects to display images in the image </HTML> gallery. In the preceding code, an array of images is created in the example1, example2,example3, example4, and preloadimages() function. This array is passed as a example5: These folders contain sample parameter to the preload() function. In the preload implementation of the colorbox plugin. Each ()function, the images are preloaded by using the Image folder illustrates a unique and customized object. The images of the document are referred to by implementation of the colorbox plugin to create using the document.images array inside the over() an image gallery or a slideshow. Each of these and out() functions. folders contains the following subfolders and files: Creating Image Gallery colorbox.css: This style sheet contains the Consider the scenario of ShopForYou.com where an formatting instructions to stylize, position, image gallery is used to display images of the products and decorate the image gallery as it is available at the website. An image gallery is a collection created by using the colorbox plugin. For of thumbnail pictures or image links. All of these can be example, background of the Web page, clicked individually to provide a large view of the border of the image, and the previous, next, corresponding product on another Web page. This image and close buttons. gallery is implemented by using JavaScript. A images folder: This folder contains images disadvantage of this feature is that to preview an image, that can be used to create and control the the customer needs to navigate to the previous page image gallery or slideshow. These images repeatedly. can be stylized and positioned on the Web To avoid repeated navigation from a page to the previous page according to the instructions specified page, you can display the full-size image on the same in the colorbox.css style sheet. index.html: This Web page is used to illustrate how the image gallery can be
displayed by using the elastic, fade, or no andcontentFiles folders on your computer: transition effects. In addition, this Web page <!DOCTYPE HTML> is used to display a slideshow of the <HTML> images. Colorbox is a jQuery plugin. Therefore, to implement the <HEAD> functionality provided by this plugin, you need the <LINK media=\"screen\" jquery-1.8.3.js file. In addition, you need the rel=\"stylesheet\" href=\"CSS/ jQuery event method, document.ready(), which is colorbox.css\" /> required to invoke the colorbox plugin to implement the <SCRIPT src=\"jQueryS/ slideshow or image gallery functionality. jquery-1.8.3.js\"></SCRIPT> <SCRIPT src=\"jQueryS/ Slideshow is used to display images one by one after a jquery.colorbox.js\"></SCRIPT> defined duration without using the previous and next buttons. <SCRIPT type=\"text/javascript\"> However, in the image gallery, the user is required to use the previous and next buttons to scroll through all the images. $(document).ready(function(){ $(\"a\").colorbox(); Let us consider an example to implement the colorbox plugin and create a lightbox for the image, Product1.png. }); For this, you need to perform the following steps: </SCRIPT> </HEAD> 1. Create a folder, such as demo, in any drive of <BODY> your system. <H1>Product Demonstration</H1> <A href=\"contentFiles/ 2. Copy the downloaded colorbox folder to this Product2.png\">Laptop</A> folder. </BODY> </HTML> 3. Create the jQueryS, CSS, andcontentFiles In the preceding code, a represents the <A> folders in the demo folder. This is done to ensure element defined inside the <BODY> element. The that the jquery file (jquery-1.8.3.js), jquery colorbox() method of the colorbox plugin is plugin file (jquery.colorbox.js), style sheet used to display the Product1.png image inside (colorbox.css), and images (Product1.png) to be the lightbox. used are stored separately for easy 10. Open the LightboxDemo.html file in Microsoft implementation. Internet Explorer. You can create the folder by any name of Click the Allow blocked content button if the your choice. In fact, it is not necessary to create a following message is displayed: new folder. This is done to ensure that all your Internet Explorer restricted this webpage from related files are stored at one place. Depending on running scripts of ActiveX controls. the storage location of your files, you need to 11. Click the Laptop hyperlink. The slide view of the specify the relative or absolute path of the product image is displayed with the default respective files in the src attribute of the transition effect by using lightbox, as shown in <SCRIPT> tag. the following figure. 4. Copy the jquery.colorbox.js file from the The Lightbox Displaying Product Image colorbox folder available in the downloaded In the preceding figure, lightbox displays a single colorbox plugin folder to thejQueryS folder. image with the default transition effects. However, you can customize the display of 5. Copy the colorbox.css file from the example1 images in an image gallery or a slideshow by folder available in the downloaded colorbox using the colorbox plugin. For this, the colorbox plugin folder to theCSS folder. plugin provides several keys, which need to be 6. Copy the downloaded jquery-1.8.3.js jQuery file to thejQueryS folder. 7. Copy the Product2.png file to the contentFiles folder. 8. Copy the images folder from the example1 folder available in the downloaded colorbox plugin folder to the CSS folder. 9. Type the following code in Notepad, and save the file as LightboxDemo.html at the same location where you have created the jQueryS, CSS,
passed as parameters to the colorbox() the first image in a method. The following table lists the keys that group of five images is can be used with the colorbox() method. displayed. Its default value is image Key Description slideshow {current} of transition speed It specifies the type of {total}. The width transition, such as fade, elastic, or {current} is detected height none, required for an and replaced with the image on the Web page. actual number of innerWidth Its default value is images being displayed innerHeight elastic. while ColorBox runs. current {total} is detected and It specifies the speed of replaced with the actual transition with which number of images in the the image is displayed. gallery. Its default value is 350 milliseconds. It specifies whether the slideshow of images It specifies the total needs to be created width of the frame in when multiple images which the image is are grouped together displayed. Its default for preview. Its default value is false, which value is false. means that the width of the frame is not fixed The Keys of the Colorbox Plugin and varies according to Consider the following code to create a lightbox by the width of the image. specifying the height and width of the frame in which the image is displayed: It specifies the total <!DOCTYPE HTML> height of the frame in <HTML> which the image is displayed. Its default <HEAD> value is false, which <LINK media=\"screen\" means that the height of rel=\"stylesheet\" href=\"CSS/ the frame is not fixed colorbox.css\" /> and varies according to <SCRIPT src=\"jQueryS/ the height of the image. jquery-1.8.3.js\"></SCRIPT> <SCRIPT src=\"jQueryS/ It specifies the inner jquery.colorbox.js\"></SCRIPT> width of the frame in <SCRIPT type=\"text/javascript\"> which the image is displayed. This does not $(document).ready(function(){ include the border and $(\"a\").colorbox({transition:\"fade\", buttons. height:\"250\", width:\"220\"}); It specifies the inner }); height of the frame in </SCRIPT> which an image is </HEAD> displayed. This does not <BODY> include the border and <H1>Product Demonstration</H1> buttons. Its default <A href=\"contentFiles/ value is false. Product2.png\">Laptop</A> </BODY> It specifies the text that </HTML> appears when multiple images are displayed by The preceding code creates a lightbox of height 250 px using lightbox, such as and width 220 px and displays the image inside this image 1 of 5 when lightbox by using the fade transition. The output of the preceding code after the Product1 photo link is clicked is displayed, as shown in the following figure.
The Lightbox Displaying Product Image href=\"contentFiles/ Product2.png\"></A> You can also control the display of a set of images in an <A rel=\"collection\" image gallery with the previous and next buttons. To href=\"contentFiles/ display a set of images or a group of images by using a Product3.png\"></A> lightbox, you need to add a link to each image by using </BODY> the <A> tag and specify the same value for the rel </HTML> attribute of each <A> tag defined for the images. The rel In the preceding code, the rel attribute of each attribute indicates the relationship between the current <A> tag defined inside the body tag is specified document and the path specified by the href attribute. By with the value, collection. This ensures that providing the same value for the rel attribute for all the the images having the same value for the rel attribute are grouped together so that these images, these can be related to a single group. images can be displayed as part of a single image Suppose, you need to create a lightbox for the set of gallery. images, Product1.png, Product2.png, and When you save the preceding code in an HTML file, and Product3.png. For this, you need to perform the then open it in Microsoft Internet Explorer, the Click here following steps: to view hyperlink is displayed. When you click the 1. Copy the Product2.png and Product3.png files hyperlink, the output is displayed with the previous to the contentFiles folder. and next buttons, as shown in the following figure. 2. Type the following code in Notepad, and save the file as LightboxGroupDemo.html at the same The Product Image with the Previous and Next Buttons location where you have created the jQueryS, CSS, andcontentFiles folders on your computer: Click the Allow blocked content button if the <!DOCTYPE HTML> following message is displayed: <HTML> Internet Explorer restricted this webpage from running <HEAD> scripts of ActiveX controls. <LINK media=\"screen\" You can create a slideshow of images by grouping these rel=\"stylesheet\" href=\"CSS/ images by using the colorbox plugin. For this, you need to use the same value for the rel attribute for all the images colorbox.css\" /> to be displayed in the <A> tag and set the slideshow <SCRIPT src=\"jQueryS/ key of the colorbox() method to true. Consider the following code that creates a slideshow and jquery-1.8.3.js\"></SCRIPT> saves it as SlideShow.html: <SCRIPT src=\"jQueryS/ <!DOCTYPE HTML> <HTML> jquery.colorbox.js\"></SCRIPT> <SCRIPT type=\"text/javascript\"> <HEAD> $(document).ready(function(){ <STYLE> $(\"a\").colorbox(); body{ }); Background-color: \"silver\";} </SCRIPT> </STYLE> <LINK media=\"screen\" </HEAD> rel=\"stylesheet\" href=\"css/ <BODY> <H1>Product Demonstration</H1> <A rel=\"collection\" href=\"contentFiles/ Product1.png\">Click here to view</A> <A rel=\"collection\"
colorbox.css\" /> Using galleria Plugin <SCRIPT src=\" jQueryS/ The galleria plugin is the jQuery plugin used for creating jquery-1.8.3.js\"></SCRIPT> elegant and professional-looking image galleries. This <SCRIPT src=\" jQueryS/ plugin is used to display an image gallery and create thumbnails of the images to be displayed in the gallery jquery.colorbox.js\"></SCRIPT> automatically. When the mouse pointer is moved on a <SCRIPT> thumbnail image, a larger version of the image is $(document).ready(function(){ displayed by using a transition effect on the same Web $(\"a\").colorbox page. Unlike the colorbox plugin, the galleria plugin cannot be used to create a slideshow of images, but the ({slideshow:true,current:false}); galleria plugin has the ability to create thumbnails of the images to be displayed in the image gallery. }); To create an image gallery by using the galleria plugin, </SCRIPT> you need to download the galleria.zip file from the </HEAD> Internet and extract the galleria folder from the <BODY> galleria.zip file at a desired location on your system. The <A href=\" contentFiles/Product1.png\" galleria folder comprises the galleria-1.2.8.js file, which rel=\"collection\">Click Here to View is the galleria plugin to be used to implement the Slideshow of Products Available at the functionality of creating the image gallery. Site </A> Activity 7.2: Creating an Image <A href=\" contentFiles/Product2.png\" Gallery rel=\"collection\"></A> <A href=\" contentFiles/Product3.png\" Summary rel=\"collection\"></A> </BODY> In this chapter, you learned that: </HTML> jQuery is an open source and cross-browser In the preceding code, the slideshow key is set to true library of JavaScript codes that was created to to create a slideshow of the images. The value of the make the JavaScript programming simpler. current key is set to false. This prevents displaying You can make use of jQuery in a Web page to the text depicting the number of the current image, such as manipulate HTML elements by downloading the image 2 of 5, during the slideshow. The output of the light-weight jQuery JavaScript library and saving preceding code is shown in the following figure. it to your system. To ensure that a Web page is fully loaded before The Slideshow of the Images the jQuery code is executed on it, jQuery provides the document.ready() function. Using jQuery, HTML elements can be selected by referring to their name, ID, or class to which they belong. jQuery provides CSS selectors to modify the CSS properties of an HTML element or document. In jQuery, events are handled by using functions or predefined event methods. Some of the predefined jQuery effects that can be used to add visual appeal to a Web page are: Hide Show Toggle Slide
Fade Animate Image rollover is an effect in which the appearance of an image changes when the mouse pointer is placed or moved on it. Preloading images is a technique to load images in the browser cache before the script on the Web page is executed and the Web page is rendered in the browser window. The Image object can be used to preload images in an application. An image gallery is a collection of thumbnail pictures or image links. By using jQuery plugins, you can create the image gallery by displaying the images dynamically at runtime on the same Web page. The light-weight, colorbox plugin enables displaying a collection of images one by one by using the previous and next buttons. The galleria plugin is the jQuery plugin used for creating elegant and professional-looking image galleries. Reference Reading Exploring jQuery Reference Reading: Books Reference Reading: URLs JavaScript: the complete http://www.w3schools.com/ reference By Thomas A. jquery/default.asp Powell, Fritz Schneider http://jquery.com/ Adding Visual Effects Using jQuery Reference Reading: Books Reference Reading: URLs JavaScript: the complete http://api.jquery.com/ reference By Thomas A. category/effects/ Powell, Fritz Schneider Implementing Image Rollover Reference Reading: Books Reference Reading: URLs JavaScript: the complete http://www.irt.org/articles/ reference By Thomas A. js132/ Powell, Fritz Schneider Creating Image Gallery Reference Reading: Books Reference Reading: URLs JavaScript: the complete http://monc.se/kitchen/146/ reference By Thomas A. galleria-a-javascript-image- Powell, Fritz Schneider gallery
Chapter 8 Introducing Geolocation and Offline Support for Data You are visiting a city for the first time and looking for Implementing the Geolocation API sight-seeing locations close to your hotel. However, you do not know where to go and which places to look for. The Geolocation API allows a website to retrieve the Therefore, it will be helpful if you have some application current geographical location of a user. This API enables that can help you locate such places and provide feedback you to create applications that guide users how to reach a for the same. This can be done by implementing target location from their current location. An example of Geolocation API. such an application is a map application that gives In addition, you may need that users are able to access a directions to a target location. Web page even when they are not connected to the The users’ location is not retrieved just through code or Internet. browser. Instead, the Geolocation API uses certain This chapter introduces you to the Geolocation API. features, such as Global Positioning System (GPS), Further, it discusses how to implement offline support in Internet Protocol (IP) address of a device, nearest mobile websites. phone towers, and input from a user, in the users’ device to retrieve the users’ location. Objectives The users’ location retrieved by using the Geolocation API is almost accurate depending upon the type of source used In this chapter, you will learn to: to retrieve the location. For example, the IP address gives Implement Geolocation a location that can be close to the users’ location; while, Implement Offline Support the GPS is able to give more accurate results. Identifying the users’ location may, at times, compromise Implementing Geolocation the users’ privacy. Hence, the location of users is not available unless they approve it. A prompt appears that ShopHere is a large retail store based in Ohio. The store asks the users if they would like to share their current offers clothes, accessories, and footwear. In addition, it location and also specifies the reason for collecting this sells the home furnishing goods and electronic items, such data. In addition, it should specify where the data will be as refrigerator, air conditioner, laptops, and mobile shared. devices. As part of its business strategy to attract new Geolocation is most beneficial with applications used for customers and build a stable customer base, the store mobile devices. This is because while the users are offers discounts and special deals on products. In addition, travelling, the Geolocation API keeps updating their the official website of the store has a feature that enables locations. In case of desktop applications, the users’ users to share their current location, based on which, they location remains constant and can be set only once. are guided to reach the nearest store. The Geolocation API provides the following methods to Such a feature is incorporated in websites by using the determine the users’ location: Geolocation API. The Geolocation API-enabled website can locate users’ current geographical location, display getCurrentPosition() points of interest around that location, or guide the users watchPosition() from their current location to a target destination. getCurrentPosition()
The getCurrentPosition() method is used to var geo=navigator.geolocation retrieve the current geographical location of a user. The else location is retrieved as a set of coordinates. { The syntax of the getCurrentPosition() method alert(\"Your browser does not support is: geolocation\") getCurrentPosition(CallbackFunction, } ErrorHandler, Options); The preceding code snippet checks whether the geolocation feature is supported by the browser. If it is not In the preceding syntax: supported, a relevant message is displayed. CallbackFunction: This is a function Consider the following code snippet for retrieving the defined by the developer to retrieve the current users’ location by using the getCurrentPosition() location. method: ErrorHandler: This is the name of a function <!DOCTYPE HTML> that is called when an error occurs while <HTML> retrieving the location of a user. This is an <BODY> optional parameter. <P ID=\"button\">Click here to know your Options: This optional parameter specifies a set location coordinates:</P> of options, such as timeout for retrieving the <BUTTON onclick=\"getLocation()\">Get location information, used for retrieving the Location</Button> information about the users’ geographical <SCRIPT> location. var geo=document.getElementById (\"button\"); The getCurrentPosition() method calls function getLocation() callbackFunction, which takes the position object as { an argument. This object specifies the current geographic if (navigator.geolocation) location of a user as a set of geographic coordinates. The { position object returns two properties, coords and navigator.geolocation.getCurrentPositi timestamp, on the successful retrieval of the location. on(getPosition); The timestamp property returns the date and time when } the location was retrieved. The coords property returns else{geo.innerHTML=\"Geolocation is not various attributes, such as latitude and longitude. supported by this browser.\";} These attributes are described in the following table. } function getPosition(position) Attribute Description { geo.innerHTML=\"Latitude: \" + coords.latitude Specifies the latitude as a position.coords.latitude + \"<BR>Longitude: \" + decimal number. position.coords.longitude; } coords.longitude Specifies the longitude as a </SCRIPT> </BODY> decimal number. </HTML> The preceding code snippet creates the Get Location coords.accuracy Specifies the accuracy of button, which, on clicking, calls the getLocation() method. This method first checks whether the geolocation position. feature is supported by the browser. If this feature is supported, the getCurrentPosition() method is coords.altitude Specifies the altitude in called. This method calls the getPosition() method that retrieves the users’ location in the form of latitude and meters above the sea level. longitude values. coords.altitudeAccu Specifies the accuracy of The innerHTML property is used to set or retrieve the text of an HTML element. racy altitude. The Attributes of the coords Property Before retrieving the users’ location by using the getCurrentPosition() method, you need to check whether the browser supports the geolocation feature. For this, you can use the geolocation property of the navigator object. The navigator object contains the information about a browser. Consider the following code snippet to check whether the browser supports the geolocation feature: if(navigator.geolocation)
Due to security reasons and firewall restrictions, you parameter of this method is an error handler function. This may not always get the latitude and longitude coordinates. function can handle the following error codes: watchPosition() PERMISSION_DENIED: Specifies that the user has declined the request to share the location. The watchPosition() method returns the current POSITION_UNAVAILABLE: Specifies that the location of a user and continuously updates the location while the user is moving. It is mostly used in devices, such users’ current location cannot be retrieved. as GPS, which inform the users about the current location TIMEOUT: Specifies that the time given to while they are travelling. The watchPosition() retrieve the users’ location has exceeded the method takes the same parameters as the maximum limit. getCurrentPosition() method and returns the UNKNOWN_ERROR: Specifies that an unknown or same object. undefined error has occurred. Consider the following code snippet for retrieving the The error handler function accepts the PositionError users’ location by using the watchPosition() object as an argument. This object has two properties, method: code and message. The code specifies the error code, function getLocation() and the message specifies the message that is to be { displayed when an error occurs. if (navigator.geolocation) Consider the following code snippet for handling errors while retrieving the users’ location: { function showError(PositionError) navigator.geolocation.watchPositio n(getPosition); { } switch(PositionError.code) else{geo.innerHTML=\"Geolocation is not supported by this browser.\";} { } case function getPosition(position) PositionError.PERMISSION_DENIED: { geo.innerHTML=\"Latitude: \" + x.innerHTML=\"User denied the position.coords.latitude + request for tracking the location\" \"<br>Longitude: \" + position.coords.longitude; break; } case The preceding code snippet continuously retrieves the PositionError.POSITION_UNAVAILABLE: user’s location by using the watchPosition() method while the user is travelling. x.innerHTML=\"User's location is You can also stop tracking the users’ location by using the not available\" clearWatch() method. This method stops the call to the watchPosition() method. break; case PositionError.TIMEOUT: Handling Errors x.innerHTML=\"The request to retrieve user's location is timed out\" break; case PositionError.UNKNOWN_ERROR: x.innerHTML=\"An unknown error occurred\" break; } At times, the user may not provide the permission to } access his location. This may raise an error in your The preceding code snippet creates the function, website. The error may also occur when a user checks the showError(), which is called when an error occurs current location on a mobile device and the device goes while retrieving the users’ location. This function accepts out of coverage area or the network connection is timed an error code which is defined in the switch construct. out. As a website developer, you need to ensure that your For example, if the user denies the access to his location, website is able to handle errors effectively. For this, you the error,User denied the request for need to consider all possible causes of errors that can tracking the location, is displayed on a Web occur in an application and can be dealt with effective page. error-handling technique. To handle errors in a geolocation-enabled website, you can use the getCurrentPosition() method. The second
following ways: Implementing client-side storage Implementing application cache Implementing Offline Support Implementing Client-side Storage At times, you must have noticed that while you are surfing The client-side storage refers to the process of storing data a website, a message, such as ‘Browser could not open the locally within the user’s browser. This is also known as Web page’, is displayed. This is because the connection to Web storage. The data stored by using client-side storage the Internet is lost. In such a case, you do not have access is retrieved only when it is requested, and not with every to the website that you were surfing. However, if you want server request. Moreover, you can store a large amount of to have some level of access to the website even if you are data by implementing the client-side storage, where the not connected to the Internet, you can use the offline data is stored in the form of key/value pairs. support feature. For example, the executives of ShopHere The client-side storage can be implemented by using the often need to visit different cities to advertise their following objects: products. They need to access the organization’s website during their promotional tours. However, the website is localStorage not accessible every time, especially in the remote areas sessionStorage where the network is not available. In such a case, the offline support feature of HTML can be used to ensure that localStorage the website is accessible to the executives even without the Internet connection. In addition, using the offline The localStorage object allows you to store data support feature avoids the normal network requests needed without any expiration date. This implies that the data to load a website. stored by using the localStorage object is not deleted after the browser is closed, and it will be available when Before the offline support feature of HTML, the offline the browser is reopened. The localStorage object storage-enabled websites were created using cookies and stores the data only in the form of string. Using this object, plugins. A cookie is a small piece of data, which is sent the cached data is accessible across all browser windows. from a website and stored in a user’s browser while the Consider the following code snippet for storing the users’ user browses the website. When the user revisits the same information by using localStorage: website, the data stored in the cookie is retrieved. Cookies <DIV ID=\"str\"></DIV> are not purely used for offline storage as they store a <SCRIPT> limited amount of data. In addition, cookies slow down the if(typeof(Storage)!==\"undefined\") network activity because they are transferred to and from the server. { These limitations are overcome with the help of the offline localStorage.name=\"John\"; support feature of HTML. The offline support feature document.getElementById provides the following benefits: (\"str\").innerHTML=\"Name: \" + localStorage.name; Ensures that the website is available even when } the user is not connected to the network. else Reduces network load on the server. { You can make your website work offline by using the document.getElementById (\"str\").innerHTML=\"Your browser does not support local storage\"; } </SCRIPT> In the preceding code snippet, the typeof() method first checks whether the browser supports the Web storage or not. If it does, thelocalStorage object stores the user’s name locally in the browser by using the key, name, which is assigned the value, John. Later, the information stored in the localStorage object is retrieved by using the key and is assigned to the innerHTML property of the <DIV> tag that has ID, str. The text, Your browser does not support
local storage, is displayed inside the <DIV> tag if () function that is called when the button is clicked. the browser does not support the Web storage. Inside the function body, the typeof() method first checks whether the browser supports the Web storage or sessionStorage not. If it does, the clickCount key is used with the sessionStorage object to store the count or number The sessionStorage object is used to store the data of times the user has clicked the button during the current for only one session. This implies that the data is deleted session. The value of the key, clickCount, is increased once the user closes the browser. The data stored by using by one every time the user clicks the button. Since the sessionStorage is confined to the browser for which value assigned to the key of the sessionStorage it was created. Consider an example where you need to object is always a string, it is converted into a number count the number of times a user has clicked a button in before incrementing by one, by using the Number() the current session. For this, you can use method. thesessionStorage object, as shown in the following The most recent value stored inside the code snippet: sessionStorage object is retrieved by using the key, <HEAD> clickCount, and is assigned to the innerHTML <SCRIPT> property of the <DIV> tag that has ID, btn, which is function clickCounter() displayed before the user. { if(typeof(Storage)!==\"undefined\") Implementing Application Cache { While browsing a website, you must have faced a situation if (sessionStorage.clickcount) when the network connection is lost and you click the Back button in the browser to view the previous page. { However, you are not able to view that page as you are not sessionStorage.clickcount=Number connected to the Internet, and the browser did not cache (sessionStorage.clickcount)+1; the page properly. To view the previous page in such a } situation, you need to reconnect to the Internet. To address else such issues, while developing a website, you can specify { the files the browser should cache so that even if you sessionStorage.clickcount=1; refresh the page when you are offline, you are able to view } the page. This process of caching a website is known as document.getElementById application cache. (\"btn\").innerHTML=\"You have clicked The application cache provides the following advantages: it\" + Offline browsing: Specifies that a website can be sessionStorage.clickcount + \" time(s) viewed even if the user is not connected to the in this session.\"; Internet. Speed: Specifies that if the user requests the Web } page, which is already there in the cache, it is else retrieved from the cache and not from the server. Therefore, the loading of the Web page is faster { as the network is not accessed as the connection document.getElementById to the server is not needed. (\"btn\").innerHTML=\"Your browser does Reduced server load: Specifies that the Web not support Web storage\"; page, if cached, will always be made available } from the cache unless the browser detects that the } cache manifest has been updated on the server or </SCRIPT> the user has cleared the browser cache. Then, the </HEAD> browser downloads a new version of the manifest <BODY> and the resources listed in the manifest. <p><BUTTON onclick=\"clickCounter()\" Therefore, the number of requests sent to the type=\"button\">Click Here</BUTTON></P> server are less; thereby, reducing the load on the <DIV ID=\"btn\"></DIV> server. <P>Click the button to see the To implement application cache, you need to create a text increase in counter.</P> file called manifest. This file contains a list of resources <P>Close the browser and try again, the counter will be reset.</P> </BODY> The preceding code snippet creates the clickCounter
that needs to be cached for use when there is no network Activity 8.1: Implementing connectivity. The manifest file also contains the list of Offline Support files or pages that should never be cached. You need to save the manifest file with the .appcache extension. The manifest file is divided into the following sections: Cache: Lists the files that need to be cached after they are downloaded for the first time. Network: Lists the files that should never be cached. Fallback: Specifies the task to be performed when a user tries to fetch the uncached files. To refer to a manifest file in an HTML document, you need to add the manifest attribute in the opening<HTML> tag, as shown in the following code snippet: <HTML manifest=\"HotelFacilities.appcache\"> The preceding code snippet enables the application cache for the HotelFacilities.appcache manifest file. Once you have cached an application on the local machine, the browser shows the cached file even if it has been changed or updated on the server. Therefore, to ensure that the browser updates the cache, you need to modify the manifest file. Summary In this chapter, you learned that: The Geolocation API allows a website to retrieve the current geographical location of a user. The Geolocation API provides the following methods to determine the users’ location: getCurrentPosition() watchPosition() To handle errors in a geolocation-enabled website, you can use the getCurrentPosition() method. The second parameter of this method is an error handler function. The offline support feature provides the following benefits: Ensures that the website is available even when the user is not connected to the network Reduces network load on the server The client-side storage refers to the process of storing data locally within the user’s browser. The client-side storage can be implemented by using the following objects: localStorage sessionStorage The localStorage object allows you to store data without any expiration date. The sessionStorage object is used to store the data for only one session. This implies that the data is deleted once the user closes the browser.
To implement application cache, you need to create a text file called manifest. You need to save the manifest file with the .appcache extension. Reference Reading Implementing Geolocation Reference Reading: Books Reference Reading: URLs The Definitive Guide to http://diveintohtml5.info/ HTML5 By Adam Freeman geolocation.html http://www.w3schools.com/ html/html5_geolocation.asp Implementing Offline Support Reference Reading: Books Reference Reading: URLs The Definitive Guide to http:// HTML5 By Adam Freeman www.pageresource.com/ html5/local-session-storage- api/
The following table lists the browser support for the various input type elements introduced in HTML5. Appendix Browser Support for HTML5 Elements HTML5 is a new standard for HTML. A lot of new features have been added to HTML5. However, all browsers currently do not provide support for all new features of HTML5. HTML5 New Elements Browser Support for Input Type Elements Introduced in HTML5 The following table lists the browser support for the HTML5 Form and Input Attributes various elements introduced in HTML5. The following table lists the browser support for the various form attributes introduced in HTML5. The following table lists the browser support for the various form input type attributes introduced in HTML5. Support for Elements Introduced in HTML5 Browser Support for Input Type Attributes Introduced in HTML5 HTML5 Input Types
The preceding table is based on support provided for HTML5 and CSS3 by the following popular browsers: Internet Explorer 10 Firefox 13.0.1 Opera 12.00 Google Chrome 20.0.1132.47 Safari 5.1.7 Please check for support provided for HTML5 and CSS3 in the version of browser you are using. Disclaimer: The support provided by various browsers for all the features of HTML5 listed in the preceding tables has been examined for accuracy and appropriateness at the time of addition. However, the same cannot be guaranteed over time as the browsers may start supporting more features of HTML5 in the near future.
Glossary Dynamic Web page It is a Web page that responds to user actions or is A dynamically created by a Web program on the basis of a Animation user's request. It is a visual technique that provides the illusion that an object is moving by displaying graphic objects in a rapid E sequence. Event Arithmetic Operator It is an action that happens on a Web page, such as a It is used to perform arithmetic operations on variables mouse click or loading of a Web page. and literals. Event Listener Assignment Operator It is an object that waits for an event to occur and performs It is used to assign a value or the result of an expression to certain actions corresponding to it. a variable. F B Form Break It is an interactive Web page that is used to accept the user This statement is used to exit the loop. input. Built-in Functions Frames They are ready to use as they are already coded. It provides a mechanism for positioning and displaying several Web pages in different sections of a single browser C window. Canvas Function It is an area on a Web page that acts as a container for It is a self-contained block of statements that has a name. embedding graphic objects. It allows dynamic rendering of G bitmap images and 2D shapes by using JavaScript. Galleria Plug-in Cascading Style Sheets (CSS) It is the jQuery plug-in used to create elegant and It is a collection of styles that allows you to change the professional-looking image galleries. appearance of HTML elements on Web pages. Graph Class Selector It is a way of representing relationships among a It is used to specify styles for a group of elements. It is collection of items. used when there is a need to apply the same style on different types of elements in the HTML document. H Client-side scripting Hyper Text Markup Language (HTML) It refers to scripts that are executed at the client-side by It is a versatile markup language that can be used on the Web browser, running on the user's computer. different Web browsers to publish information as a Web Colorbox Plug-in page. It enables displaying larger size images on the same Web page when a user clicks a hyperlink or an image. I Comments ID Selector These are statements that are not executed by the It is used to identify an element that you need to style interpreter but are used to enhance the readability and differently from the rest of the page. understandability of the code. Images Comparison Operator It is used to add an artistic value to a Web page. It is used to compare two values and perform an action on the basis of the comparison. Image Gallery Conditional Construct It is a collection of thumbnail pictures or image links. It allows you to execute a selective statement or a block of Image Rollover statements based on the result of the expression being It is an effect in which the appearance of an image changes evaluated. when the mouse pointer is placed or moved on it. Continue This statement is used to bring the control to the beginning J of the loop. JavaScript It is used for client-side as well as server-side scripting. D jQuery It is an open source and cross-browser library of JavaScript codes that is created to make the JavaScript programming simpler. L Logical Operator
It is used to evaluate complex expressions in which there W is a need to evaluate a single or multiple expressions to World Wide Web (WWW) assess the result. It is a collection of resources on varied topics that can be Loop Structure accessed through the Internet. It is used to repeatedly execute one or more lines of code. M Markup Language It provides a way to describe the structure of a Web page, specifying how text or graphics are displayed on the Web page. P Path It is a series of points joined together to create lines or shapes. Preloading Images It is a technique to load images in the browser cache before the script on the Web page is executed and the Web page is rendered in the browser window. R Regular Expression It is a set of characters, which is used to specify a pattern. Relative Path It is the path of the file with respect to the current working directory. RGraph It is a JavaScript library that allows you to create different types of graphs on a Web page. S Selector It is used to specify the HTML element that you want to style. You can have one or more selectors in a rule. Server-side scripting It refers to the scripts that are executed by the Web server on the basis of the user's request. Static Web page It is the web page that is delivered to the users exactly as these are stored. The content of these Web pages is not updated dynamically. T Tables They are used for structuring and displaying complex information in a structured format on a Web page. U Uniform Resource Locator It is the unique address of the website or a Web page on the Internet. User-defined Functions These are used to define your own functions according to your needs. V Variable It is a named location in memory that is used to store a value.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149