Building image tags with jquery
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:
<script type="text/javascript">
$(document).ready(function() {
<div></div>
$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');
<div></div>
});
</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”.