5

I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

<?php


   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

       <table class='mobileTable'>
          <tr> <td><img src='<?php echo $img ?>' onerror='imgError(this)' /></td></tr>
          <tr> <td  class='mobMidTitle'><?php echo $title ?></td></tr>//i want to remove this title as well
       </table>
   <?php } ?>

 <script>
 function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('tit').style.display='none';
    return true;
}</script>

code above will fetch 5 images from database and with javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

Yugraaj Sandhu
  • 392
  • 3
  • 14
  • 1
    Possible duplicate of [Check if an image is loaded (no errors) in JavaScript](http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript) – AG_ Apr 02 '17 at 07:46
  • you can add a certain id to your rows. In case your image is broken in a row you can manage to hide the entire row or do whatever you want to do with it. – f_i Apr 02 '17 at 07:49

4 Answers4

4

You can accomplish this in one of two ways:

Either use the removeChild function (assuming you want to remove the elements and not hide them):

function imgError(image) {
   // Get image row
   var imageRow = image.parentNode.parentNode;
   // Get image label row
   var imageLabel = imageRow.nextElementSibling;
   // Get table element of that image row and remove imageLabel
   imageRow.parentNode.removeChild(imageLabel);
   // Get table element of that image row and remove img element
   imageRow.parentNode.removeChild(imageRow);
}

Or you can instead hide your elements using the .style.visibility property of the image and label elements:

 function imgError(image) {
    // Get image row
    var imageRow = image.parentNode.parentNode;
    // Get image label row
    var imageLabel = imageRow.nextElementSibling;
    // Hide imageLabel
    imageRow.style.visibility = 'hidden';
    // Hide imageRow
    imageLabel.style.visibility = 'hidden';
}
guychouk
  • 671
  • 1
  • 8
  • 28
  • this won't remove the title td – hassan Apr 02 '17 at 08:01
  • @hassan I've updated my answer to include that as well. Further testing is required, I just implemented a solution based on OPs situation and have not yet tested it yet, feedback will be appreciated. – guychouk Apr 02 '17 at 08:06
  • 1
    this doesn't worked too, this is because of `nextSibling` is sensitive to white-spaces , use `nextElementSibling` instead, also the OP does not want to remove the Image itself , so you don't need to remove the image element; – hassan Apr 02 '17 at 08:09
  • @hassan Noticed it 2 seconds after you did :) I've updated my answer accordingly, thank you. – guychouk Apr 02 '17 at 08:09
  • @hassan also, OPs question description implies otherwise since OP wrote **remove**, I'll try and update my answer to include a **hide** solution as well. – guychouk Apr 02 '17 at 08:12
3

How about this JQuery javascipt (https://jquery.com) to hide any image that failed to load:

$("img").error(function() { $(this).hide(); });

or, if you want to hide its container you can do this:

$("img").error(function() { $(this).parent().hide(); });

or if you really want to remove the image, or container, use remove() instead of hide().

You could also display your own error image:

$("img").error(function() { $(this).attr("src","error.png"); });

Code has been tested and it works.

You can make it more specific by selecting only those images you want to hide or remove. Change $("img") to $(".hideOnError") and the use the class hideOnError on those images you want to hide or remove. Different actions could be take like replaceOnError. You can also apply this to other loadable elements.

In your specific case you have two elements you want to remove when an image fails. The best way to go about this is to associate the title with the image through attributes:

   <table class='mobileTable'>
      <tr><td><img id='image1' src='<?php echo $img ?>'></td></tr>
      <tr><td id='image1title' class='mobMidTitle'><?php echo $title ?></td></tr>
   </table>

As you can see, the id of the image here is image1 and the table cell containing the title has id image1title. To remove image and title on error, while leaving the table structure intact, you do:

$("img").error(function() { 
  var id = $(this).attr('id');     // get id of image
  $(this).remove();                // remove image
  $("#"+id+"title").empty();       // remove title
});
KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • why he needs to use such a big library like jquery to execute single task such as removing images ? – hassan Apr 02 '17 at 08:11
  • 1
    You definitely shouldn't. But if you're using JQuery you could. See, I don't force anyone to do it this way. Freedom for all! – KIKO Software Apr 02 '17 at 08:14
3

well, there are multiple approaches to do this :

here, I'm assuming that you want to use Pure javescript -no jquery- and keeping the original DOM document hierarchy.

<table class='mobileTable'>
    <tr> <td><img src='path/to/broken/image.jpg' onerror='imgError(this)' /></td></tr>
    <tr> <td  class='mobMidTitle'>some title</td></tr>
</table>

<script>
function imgError(image) {
    // this will step up to get the parent of the image's parent
    var imgParent = image.parentElement.parentElement;
    // this will get the next sibling of the image grandpa
    var nextSib = imgParent.nextElementSibling;
    // reset it's html to empty
    nextSib.innerHTML = '';
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    return true;
}
</script>

another easier approach is by adding new ID to your title TD and then remove it using javascript as follows :

/* here we've added id='mobMidTitle' */
<td  class='mobMidTitle' id='mobMidTitle' >some title</td>

<script>
function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('mobMidTitle').style.display = 'none';
    //                       ^^^^^^^^^^^
    return true;
}
</script>
hassan
  • 7,812
  • 2
  • 25
  • 36
  • worked as well ,thank you .bus as i was bringing data from mysql through while loop so it was removing last inserted td. – Yugraaj Sandhu Apr 02 '17 at 09:07
  • because you are using ID instead of classes , i think that the first solution would works fine with loops – hassan Apr 02 '17 at 09:11
1

You can replace image if img tag has broken image. Please check below code

<img src='brokenimage.jpg' onError="ImageError(this);">

<script language="JavaScript">
  function ImageError(img)
  {
    img.src = "https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
  }

</script>