Skip to content
Advertisement

Image on load function in jQuery

I have pictures on the site I want to do (If the image has been downloaded, delete p) But I was surprised that ‘load’ has been removed from the new jQuery version

<div>
    <img src="Imgur.jpg" alt="Tutor" width="304" height="236">
    <p>1</p>
</div>
    <div>
    <img src="Imgur.jpg" alt="Tutor" width="304" height="236">
    <p>1</p>
</div>
    <div>
    <img src="Imgur.jpg" alt="Tutor" width="304" height="236">
    <p>1</p>
</div>
    <div>
    <img src="Imgur.jpg" alt="Tutor" width="304" height="236">
    <p>1</p>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>

            $("img").on("load", function () {
                $(this).parent().find("p").remove()
            })
        
</script>

Advertisement

Answer

Your code works. I used JQuery Version 3.6.0

 $("img").on("load", function() {
   $(this).parent().find("p").remove()
 })
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div>
  <img src="https://via.placeholder.com/150" alt="Tutor" >
  <p>1</p>
</div>
<div>
  <img src="https://via.placeholder.com/150" alt="Tutor" >
  <p>1</p>
</div>
<div>
  <img src="https://via.placeholder.com/150" alt="Tutor">
  <p>1</p>
</div>
<div>
  <img src="https://via.placeholder.com/150" alt="Tutor">
  <p>1</p>
</div>

If you want just a special p to remove give the image an id

<img id="picture1" src="https://via.placeholder.com/150" alt="Tutor">
 $("#picture1").on("load", function() {
   $(this).parent().find("p").remove()
 })

That’s it.

So include like this:

script.js

$(document).ready(function() {
    console.log("ready!"); //You see this in Console if it works!
    $("img").on("load", function() {
       $(this).parent().find("p").remove()
    })
});

Then your html file:

<html>
   <head>
   ....
   </head>
   <body>
   <div>
      <img src="https://via.placeholder.com/150" alt="Tutor" >
      <p>1</p>
   </div>
   <div>
      <img src="https://via.placeholder.com/150" alt="Tutor" >
      <p>1</p>
   </div>
   <div>
      <img src="https://via.placeholder.com/150" alt="Tutor">
      <p>1</p>
   </div>
   <div>
      <img src="https://via.placeholder.com/150" alt="Tutor">
      <p>1</p>
   </div>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="yourfolder/script.js"></script>
   </body>
</html>
Advertisement