jQuery

jQuery Get Image SRC On Click Examples

While working with Web Design/Web Development & jQuery, it might be desirable to get image source using jQuery. Very often, the situation can demand us to get image source on click of a button or a div, etc. so that you can do other stuff, like store the path to that image in the database, etc. So in this article, I am going to share a very easy way to get image source using jQuery. Read on to find out more.

How to use jQuery to Get Image SRC (source) Value

For the sake of example, let’s assume that we have an image with class “.my_img”. We need to get source of image value on click. So let’s place a button. Now let’s see how to get the image source value using different available methods in jQuery.

Here is the HTML source code for the following examples:

<html>
<head>
<title>Examples to Get Image Source On Click using jQuery</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<img src="images/money.jpg" width="350" height="350" class="my_img">

<br>
<input type="submit" name="sbt_get_img_src" id="sbt_get_img_src" value="Get Image Source"><br>

</body>
</html>

Example 1: Get Image Source using attr() method when button is clicked using jQuery

<script type="text/javascript">

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

alert( $('.my_img').attr('src') );

});

</script>

Example 2: Get Image Source using prop() method when button is clicked using jQuery

<script type="text/javascript">

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

alert( $('.my_img').prop('src') );

});

</script>

From both the above examples, you can get the image source. But then, you must be wondering which one to use. Well, here are the cases:

1. Use attr() if you  using jQuery < 1.6

2. Use prop() if you are using jQuery > 1.6

3. If you want to get only the relative path of the image (i.e. without the http://www.mydomain.com) part, use attr(). So in the Example 1, if you look at the alert when attr() is used, you will see the alert: images/money.jpg

4. If you want to get the complete absolute path of the image (i.e. with the http://www.mydomain.com) part, use prop(). So in the Example 2,  if you look at the alert when prop() is used, you will see the alert: https://theextremewebdesigns.com/blog/images/money.jpg

That’s it for now!

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

Share your thoughts, comment below now!

*

*