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

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...

Enhanced Navbar Dropdown Menu with Multiple Columns in Bootstrap 4 Beta 2

My attempt at building a navbar using Bootstrap 4.0.0-Beta 2 with right-aligned elements is not turning out as expected, especially when viewed on a full page. The dropdown element is not displaying correctly and seems off. I have included the code below ( ...

Event listener for clicking on a custom overlay in Google Maps

Incorporating Google Maps into an Ionic project, I have successfully added a custom overlay to display the address of a marker location on top of the map. By adding a click event listener to the map, I can detect clicks and update the marker for new locat ...

Creating a dropdown navigation menu using jQuery

I have been experimenting with creating a customized Drop Down menu using ul li and Jquery, following this helpful Tutorial. Here is the sample HTML Code for testing: <div id="dd" class="wrapper-dropdown-3" tabindex="1"> <span>OS</span> ...

Discovering the indices of undefined array elements in JavaScript without using a loop

Is there a way in JavaScript to retrieve the indexes of undefined array elements without using a loop? Possibly utilizing a combination of map, filter, and indexOf? I have a loop solution that I'm seeking an alternative for - something more concise, ...

Dynamically load WordPress content using ajax and incorporate CSS3 animations for added visual appeal

It's time for a new challenge to push my learning curve. I've never ventured into the world of ajax before, but it seems like a skill I need to acquire. What better opportunity to learn than by implementing it on a fresh portfolio site. The main ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Is it possible to use Ajax post with localhost on Wamp server?

Looking to execute a basic POST function using Ajax on my localhost WAMP server. Here's the code I have: function fill_table() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...

Struggling to perform a basic http GET request in Angular 2

Attempting to create a basic http GET request in my Angular2 app: this.http.get("https://mybaseurl.com/hello") .map(res => res.json()) .subscribe( function(response) { console.log("Success Response" + response)}, function(error) { conso ...

In PowerShell, use the "ConvertTo-Html" commandlet to incorporate

I have a script that retrieves data from a server, converts it to HTML, and then sends the report via email. Here is a snippet of the script: $sourceFile = "log.log" $targetFile = "log.html" $file = Get-Content $sourceFile $fileLine = @() foreach ($Line i ...

Localhost Firebase authentication with Facebook integration

I am currently working on a Vue.js app that integrates Firebase for authentication, specifically with the Facebook provider. Despite configuring my Firebase code correctly, I continue to encounter the "Can't load URL: The domain of this URL isn't ...

How to modify this to return a function and eliminate the need for declaring a function

Greetings! I understand that this may seem simple to some of you, but I am feeling quite lost. I've been tasked with removing the function declaration and converting it into a return function. Any assistance would be greatly appreciated. const canView ...

How can I load a URL without causing a page refresh?

While searching around, I stumbled upon this HTML 5 code snippet: window.history.pushState("object or string", "Title", "/new-url"); I started thinking: how can this be implemented? Is there a way to utilize this code to change the URL to without needin ...

The implementation of $(this).addClass within AJAX success is not yielding the desired results

Currently, I am working on some ajax processing for a click event. Everything is functioning correctly so far, but now I have encountered an issue when trying to add a class in the success function. I am using $(this).addClass("cover");, however, nothing ...

Node.js seems to be playing tricks on me. It's creating bizarre names and tweets by utilizing arrays

Trying to decipher a snippet of code that is tasked with generating random tweets has left me puzzled. Specifically, I find myself stumped when it comes to understanding the line: Math.floor(Math.random() * arr.length) I believe this line selects a rando ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

Choose a single SVG file based on its unique ID

Looking for some guidance - I have a vector file with 40 svgs all combined into one image. Each vector is identified by an id inside the <g> tag. How can I select a specific svg from this single file without choosing the entire image in html? PS: E ...

Switching the Vue image on Routerlink's isExactActive feature

Is there a way to display different images based on whether a link is active or not? <router-link to="/"> <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Something along these lines ...