Is it possible to conceal the "Image not found" error icon without the need for "this.style.display = 'none'"?

Creating multiple image boxes within a span element without a predetermined src is the task I have set for myself in JavaScript, specifically for a basic game of blackjack. Below is the current HTML code for the span of image boxes:

Note: This site is not being hosted; it is running in my browser with no JQuery.

<span> <!-- Players Cards -->
    <img class='imagebox' id='imagebox1' src=''></img>
    <img class='imagebox' id='imagebox2' src=''></img>
    <img class='imagebox' id='imagebox3' src=''></img>
    <img class='imagebox' id='imagebox4' src=''></img>
</span>

When a card is selected in the JavaScript file, interpolation is used to display an image by changing the image's src:

function deal(box) {
  let card = randomcard();
  const image = document.getElementById(`imagebox${box}`);
  if (image.src !== card) {
    image.src = `cardpng/${card}`;
  } else {
    redeal();
  }
}

The issue is that until a src is assigned to each image box, it will display an "image not found" icon, which I find aesthetically unpleasing. I attempted to remove this icon using the following code:

<img class='imagebox' id='imagebox1' onerror='this.style.display = "none"' src=''></img>

However, even after a src is defined and there should be no error, the style remains as "none." I am looking for a more elegant solution that requires minimal interaction between HTML and JS.

Thank you in advance for any suggestions.

Answer №1

Apply CSS

img[src=""] {
  display: none;
}

Here's an example -

setTimeout(() => document.getElementById('imagebox1').src = "image.jpg", 2000)
img[src=""] {
  display: none;
}
<span> <!-- Players Cards -->
    <img class='imagebox' id='imagebox1' src=''/>
    <img class='imagebox' id='imagebox2' src=''/>
    <img class='imagebox' id='imagebox3' src=''/>
    <img class='imagebox' id='imagebox4' src=''/>
</span>

However, do you actually see an image not found icon? Because I don't see any here

<span> <!-- Players Cards -->
    <img class='imagebox' id='imagebox1' src=''/>
    <img class='imagebox' id='imagebox2' src=''/>
    <img class='imagebox' id='imagebox3' src=''/>
    <img class='imagebox' id='imagebox4' src=''/>
</span>

note: img does not have a closing tag - it's either <img ...../> or <img .....> with no </img>

Answer №2

An effective solution for handling broken images, not just those without a set src, is to assign an empty string to the alt attribute:

<section>
  <p>Using <code>alt=""</code></p>
  <img alt="">
  <img alt="" src="">
  <img alt="" src="https://example.com/broken-image.jpg">
  <img alt="" src="https://www.fillmurray.com/50/50">
</section>
<section>
  <p>Not Using</p>
  <img>
  <img src="">
  <img src="https://example.com/broken-image.jpg">
  <img src="https://www.fillmurray.com/50/50">
</section>

It's important to note that with this approach, the images are converted into empty text nodes for the renderer. While they don't take up space, neighboring white spaces may be rendered. In the example provided, the new lines between each <img> tag appear as a single-space text node in the final page rendering, similar to how they would appear if the images were displayed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining information from a jQuery ajax post using ExpressJS

Hey there, I've got a jQuery POST request set up to send some data: $.ajax({ type: "POST", url: app.config.backend_2 + '/notifications/usernames', data: data, contentType: 'application/javascript', dataType: &a ...

How can we stop KeyboardAvoidingView in React Native from overlapping content?

I'm working on implementing a KeyboardAvoidingView section for a signup form. I've managed to adjust the keyboard properly on both iOS and Android, but instead of increasing the view's height and scrolling up, the KeyboardAvoidingView is red ...

Is it possible to easily extract all values associated with a particular key in a nested JSON using JavaScript?

