Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a time, with the small image initially loading and then being replaced by the large image once it has fully loaded in the background. I have code that switches the large image from the data-src attribute to the src attribute.

$(document).ready(function(){
    $("#image4").load(function(){
        var imgDefer = document.getElementsByTagName('img');
        for (var i=0; i<imgDefer.length; i++) {
            if(imgDefer[i].getAttribute('data-src')) {
                imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
            }
        }
    });
}); 

This approach allows me to show the small image first without having to wait for the large image to load completely. However, I am currently experiencing an issue where both small and large images are loading concurrently when the page loads. It's important to note that these images feature drag and zoom functionality. You can view the live version of this code here:

Answer №1

Your current code snippet is not being used on your server - it seems like another script is handling the mousewheel event.

To resolve this issue, consider preloading the large image in the background and then switching to display it once fully loaded:

// Loop through all images
$('img').each(function(i, img) {
 var img = $(img);
 // Check if they have a data-src attribute
 if(img.attr('data-src')) {
   // Listen for load event on initial image
   img.one('load', function() {
     // Once small image is loaded, start loading large image
     // Create hidden image element
     var hiddenImg = new Image();
     hiddenImg.onload = function() {
          // Set src attribute of real image once hidden image is loaded
          img.attr('src', img.attr('data-src'));
      };
      // Begin loading the resource
      hiddenImg.src = img.attr('data-src');
     });
   });
});

(Credits: Load image from url and draw to HTML5 Canvas)

Answer №2

One strategy is to initially load content into a hidden element, and then dynamically change it once the loading process is complete.

Answer №3

One possible approach is to initiate the loading process after the image has been fully loaded.

$('img').load(function(){
    var bigImgSrc = $(this).data('src');
    var img = $(this);

    if(bigImgSrc !== img.prop('src')){
      var bigImg =$('<img>').prop('src', bigImgSrc);
      bigImg.load(function(){
        img.prop('src', bigImgSrc);
      });
    }
});

It's uncertain whether you need to attach the bigImg to the DOM in order for it to load properly. If necessary, you can use bigImg.hide().appendTo('body') and then remove it once it has finished loading.

Keep in mind that the load function may not work under all circumstances; refer to https://api.jquery.com/load-event/ for more information.

Edit: The previous code example contained an infinite loop.

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

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

What causes the fixed div to appear when scrolling horizontally?

I have replicated this issue in a live example: http://jsfiddle.net/pda2yc6s When scrolling vertically, a specific div element sticks to the top. However, if the window is narrower than the wrapper's width and you scroll horizontally, the sticky elem ...

Experiencing blank areas when I try to minimize the screen while using Chrome

While using Chrome, my webpage looks perfect in normal mode. However, when I minimize the screen, white space appears at the bottom and some content gets hidden. The page is built using reactjs, html, and css. Interestingly, it works fine for IE in both no ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

What is the best way to retrieve a particular value from a database using PHP?

$sql="Select chanceNo From gm_gacha_token1 where token_code='$mytoken'"; $result=mysql_query($sql); $count=mysql_num_rows($result); Language: PHP I am attempting to retrieve a single value of `chanceNo. Is there a way to get this value and stor ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

Unveil the modules of a Node.js NPM application

I have a Node application that is used as an npm module and serves as a dependency in the package.json file of another Node application. This application needs to grant access to internal modules to the app utilizing my package as a dependency. All these m ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

How can I find the hexadecimal color value from this jQuery plugin?

Hey everyone, I've been using this awesome jQuery plugin for a color picker. However, I'm curious about where the hex value of the chosen color is stored when the user selects it. I need to process it and save it to the database. Thanks! If you& ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...

Exploring the distinctions among different xpath implementations in Selenium WebDriver

Looking at this snippet of HTML code: <div id="divTooltips_Section_Filter" style="float:right; padding-right: 30px; padding-bottom: 10px;"> <img src="/mkteditor/css/images/tooltip.png" width="25px" height="25px" alt=""> </div> I've ...

Angular.js: Ensure all services are loaded before initializing the application

I am currently developing an application using angular.js and I need to ensure that the result from a specific service is accessible throughout the entire application right from the beginning. How can this be accomplished? The service in question is as f ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

How can I create a custom AppBar transition using Material-UI?

Is there a way to incorporate transitions into the AppBar element within Material-UI? I have tried adjusting the class properties, but unfortunately, I'm not seeing any animation. Can anyone pinpoint what the issue might be? To see the code in action ...

"Switching from vertical to horizontal time line in @devexpress/dx-react-scheduler-material-ui: A step-by-step guide

Is there a way to switch the Time to a horizontal line using @devexpress/dx-react-scheduler-material-ui? <WeekView startDayHour={7} endDayHour={20} timeTableCellComponent={TimeTableCell} dayScaleCellComponent={DayScaleCell} /> Click ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...