Jquery как изменить src картинки

To change the source (src) of an image element, we need to use the jQuery attr() method.

You are here: Home / jQuery / Using jQuery to Change Image src

To change the image src using jQuery, the simplest way is to use the jQuery attr() method:

$("#img-1").attr("src","anotherImg.jpg");

Let’s say I have the following HTML code:

<div id="div1">
  <img id="img-1" src="img.jpg">
</div>

To change the image src of #img-1 from img.jpg to anotherImg.jpg, we will use the jQuery attr() method like in the following Javascript code:

$("#img-1").attr("src","anotherImg.jpg");

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#img-1").attr("src","anotherImg.jpg");

Changing Image Src Using jQuery with a Click

Many times when creating a web page and the user experience, we want to change an image after an interaction with another element on the web page.

To change the image src using jQuery, we can combine the attr() method with a click event.

Let’s say we have the same HTML from above.

<div id="div1">
  <img id="img-1" src="/wp-content/uploads/2021/11/tpe-main.jpg">
  <div id="click-me">Change image</div>
</div>

We have two images, tpe-main.png is a picture of gears in png form, and tpe-main.jpg is the same image, but in jpg form.

If we want to change the image from the .jpg version to the .png version when we click the #click-me div, we can add the following Javascript code to accomplish this:

$("#click-me").click(function(){
  $("#img-1").attr("src","/wp-content/uploads/2021/11/tpe-main.png");
}); 

The final code and output for this example of how to change the source of an image using the jQuery attr() method and Javascript is below:

Code Output:

Change image

Full Code:

<div id="div1">
  <img id="img-1" src="/wp-content/uploads/2021/11/tpe-main.jpg">
  <div id="click-me">Change image</div>
</div>

<script>

$("#click-me").click(function(){
  $("#img-1").attr("src","/wp-content/uploads/2021/11/tpe-main.png");
}); 

</script>

Hopefully this article has helped you understand how you can update the image source (src) using jQuery.

Other Articles You’ll Also Like:

  • 1.  Using jQuery to Hide a Div
  • 2.  Add Style to HTML Element Using jQuery
  • 3.  Using jQuery to Scroll to Div
  • 4.  jQuery on change
  • 5.  jQuery parent – Get the Parent Element of a Div
  • 6.  jQuery mousedown – An Interactive Example of the jQuery mousedown Method
  • 7.  Using jQuery to Move Element Before Another
  • 8.  jQuery Get Last Child
  • 9.  jQuery fadeIn – Fading In Element in HTML
  • 10.  Using jQuery to Show and Hide a Div

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

This is a tutorial on how to change the “src” attribute of an image using JavaScript.

The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.

In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.

Changing the src attribute using regular JavaScript.

If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.

Take a look at the example below:

<img id="myImage" src="https://thisinterestsme.com/LOGO.png">

<script>
    //Modify the src attribute of the image with the ID "myImage"
    document.getElementById("myImage").src = 'img/new-image.jpg';
</script>

If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.

A more verbose example for those of you who want to understand what is going on here:

//Get our img element by using document.getElementById
var img = document.getElementById("myImage");

//Set the src property of our element to the new image URL
img.src = 'img/new-image.jpg';

In this case, we have broken the process up into two steps:

  1. We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
  2. After retrieving the img, we were able to modify its src attribute and assign a new URL.

This will force the browser to load our new image.

Changing the img src using jQuery.

If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:

//Change the img property using jQuery's attr method
$("#myImage").attr("src", 'img/new-image.jpg');

In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.

Determining when the new image is loaded.

If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:

//Change the img property and use load() to figure out when
//the new image has been loaded
$("#myImage").attr("src", 'img/new-image.jpg').load(function(){
    alert('New image loaded!');
});

Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.

To get the image src and set the image src using jQuery attr(). In this tutorial, you will learn how to get and set the image src using jQuery.

The attr() method to get and change the image source in jQuery.

Get Image Src

Use the below script to get image src.

        $(document).ready(function() {

            $('.btn').click(function(){

                $imgsrc = $('img').attr('src');
                alert($imgsrc);

            });

         });

Set the Image Src

