2
<div class="A">
   <a href="abc"><img class="A" alt=" " src="/1.jpg"></a>
</div>

I need a javascript to detect if image broken,make div height to 0px,basically to hide it. Or are there any css to do it?

<script> $('.A').find('img').length == 0){
       $(this).hide();

    }</script>
3
  • by broken image do you mean that the image is not found? Commented Dec 13, 2013 at 12:42
  • yes thats what i meant Commented Dec 13, 2013 at 12:47
  • from what i understand you cannot poll the server using JS and check if the image is present or not , for that we have server side languages like php. Commented Dec 13, 2013 at 12:48

2 Answers 2

4

The exact code you are searching for is something like this:

<div class="A">
    <a href="abc"><img src="/1.jpg" onerror="this.parentNode.style.display='none'" class="A" alt=" " /></a>
</div>

The error event in the img tag makes its parent node div to be hidden. This should work.

Sign up to request clarification or add additional context in comments.

Comments

3

To check if an image has completely loaded, you can check if it is complete like this:

$.ready(function(){
    //I'm guessing that's how find() works, correct me if I'm wrong
    if($('.A').find("img")[0].complete){

            console.log("successfully loaded!")
      }else{
           $('.A').find("div")[0].hide();
      }
}

A pure JS Solution is:

document.onload=function(){
    if(document.getElementById("image").complete){
        console.log("complete")
    }else{
        document.getElementById("imgwrap").style.display="none";
    }
}

8 Comments

Doesn't that need to be inside a document.ready()? Otherwise it might run the javascript before the image has finished loading - OP wants to check whether it is broken, not whether it is incomplete.
hi, do you mind to give example based on the given html? i couldn't figure out what to replace in the code above,thanks
@AnnaBoyle that should do it, but I'm not too familiar with jQuery, so correct me if that's not how to correctly find the element.
@scrblnrd3 im not using jquery, i need javascript :)
@AnnaBoyle What? You have jQuery in your question!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.