2

I understand how to hide images if they're as followed,

<img src=""......>

However, I'm having problems as I know nothing about JS on how to hide broken images if they're like this,

<div class="lx-g3-f" >
  <div class="lx-gallery" data-bg="image_url" alt="alt text" referrerpolicy="no-referrer" title="something title">
  <div class="lx-gallery-title" >
    <h3><a href='something_img_url' referrerpolicy="no-referrer">click here!</a></h3>
  </div>
</div>              

How can I make the following work when img doesn't exist.

$("img").on("error", function() {
    $(this).closest('.lx-g3-f').hide();
});

1 Answer 1

3

Not trivial

Try

$(function() {
  $("[data-bg]").each(function() {
    const $parent = $(this).closest(".lx-g3-f")
    const img = new Image();
    img.onerror=function() {
      $parent.hide();
    }
    img.src=$(this).data("bg")
  })
})
Sign up to request clarification or add additional context in comments.

2 Comments

$(function() { $("[data-bg]").each(function() { const $parent = $(this).closest(".lx-gallery") const img = new Image(); img.onerror=function() { $parent.hide(); } img.src=$(this).data("bg") }) }) worked amazingly well thank you.
You can just to const $this = $(this); and then $this.hide() if you want to hide the div with the background

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.