Use the below script to set the image src.

     $(document).ready(function() {

         $('.btn').click(function(){

            $("img").attr("src",'test.png');

         });

     });

Let’s take an example

The following example will change the second image to the first image.

<html>

   <head>

      <title> How to get and set image src attribute example</title>

      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   

      <script>

         $(document).ready(function() {

            $('.btn').click(function(){

                $imgsrc = $('#first').attr('src');
                $("#second").attr("src",$imgsrc);

            });

         });

      </script>
      <style>
        .card{
            margin: 30px;
        }
     </style>
   </head>

   <body>

    <div class="card">
        <img src="//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg" width="100" id="first" alt="Poker Card">
    </div>


    <div class="card">
        <img src="//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Download-Install-XAMPP-on-Windows.jpeg" width="100" id="second" alt="Poker Card">
    </div>

   <button type="type" class="btn">Get & Set image src</button>


   </body>

</html>

In the above example, we have got the first image src and set the src to the second image.

Conclusion

In this article, you have learned how to get the image tag src and set the image tag src using jQuery attr() with example.

Recommended jQuery Tutorials

  1. How to Get the Current Page URL in jQuery
  2. jQuery Ajax Get() Method Example
  3. get radio button checked value jquery by id, name, class
  4. jQuery Set & Get innerWidth & innerHeight Of Html Elements
  5. jQuery Get Data Text, Id, Attribute Value By Example
  6. Set data attribute value jquery
  7. select multiple class in jquery
  8. How to Remove Attribute Of Html Elements In jQuery
  9. How to Checked Unchecked Checkbox Using jQuery
  10. jQuery removeClass & addClass On Button Click By E.g.

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

View all posts by Admin

Probably, the best method to change the image sources is jQuery’s attr() function.

For example, let’s assume your <img> tag has an id attribute of ‘your-image’, so you can act like this:

<img id="your-image" src="image1.jpg"/>

Next, you can change the src of your image with jQuery like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src="https://ru.w3docs.com/uploads/media/default/0001/05/2c669e35c4c5867094de4bed65034d0cac696df5.png" alt="JS" />
    </div>
    <script>
      $(document).ready(function() {
          $("img").click(function() {
              // Change src attribute of image
              $("#your-image").attr("src", "https://www.w3docs.com/uploads/media/default/0001/05/9eb9e9cba721ba3bb5e653751449173197f2924a.png");
            });
        });
    </script>
  </body>
</html>

To attach the give code piece to a click event, you can do the following:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src="https://ru.w3docs.com/uploads/media/default/0001/05/2c669e35c4c5867094de4bed65034d0cac696df5.png" alt="JS" />
    </div>
    <script>
      $(document).ready(function() {
          $('#your-image').on({
              'click': function() {
                $('#your-image').attr('src', "https://www.w3docs.com/uploads/media/default/0001/05/9eb9e9cba721ba3bb5e653751449173197f2924a.png");
              }
            });
        });
    </script>
  </body>
</html>

To change the image, you can act as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src='https://ru.w3docs.com/uploads/media/book_gallery/0001/02/c8d75681dcd87da6f7d8ebfa0cdb40cbb403bed8.png' alt="Image" />
    </div>
    <script>
      $(document).ready(function() {
          $('img').on({
              'click': function() {
                let src = ($(this).attr('src') === 'https://ru.w3docs.com/uploads/media/book_gallery/0001/02/c8d75681dcd87da6f7d8ebfa0cdb40cbb403bed8.png') ?
                  'https://www.w3docs.com/uploads/media/book_gallery/0001/02/c4ba86c634f0f9c7ea055964c7f7436bab2bb698.png' :
                  'https://ru.w3docs.com/uploads/media/book_gallery/0001/02/c8d75681dcd87da6f7d8ebfa0cdb40cbb403bed8.png';
                $(this).attr('src', src);
              }
            });
        });
    </script>
  </body>
</html>

The .attr() method is used to get the attribute value for only the first element in the matched set. To get the value for each element separately, you can use a looping construct such as the .each() or .map() method.

Понравилась статья? Поделить с друзьями:
  • Jquery validation error class
  • Jquery validate error list
  • Jquery validate error element
  • Jquery validate error custom
  • Jquery validate error class