Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account.

Here is the current output: http://jsfiddle.net/LvsYc/2973/

Check out the default image here:

This is the script being used:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Answer №1

Check out this fiddle that demonstrates the concepts discussed in the comments:

HTML

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <div class="img">
        <img id="blah" src="#" alt="your image" />
    </div>
</form>

CSS

img {
    width: 120px;
    height: 120px;
}
img[src="#"] {
    display: none;
}
.img {
    background: url('http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg');
    background-position: -20px -10px;
    width: 120px;
    height: 120px;
    display: inline-block;
}

The javascript code remains unchanged.

Answer №2

I came up with a simple script to address this issue:

Check out the JSFiddle link for more details: http://jsfiddle.net/LvsYc/3102/

$(function () {
    var loader = 'http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg';
    $('img[data-src]:not([src])').each(function () {
        var $img = $(this).attr('src', loader),
            src  = $img.data('src'),
            $clone = $img.clone().attr('src', src);
        $clone.on('load', function () {
            $img.attr('src', src);
        });
    });
});

Here's how it works:

  1. When the page loads, it checks all image tags with a data-src attribute but no src set.
  2. A clone of the image tag is created with the src set to the value of data-src.
  3. Once the cloned image has finished loading, the original image tag's src is updated to match the data-src.

There are many approaches to solving this problem, and while this may not be the most efficient method, it should get the job done.

Answer №3

To handle the onError event for an image and reassign its source using Javascript, you can use the following methods:

function handleImageError(img) {
    img.onerror = "";
    img.src = "/images/noimage.gif";
    return true;
}

<img src="image.png" onerror="handleImageError(this);"/>

Alternatively, you can achieve the same result without a JavaScript function like this:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

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

Customizing div elements in various RMarkdown documents with a CSS file

I want to apply styling to divs in various RMarkdown files using a CSS file. However, I am encountering syntax issues when trying to use the external CSS file to style the div. Embedding the style tag within the rmarkdown body works as shown below: --- ti ...

What is the best way to simultaneously create a customer and add a card with Stripe?

When attempting to initialize a customer for the first time, I encounter an issue where using a Stripe token more than once raises an error. The process involves a form submission on the client side and handling the token creation on the server side: var ...

Fixing the Timeout Error in Node.js & Mongoose: A Step-by-Step Guide

After developing an API, I encountered the following issue: const express = require("express"); const router = express.Router(); const {getAttendanceSheet,getDailyAttendance} = require("../../services/attendanceService"); router.get(& ...

Is there a way for me to figure out if a Primefaces RadioCheckbox has been selected?

Despite the numerous examples available on how to count checked checkboxes, I am facing difficulties in getting it to work. My goal is to enable a button when at least one checkbox is checked on the page, and disable it when none are selected. However, n ...

Trouble with displaying autocomplete options for ajax requests

I recently implemented the autocomplete feature using bootstrap typeahead in my project. The original code snippet worked flawlessly: $(function () { var $input = $(".typeahead"); $input.typeahead({ source: [ {id: "someId1", name: "Display nam ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Could someone please clarify a specific aspect of how floats work?

Could someone simplify this explanation for me? A float is positioned next to a line box if there is a vertical space that meets these conditions: (a) at or below the top of the line box, (b) at or above the bottom of the line box, (c) below the top margi ...

Troubleshooting: npx create-react-app displaying errors during installation

Encountering an error while trying to install create-react-app using npx. Seeking assistance on resolving this issue. My Node.js version is v16.14.2 and npm version is 8.5.0 Installing packages. This may take a few minutes. Installing react, react-dom, a ...

JavaScript's data.map function cannot be found

I've been developing a full stack application using Vue.Js, NodeJS, ExpressJS, and MongoDB. In my frontend code, I have a PostService.js class that manages HTTP requests to the API. However, I encountered an issue while trying to map the response data ...

Triggering a jQuery event upon clicking a link

Trying to achieve a specific functionality here. Clicking on an image triggers a lightbox, but right-clicking and opening in a new tab should lead to a different page. Instagram has a similar feature that I'm aiming for. Using <a href=""> doesn& ...

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

Customizing the CSS shadow for a specific ionic select text color, while ensuring that other ion select instances remain unaffected

I'm encountering an issue while attempting to customize the text color inside an ion select element based on the option selected. Unfortunately, when I make changes to the shadow part in one component, it affects other components as well. I want to ap ...

Determination of Vertical Position in a Displayed Table

I am trying to incorporate infinite scrolling with an AJAX-based loader in the body of an HTML table. Here is a snippet of my HTML code: <table> <thead> <tr><th>Column</th></tr> </thead> <tbody> ...

Is Ajax still a popular choice for developing web applications?

Currently, I am developing a comprehensive ajax-based web application and have been investigating various frameworks for SEO optimization and history tracking. During my research, I came across an interesting framework at Although it seems promising, I no ...

Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module. Below is the code for my module which you can review and provide feedback on. var employee = { all: function (req, res) { jwt.verify(req.token, 'novatureso ...

Setting up route handlers in Node.js on a pre-initialized HTTP server

Is there a way to add route handlers to an http server that is already instantiated? Most routers, including express, typically need to be passed into the http.createServer() method. For instance, with express: var server = http.createServer(app); My r ...

Whenever I repeatedly click the button, the array will store a new value. My goal is for it to collect and store all values obtained from the function

After retrieving data from the listAPI value using an API, the output is displayed as follows: //output - console.log(listAPI) 5) [{…}, {…}, {…}, {…}, {…}] 0: {id: "1", name: "name 1", active: "true"} 1: {id: " ...

How to assign a click event to dynamically generated HTML elements using jQuery

My goal is to attach an onclick event to a dynamically inserted element using jQuery However, I am facing an issue where the function does not execute. I would appreciate it if someone could help me determine why this example is not functioning correctly ...

Vue.js encounters a null value for "$slots.default()[0].el" when dynamically passing a slot using v-for

Is there a way to access the HTMLElement of a dynamically passed slot when using v-for? I'm having trouble as the element (el) always seems to be empty. app.vue : <template> <div id="app"> <prod> <span> ...

What is the best way to automatically show scrollbars when a page loads using JavaScript?

How can I make the vertical scrollbar appear as soon as the page loads using javascript? I am currently using a jquery slide toggle animation that causes the vertical scrollbar to show up because it makes the page longer. However, when the scrollbar appear ...