jQuery

jQuery Change Image SRC Attribute Examples

Ever wanted to change image src at the click of a button using jQuery? In this article, I am going to share different way to change image source attribute using jQuery with different examples.

Examples on how to Change Image SRC (source) using jQuery

For the sake of demo, I am assuming that we already have an image in the page and we need to change img src of this image when the “Change Source” button is clicked.

Common HTML Source code for all the following examples:

<html>
<head>
<title>Change Image Source</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<img src="images/1.jpg" id="img" class="img_class" style="color:#03C;" />

<input type="submit" name="change_src" id="change_src" value="Change Source" />

</body>
</html>

Example 1 – Change Image Source Attribute using image ID in jQuery

<script type="text/javascript">

$('#change_src').click(function() {

$('#img').attr('src','somedir/some_image_name.jpg');

});

</script>

Example 2 – Change Image Source Attribute using image Class in jQuery

<script type="text/javascript">

$('#change_src').click(function() {

$('.img_class').attr('src','somedir/some_image_name.jpg');

});

</script>

Example 3 – Change Image Source Attribute of all images belonging to a specific Class in jQuery

<script type="text/javascript">

$('#change_src').click(function() {

$('.img_class').each(function(){
$(this).attr('src','somedir/some_image_name.jpg');
});

});

</script>

Example 4 – Change Size / Style Attribute of all Images belonging to a specific Class in jQuery

<script type="text/javascript">

$('#change_src').click(function() {

$('.img_class').each(function(){

//Check if the style attribute is already defined. If yes, then get that value

if($(".img_class[style]").length)

{

var current_style = $(this).attr('style');

}

else

{

//Assign empty value

var current_style = '';

}

$(this).attr('style','width:150px;' + current_style);

});

});

</script>

In the above example, it’s mandatory to assign an empty value to the style attribute if it does not exist. If no style attribute is defined, assign empty value or the text “undefined” gets added to the style when button is clicked.

Easy, isn’t it?

Do you know of any other ways to change image src using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*