If the source of the image is labeled as '(unknown)', then swap it with 'missing.png'

When an image is not provided in my CMS database, it currently produces an img src="(unknown)". I am looking for a way to use JavaScript to change this to img src="/images/missing.png". As someone who is new to JS, I have attempted various hacks but none have been successful. Any suggestions? (There may be multiple images on the page, if that matters)

Answer №1

If you encounter a missing image src, you can make it work by utilizing the onError event for handling it.

<img src="main_img.png" onError="this.onerror=null;this.src='/images/missing.png';" />

Answer №2

This code snippet helped me tackle a comparable issue I faced (using JavaScript)...

const pics = document.querySelectorAll("img");

pics.forEach((pic) => {
  let picSrc = pic.getAttribute("src");
  if (picSrc === "") {
    pic.src = "/images/not-found.png";
  }
});

Answer №3

When working with PHP, you may encounter this issue, but don't worry, simply utilize the esc_url($url) function.

The esc_url function effectively resolves the problem.

Answer №4

When the page is loading, if you are dynamically adding the src attribute, it's a good idea to have a check in place to switch it with a placeholder if necessary.

if (imgSrc === "unknown") {
    imgSrc = "placeholder.png";
}

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

Utilizing lodash chain to filter and retrieve the parent object

I am trying to utilize the Lodash chain function to filter through nested array items within an array and then return the full parent object. Let me share some dummy data that outlines the scenario I am facing: const capital = [ { "financeCategory" ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Disabling the browser's back button initially allows users to go back, but then forces them to browse forward instead

I need to prevent the user from being able to navigate back to the previous page in their browser. To achieve this, I have included the following code snippet in the layout pages of my ASP.NET MVC application (in addition to setting appropriate response h ...

Trouble with the find() function in jQuery not functioning properly upon page initialization

In my jQuery script, I am attempting to remove the style attribute from all table, tr, and td elements that are within a div element with an id="testdiv". $(document).ready(function(){ $("#testdiv").find("table, tr, td").removeAttr("style"); }); When ...

Express Router triggers XHR onreadystatechange 3

Having just started using Express, I am currently working on setting up a login authentication system. However, I have encountered an issue where XHR is not showing a ready state 4. This problem arose after implementing express.Router which I came across i ...

Switch from using jQuery to vanilla JavaScript for handling POST requests

I am looking to eliminate the jQuery dependency and use plain JavaScript instead in the code below for a post request. <script type="text/javascript> $(function() { $.post("test_post.php", { name: "John Doe", ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...

Exploring the depths of angular views with the powerful ui.router

Can someone guide me on how to implement login in the index and info in login using ui.router in Angular? I want to display different views based on the URL being used. For instance, when logging in and accessing the driver view, I want the HTML to be inj ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

What is the method for obtaining the entire object as a response following a click?

I am working on a basic JavaScript snippet: var image = [{name: "Breakfast", age: 100, author: "Alice"},{name: "Dinner", age: 10, author: "Teddy"}]; function gallery(name, content) { this.name = name; this.c ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

Understanding the Typescript definitions for different event types in React

How do I properly define the type for React events? In the beginning, I simply used any to keep things simple. However, I am now trying to improve my code and eliminate the use of any altogether. Here is a basic example: export interface LoginProps { l ...

Discovering an HTML Element in a JavaScript Array with Specific Styling: A Step-by-Step Guide

I am in the process of developing a website that consists of different sections. The concept is simple - by clicking on a button located at the bottom of the page, it will reveal the corresponding div section. For styling purposes, I have initially hidden ...

"Discover the method of extracting data from a hidden field within a td element using jQuery

I'm currently working with a dynamic table and facing an issue retrieving the value of a hidden field called order_id. The problem is that I am only able to get the value of the first id even when clicking on buttons in other rows. Here is the code sn ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

Creating a custom filter with ngx-pagination

Having trouble with filtering in Angular 7 + Electron 4 while using ngx-pagination. I followed the steps mentioned in the documentation, but encountered an error Uncaught Error: Template parse errors: The pipe 'stringFilter' could not be found ...

Converting a String to an Integer in JavaScript

I'm having trouble printing the sum in this code // 1. create variables // 2. input numbers into variables [but they are strings] // 3. unable to print the sum // Variables let num = [""]; let num22 = [""]; // Add new number to num ...