- 2.1. Accessing Elements and Protecting the DOM
- 2.2. Editing the Web Page with DHTML ? la jQuery
- 2.3. Animatedly Reducing and Enlarging of an Element
- 2.4. Changing Attributes Dynamically
- Summary
2.4. Changing Attributes Dynamically
This section shows how you can dynamically change attributes for an element of the web page. To this purpose, jQuery offers the extremely flexible and useful method attr(). With this, you can dynamically change one or several attributes of an element. In curly brackets, you set a value pair as parameter, first specifying the attribute, followed by a colon and then a string with the new value. Alternatively, you can also specify two string parameters. In this variation, the first parameter represents the attribute name and the second parameter the value. (In this case, you can change only one attribute.) If you only want to request the value of an attribute, you just enter the name of the attribute as a string parameter.
For our example, we want to replace an image in the web page by changing the value of the attribute src of an <img> tag (ch2_4.html).
Listing 2.7. Changing Attributes on an Element
... 06 <script type="text/javascript" 07 src="lib/jquery-1.8.min.js"></script> 08 <script type="text/javascript"> 09 $(document).ready(function(){ 10 $("#toggle1").click(function(){ 11 $("img").attr({ 12 src: "images/i1.jpg" 13 }); 14 }); 15 $("#toggle2").click(function(){ 16 $("img").attr( 17 "src", "images/i2.jpg" 18 ); 19 }); 20 }); 21 </script> 22 </head> 23 <body> 24 <h1>Replacing an image</h1> 25 <button id="toggle1">Image 1</button> 26 <button id="toggle2">Image 2</button> 27 <hr/><img src="images/i1.jpg"/> 28 </html>
We change the value via the notation in the curly brackets once, and via the two string parameters once. As mentioned earlier, we replace the value src in each case.