Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Objects

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Dynamic Styles - DOM

Such style changes can create many effects, including mouse hover effects, interactive menus, and animations.

Dynamic Styles


An element’s style can be changed dynamically. Often such a change is made in response to user events, which we discuss in Chapter 13. Such style changes can create many effects, including mouse hover effects, interactive menus, and animations. Figure 12.4 is a simple example that changes the background-color style property in response to user input.

        <?xml version = "1.0" encoding = "utf-8"?>


        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




        <!-- Fig. 12.4: dynamicstyle.html -->


        <!-- Dynamic styles. -->


        <html xmlns = "">



    <title>Dynamic Styles</title>


      <script type = "text/javascript">



      function start()


var inputColor   = prompt( "Enter a color name for the " +

"background of this page", "" ); = inputColor;


      } // end function start

      // -->






      <body id = "body" onload = "start()">


      <p>Welcome to our website!</p>





Fig. 12.4 | Dynamic styles.

Function start (lines 12–17) prompts the user to enter a color name, then sets the background color to that value. [Note: An error occurs if the value entered is not a valid color. See Appendix B, XHTML Colors, for further information.] We refer to the back-ground color as—the body property of the document object refers to the body element. We then use the style property (a property of most XHTML elements) to set the background-color CSS property. This is referred to as backgroundColor in JavaScript—the hyphen is removed to avoid confusion with the subtraction (-) operator. This naming convention is consistent for most CSS properties.


For example, borderWidth correlates to the border-width CSS property, and fontFamily correlates to the font-family CSS property. In general, CSS properties are accessed in the format


Figure 12.5 introduces the setInterval and clearInterval methods of the window object, combining them with dynamic styles to create animated effects. This example is a basic image viewer that allows you to select a Deitel book cover and view it in a larger size. When one of the thumbnail images on the right is clicked, the larger version grows from the top-left corner of the main image area.


The body (lines 66–85) contains two div elements, both floated left using styles defined in lines 14 and 17 in order to present them side by side. The left div contains the full-size image iw3htp4.jpg, the cover of this book, which appears when the page loads. The right div contains six thumbnail images which respond to the click event by calling the display method and passing it the filename of the corresponding full-size image.


The display function (lines 46–62) dynamically updates the image in the left div to the one corresponding to the user’s click. Lines 48–49 prevent the rest of the function from executing if interval is defined (i.e., an animation is in progress.) Line 51 gets the left div by its id, imgCover. Line 52 creates a new img element. Lines 53–55 set its id to imgCover, set its src to the correct image file in the fullsize directory, and set its required alt attribute. Lines 56–59 do some additional initialization before beginning the animation in line 61. To create the growing animation effect, lines 57–58 set the image width and height to 0. Line 59 replaces the current bigImage node with newNode (created in line 52), and line 60 sets count, the variable that controls the animation, to 0.


Line 61 introduces the window object’s setInterval method, which starts the anima-tion. This method takes two parameters—a statement to execute repeatedly, and an integer specifying how often to execute it, in milliseconds. We use setInterval to call


      <?xml version = "1.0" encoding = "utf-8"?>


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




      <!-- Fig. 12.5: coverviewer.html -->


      <!-- Dynamic styles used for animation. -->


      <html xmlns = "">




      <title>Deitel Book Cover Viewer</title>


<style type = "text/css">

.thumbs {    width: 192px;

       height: 370px;

       padding: 5px;

       float: left }

.mainimg    {    width: 289px;

       padding: 5px;

       float: left }

.imgCover { height: 373px }

img   {     border: 1px solid black }



        <script type = "text/javascript">



        var interval = null; // keeps track of the interval


        var speed = 6; // determines the speed of the animation


        var count = 0; // size of the image during the animation


        // called repeatedly to animate the book cover


        function run()


count += speed;


// stop the animation when the image is large enough

if ( count >= 375 )


window.clearInterval( interval );

interval = null;

} // end if


var bigImage = document.getElementById( "imgCover" ); = .7656 * count + "px"; = count + "px";


        } // end function run

        // inserts the proper image into the main image area and


        // begins the animation


        function display( imgfile )


if ( interval    )



var bigImage = document.getElementById( "imgCover" );

var newNode =    document.createElement( "img" ); = "imgCover";

newNode.src =    "fullsize/" + imgfile;

newNode.alt =    "Large image";

newNode.className = "imgCover"; = "0px"; = "0px";

bigImage.parentNode.replaceChild( newNode, bigImage );

count = 0; //    start the image at size 0

        interval = window.setInterval( "run()", 10 ); // animate


        } // end function display

        // -->








        <div id = "mainimg" class = "mainimg">


        <img id = "imgCover" src = "fullsize/iw3htp4.jpg"

        alt = "Full cover image" class = "imgCover" />




        <div id = "thumbs" class = "thumbs" >


        <img src = "thumbs/iw3htp4.jpg" alt = "iw3htp4"

        onclick = "display( 'iw3htp4.jpg' )" />


        <img src = "thumbs/chtp5.jpg" alt = "chtp5"

        onclick = "display( 'chtp5.jpg' )" />


        <img src = "thumbs/cpphtp6.jpg" alt = "cpphtp6"

        onclick = "display( 'cpphtp6.jpg' )" />


        <img src = "thumbs/jhtp7.jpg" alt = "jhtp7"

        onclick = "display( 'jhtp7.jpg' )" />


        <img src = "thumbs/vbhtp3.jpg" alt = "vbhtp3"

        onclick = "display( 'vbhtp3.jpg' )" />


        <img src = "thumbs/vcsharphtp2.jpg" alt = "vcsharphtp2"

        onclick = "display( 'vcsharphtp2.jpg' )" />







Fig. 12.5 | Dynamic styles used for animation.

function run every 10 milliseconds. The setInterval method returns a unique identifier to keep track of that particular interval—we assign this identifier to the variable interval. We use this identifier to stop the animation when the image has finished growing.


The run function, defined in lines 28–42, increases the height of the image by the value of speed and updates its width accordingly to keep the aspect ratio consistent. Because the run function is called every 10 milliseconds, this increase happens repeatedly to create an animated growing effect. Line 30 adds the value of speed (declared and ini-tialized to 6 in line 24) to count, which keeps track of the animation’s progress and dictates the current size of the image. If the image has grown to its full height (375), line 35 uses the window’s clearInterval method to stop the repetitive calls of the run method. We


pass to clearInterval the interval identifier (stored in interval) that setInterval created in line 61. Although it seems unnecessary in this script, this identifier allows the script to keep track of multiple intervals running at the same time and to choose which interval to stop when calling clearInterval.


Line 39 gets the image and lines 40–41 set its width and height CSS properties. Note that line 40 multiplies count by a scaling factor of .7656 in order to keep the ratio of the image’s dimensions consistent with the actual dimensions of the image. Run the code example and click on a thumbnail image to see the full animation effect.


This section demonstrated the concept of dynamically changing CSS styles using JavaScript and the DOM. We also discussed the basics of how to create scripted animations using setInterval and clearInterval.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.