Dynamically creating a full-featured img element using jQuery

Leave a Comment

In below code, we want to create an image element complete with multiple attributes, some styling, and let’s make it clickable.
$('<img>',
{
src: 'images/little.bear.png',
alt: 'Little Bear',
title:'I woof in your general direction',
click: function(){
alert($(this).attr('title'));
}
})
.css({
cursor: 'pointer',
border: '1px solid black',
padding: '12px 12px 20px 12px',
backgroundColor: 'white'
})
.appendTo('body');

You can append this image to any element. In above example we can append image to body tag.

The single jQuery statement in above code creates the basic <img> element, gives it important attributes, such as its source, alternate text, and flyout title, styles it to look like a printed photograph, and attaches it to the DOM tree.

0 comments:

Post a Comment