Using jQuery and CSS to create a temporary placeholder for images that have varying sizes

I am currently developing an innovative image gallery feature where a temporary heart image is displayed for 1 second in place of the actual images (image 1, image 2 etc).

If you want to view the implementation, check out my jsfiddle below:

https://jsfiddle.net/tgzqLmma/

For each image, I use the heart image as the src and store the actual image using data-src like this:

<div>
    <img class="delay" src="http://s12.postimg.org/4toxdafhl/heart.png" 
    data-src="http://placehold.it/260x280/E8117F/FFFFFF?text=image+1" alt=""     
    style="padding-top:120px; padding-bottom:120px"/>
</div>

To vertically center the heart image within the container, I utilize top and bottom padding values which will be dynamically calculated based on the image's height.

In my jQuery script, after 1 second, I remove the padding and switch the src with the data-src value for each image:

jQuery( document ).ready(function() {
    setTimeout(function () {
       jQuery('.delay').each(function () {
          var imagex = jQuery(this);
          var imgOriginal = imagex.data('src');
          jQuery(imagex).removeClass('delay');
          jQuery(imagex).css('padding',0);
          jQuery(imagex).attr('src', imgOriginal);
        });
     }, 1000);
});

To adjust the size of the main images and container, I make use of media queries and CSS styling.

However, I encounter an issue regarding maintaining the heart image at 40x40px while ensuring that the subsequent main images are displayed in their correct sizes. In the current state of my jsfiddle, you can observe that the first two images expand the heart image instead of being displayed correctly like the third image (which intentionally remains unchanged).

This problem arises from the way I have set the width and max-width properties in my CSS. Is there a way I can modify the code to achieve the desired layout effect?

Answer №1

To optimize your code, consider placing the placeholder in the background of the image instead of directly in the source. Take a look at this example fiddle for reference.

All you need to do is assign a .placeholder class to the image:

<img class="delay placeholder" src="" data-src="http://placehold.it/260x280/E8117F/FFFFFF?text=image+1" alt="" style="padding-top:120px; padding-bottom:120px"/>

Then add the CSS for the placeholder class:

div img.placeholder{
    background:url('http://s12.postimg.org/4toxdafhl/heart.png') center center no-repeat;
    display:block;
}

Finally, make some adjustments to the JavaScript code to remove the class when necessary:

jQuery( document ).ready(function() {
    setTimeout(function () {
       jQuery('.delay').each(function () {
          var imagex = jQuery(this);
          var imgOriginal = imagex.data('src');
            jQuery(imagex).css('padding',0);
            jQuery(imagex).attr('src', imgOriginal);
            jQuery(imagex).removeClass('placeholder'); /*added this*/
       });
    }, 1000);
});

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

Background image color not displaying correctly

I've been attempting to overlay a transparent color on top of a background image. While the background image is displaying correctly, I'm having trouble getting the color to show up. I noticed that this question has been asked before. I tried im ...

traverse a JSON object with JavaScript for a loop

After fetching and parsing data from a database using JavaScript, I have the following code snippet: var categories = <?php echo json_encode($categories); ?>; The 'categories' variable in the source code contains the values: var categori ...

Update the table with information from a designated URL every 5 seconds

So here's the situation: I've got a dynamic HTML table <table id="example"></table>. The data displayed in this table changes according to the URL. Normally, my default URL looks like this: index.php?action=add To handle this, I&a ...

A step-by-step guide for efficiently transmitting two JSON arrays via AJAX to be displayed in Django

I am currently implementing ajax to pass a JSON array to the view in Django. On my index page, I have two columns - left and right. Each column contains several text inputs, and there is a 'Save' button that saves all the values from both sides i ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

"Double the fun with fullcalendar.io - where every event is doubled

I am currently using a combination of rails and react.js for my latest project. Let's say I create event A, but then have a change of heart and decide to cancel it via a bootstrap modal. Afterward, I start another event B and proceed to confirm it, ho ...

Page title missing from browser tab

I don't come from a design background, so the issue I'm experiencing is quite peculiar. Below is a snippet of code from MVC4 - <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-C ...

Navigating data within a JSON file with D3 javascript: a step-by-step guide

Currently, I am attempting to extract and manipulate data from a JSON file using D3 Javascript. Below is the content of the JSON file: { "Resources": [ { "subject": "Node 1", "group" : "1" }, { "predicate": ...

Contact Form Validation in CakePHP 2.0 using Ajax

I'm currently working on my website . On the homepage, I have created an Enquiry Form. The form's standard validation is functioning properly, but I am looking to implement JQuery and Ajax validation. The form is set to submit to 'enquiry/ad ...

What are some ways to trigger a function once the modal has finished loading?

I'm looking to trigger a function on the Bootstrap modal after it has been opened. I came across the event show.bs.modal in the documentation. I attempted to connect to the modal using this code: $('#my-modal').on('show.bs.modal' ...

Generate a table inside a bootbox dialog using the data retrieved from an ajax call

I'm currently working on an app that requires attendance to be reported for specific events. I retrieve a list of JSON objects using AJAX. My goal is to create a table within a bootbox dialog that generates new rows for each item in the result from m ...

The jQuery menu is not working properly on Android's Chrome browser

When browsing http://creeight.se/stackExample1/, I noticed that the vertical dropdown menu functions properly in my desktop browsers (Chrome, FF, IE10), but experiences glitches when using Chrome for android. The menu utilizes .slideDown() to reveal submen ...

When attempting to pass Rgraph image data through a jQuery AJAX call, a 403 Forbidden error is being

I have been working on a project that involves creating graphs/charts using the Rgraph PHP library. To generate these charts, my script follows these steps: Calculate the graph points and render the graph using the Rgraph Draw() method. Create an image d ...

The design of the button appears unappealing when viewed in

Hi there! I am currently working on creating a button for Outlook 2010, but I am running into an issue. The button image is not aligning vertically in the center, and the padding and margin are not displaying properly. It works perfectly fine on most ema ...

The bootstrap carousel seems to be malfunctioning and instead displaying as background images

As someone who is new to coding, I have been attempting to create a slider on Bootstrap, but it seems to be displaying more like a background than an actual slider. Here is an excerpt of my HTML code: <body> <div class="navbar navbar-default ...

Drupal jQuery carousel featuring a pager

Seeking a high-quality jQuery carousel specifically for Drupal. Mandatory features: Pager functionality for easy slide selection Compatibility with Drupal 6 and jQuery Hover effect to display additional content Integration of Drupal variables in conten ...

Having trouble with your jQuery animation on a div?

Check out this jsFiddle example: http://jsfiddle.net/uM68j/ After clicking on one of the links in the demo, the bar is supposed to smoothly slide to the top. However, instead of animating, it immediately jumps to the top. How can I modify the code to ac ...

Steps for resetting the HTML5 meter element

I have implemented the meter element to rate between 0 and 5, but I want to display a specific image for each value instead of the default meter style: <meter min="0" max="5" value="5"> <img width="80" height="20" alt="5 out of 5 stars" src=" ...

Verify whether a class or id is present in the HTML response obtained from an AJAX request

Is there a way to check the content of HTML returned by an AJAX call before rendering it to avoid any flickering effect? I am aware of using hasClass() to check for classes, but in this scenario, the AJAX response is returning HTML. I can append the HTML ...