Like tables, jQuery also allows you to play around with all other tags. In a recent project, we wanted to change a fixed set of labels/texts into icons instead. For this challenge jQuery was used to build the new image tag, and for good measure, here is a small example of how you can build an image tag – including alt-text and click-event.
The basic code for building and inserting an image into the DOM looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div id="image"></div> <script type="text/javascript"> $(document).ready(function() { $image = $('<img>').attr('src', 'image_polar.jpg'); $image.attr('alt', 'Polar bear'); $image.attr('height', '200').attr('width', '300'); $image.click(function () { alert('You clicked the image'); }); $image.appendTo('#image'); }); </script> |
The code above creates a new image tag. Adds an alt-text and sets the height and width (resizing the image in the browser). Finally it attaches a click-event and inserts the image into the DIV-tag named “image”.