I have a JSON structure that looks like this: [ { cells: [ { id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} }, { id: "2", cellType: 4, widget: { id: 2, description: "myDesc2"} } ] }, { cells: [ { id: "3", c ...

Troubleshooting overload errors within ReactJS: tips and tricks

import React from 'react' import { Link } from 'react-scroll' import "./Protocol.css" import { ANALYTICS, TRADE, USERS, TRADERS, VOTES, ZEROES } from "../../Constants" const Protocol = () => { return ( ...

What steps should be taken to ensure that Google effectively crawls through an AngularJS application?

According to a source at Allotment Digital, it is unnecessary to provide different or pre-rendered content to Google when using html5mode and removing hashtags from URLs. While some websites state that ajax crawling documents are deprecated, others such a ...

Fetching an image stored in a database and showing it, along with instructions on how to create a pop-up window for enhanced image visibility

I need to fetch an image from a MYSql Database and display it on a web page. Once the images are displayed, I want them to appear in a clear pop-up when I hover my mouse over them. Here is the code for retrieving the images: <table align=center class=" ...

Store the outcome in a JSON file while utilizing a post request with AJAX and Node.js

In my current project, I am developing a JavaScript code to track the system configuration of users, such as screen resolution statistics. Initially, I created an AJAX file to collect the data in object form and utilized node.js to handle the request and s ...

Having trouble adjusting the space between the footer and the bottom of the page

Looking to create a footer using multiple elements The first element should be positioned at: left: 944px; top: 9749px; The second element should be positioned at: left: 715px; top: 9819px; The third element should be positioned at: left: 718px; top: ...

Server headers in Node.js

As a newcomer to web development, I am currently delving into the world of node.js to create an app that involves retrieving data via REST and implementing search and sort functionalities. However, I've hit a roadblock when it comes to understanding h ...

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Having trouble retrieving JSON array in PHP

I'm facing a challenge accessing data from PHP that's coming from JSON in JavaScript. I utilize local storage to store some temporary information: var tbRomaneio = localStorage.getItem("tbRomaneio");// Retrieves stored data tbRomaneio = JSON.pa ...

Is it possible to modify the ID of an SVG path element by hovering over a different element?

I gave unique IDs to SVG path elements - opacity-1n and opacity-1e. My aim is to make opacity-1e visible when hovering over opacity-1n. <g id="Layer_1"> <path id="opacity-1n" d="M135.4 6.8v38.3h-1.9l-15.1-13.8-1.8-1.6-6.8- ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Tips for creating a high-quality file upload button in Laravel 5 using Bootstrap 4

I need a file upload input similar to the one showcased in this example <input type="file" id="dp_file_input" name="demo" /> The current file input design is not visually appealing, so I am looking for a solution like the one demonstrated in the ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Handle changes to input values on ng-click even if they were made outside of Angular's control

Looking to pass input values on ng-click even when they are changed outside of Angular. Everything works fine when manually typing, but once the inputs have dynamic values, ng-click passes empty form data. Below is the HTML code snippet: <form id="form ...

What is the best way to display a background image at the top of a webpage and ensure it fills the entire visible area of the screen?

I'm a beginner in the world of development, and I've been given a challenging task to tackle. The assignment is to create a one-page website with navigation links for 'About Us' and 'Contact Us'. Upon clicking these links, th ...

Guidelines for centering 2 images with JavaScript

I am faced with a unique challenge involving 2 images, where one image has a designated Mask area and the other image is supposed to be visible through the Masked area of the first image. My goal is to align the second image in the center of the Mask area ...

Updating preg_replace as it is now deprecated and trying to resolve the issue

After upgrading to PHP 7, I successfully resolved deprecated function errors. However, I'm struggling with updating the preg replace method in my "view php array in an interactive collapsible javascript element" code. The specific code snippet causin ...

Creating a View-Model for a header bar: A step-by-step guide

I am looking to develop a View-Model for the header bar using WebStorm, TypeScript, and Aurelia. In my directory, I have a file named header-bar.html with the following code: <template bindable="router"> <require from="_controls/clock"></ ...