loading images in slider without sacrificing performance (vanilla JavaScript)

Currently, I am attempting to incorporate lazy-loading images property into my slider using JS. I came across a solution from T.J. Crowder on Lazy loading images how. However, I seem to be facing an issue as nothing is showing up in the console. Could someone provide me with some guidance on how I can troubleshoot and successfully implement lazy-loading for the slider?

Below is the JS script for reference:

var slideIndex = 0;
setTimeout(slider, 3000);

var move_left = 0;

function setMoveLeft(){
    if (move_left != (document.getElementsByClassName("part")[0].offsetWidth + 4)) {
        move_left = document.getElementsByClassName("part")[0].offsetWidth + 4;
    }
}
setMoveLeft();

window.onresize = function(event) {
    setMoveLeft();
};

var prod, imgsrc, img;

prod = document.getElementsByClassName('part');
imgsrc = prod.getAttribute('data-src');

if (imgsrc) {
    img = document.createElement('img');
    img.src = imgsrc;
    prod.appendChild(img);
    prod.removeAttribute('data-src');
}


function slider() {
    var i;
    var x = document.getElementsByClassName("part");
    for (i = 0; i < x.length; i++) {

    }
    slideIndex++;

if (slideIndex >= x.length) {
        slideIndex = 0
    }
document.getElementsByClassName("content-handler")[0].style.marginLeft = (-move_left*slideIndex)+"px"



    setTimeout(slider, 3000);
}

Here is the HTML code snippet:

<div class="row slider-container">
    <section class="content"> 
        <div class="content-handler">
            <div id="img1" data-src="img/mockup-863469_1920.jpg" class="part">
                <h3>title</h3>
                <p>text</p>
            </div>
            <div id="img2" data-src="img/board-453758_1920.jpg" class="part">
                <h3>title</h3>
                <p>text</p>
            </div>
            <div id="img3" data-src="img/digital-marketing-1433427_1920.jpg" class="part">
                <h3>title</h3>
                <p>text</p>
            </div>
            <div id="img4" data-src="img/action-2277292_1920.jpg" class="part">
                <h3>title</h3>
                <p>text</p>
            </div>  
        </div>
    </section>
</div>

Lastly, here is the styling provided by CSS:

/*CSS STYLES OMITTED FOR BREVITY*/

Answer №1

In your JavaScript code, you are using prod.getAttribute(). The issue here is that prod is an array of elements returned by getElementsByClassName, which means it contains multiple elements with the same class name. To modify all these elements correctly, you need to enclose the code inside a for loop.

I have included a different image in this example to demonstrate that images do load as intended. However, it seems like the background image remains even after appending the new image. To achieve the desired look, consider removing the background-image styling once the image is loaded or adjusting the styling of the appended image tag accordingly.

var slideIndex = 0;
setTimeout(slider, 3000);

var move_left = 0;

function setMoveLeft() {
  if (move_left != (document.getElementsByClassName("part")[0].offsetWidth + 4)) {
    move_left = document.getElementsByClassName("part")[0].offsetWidth + 4;
  }
}
setMoveLeft();

window.onresize = function(event) {
  setMoveLeft();
};

var prod, imgsrc, img;

prod = document.getElementsByClassName('part');
imgsrc = new Array();
for (i = 0; i < prod.length; i++) {
  imgsrc[i] = prod[i].getAttribute('data-src');
  if (imgsrc) {
    img = document.createElement('img');
    img.src = imgsrc[i];
    prod[i].appendChild(img);
    prod[i].removeAttribute('data-src');
  }
}


function slider() {
  var i;
  var x = document.getElementsByClassName("part");
  for (i = 0; i < x.length; i++) {

  }
  slideIndex++;

  if (slideIndex >= x.length) {
    slideIndex = 0
  }
  document.getElementsByClassName("content-handler")[0].style.marginLeft = (-move_left * slideIndex) + "px"

  setTimeout(slider, 3000);
}
section {
  overflow: hidden;
  color: #F5F5F5;
}

div #img1 {
  background-image: url(https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg);
  background-position: center;
  background-size: cover;
}

div #img2 {
  background-image: url(https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg);
  background-position: center;
  background-size: cover;
}

div #img3 {
  background-image: url(https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg);
  background-position: center;
  background-size: cover;
}

div #img4 {
  background-image: url(https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg);
  background-position: center;
  background-size: cover;
}

div .slider-container {
  position: relative;
  height: 450px;
  margin-top: 50px;
}

div .content {
  width: 500px;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
}

div .content-handler {
  width: 5000px;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}

div .part {
  width: 500px;
  text-align: center;
  padding: 10px;
  border: 1px groove;
  background-color: #F5F5F5;
  color: #292929;
  display: inline-grid;
}

div .part h3 {
  font-size: 2em;
  border: 1px groove;
  background-color: #F5F5F5;
  color: #292929;
  opacity: 0.9;
  width: 400px;
  margin-left: 35px;
}

div .part p {
  font-size: 1.1em;
  line-height: 25px;
  padding: 15px;
  width: 400px;
  height: 250px;
  border: 1px groove;
  background-color: #F5F5F5;
  color: #292929;
  opacity: 0.9;
  margin-left: 35px;
}
<div class="row slider-container">
  <section class="content">
    <div class="content-handler">
      <div id="img1" data-src="https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg" class="part">
        <h3>title</h3>
        <p>text</p>
      </div>
      <div id="img2" data-src="https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg" class="part">
        <h3>title</h3>
        <p>text</p>
      </div>
      <div id="img3" data-src="https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg" class="part">
        <h3>title</h3>
        <p>text</p>
      </div>
      <div id="img4" data-src="https://blogs.mulesoft.com/wp-content/uploads/2012/03/hello-world.jpg" class="part">
        <h3>title</h3>
        <p>text</p>
      </div>
    </div>
  </section>
</div>

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

Is there a way to import an image from a different webpage using HTML?

Is it possible to load an image from another page using the load method? Here's an example: $("#result").load(url, 'tag.attribute') However, I am facing a challenge where I need to retrieve the path of the first image from a list on anothe ...

Customizable page layout with fixed width that adjusts based on content

I am looking to enhance the design of my website by updating its template. I want the content to be displayed within a fixed width centered div. While there are plenty of examples on the web for this, I want to ensure that existing text and tables in my ...

Is there a way to incorporate HTML input text into an image with CSS?

Here is an image that I have: https://i.sstatic.net/wHNk1.png Is there a way to add input fields to this image? I want the user to be able to click on the input fields (green boxes) within the image and enter values. How can I achieve this? ...

What steps can I take to avoid redirection after submitting form data in express.js?

Is there a way to prevent a redirect on an AJAX call in Express? I've tried using the "return false" method, but it doesn't seem to be working. How can I manage redirection after submitting data? The code below is functioning correctly, but it re ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

What is the best way to align two spans vertically on either side of a div, in relation to the div itself?

At the current moment, it appears as follows: _______________________________________ | | | ___________ | | | | | | ______ | div | ______ | | |s ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

Tips for retaining JWT token in local storage even after a page refresh

I am currently working on implementing a login/logout feature and utilizing the context API to manage functions such as storing tokens in local storage and removing them upon logging out. However, I have encountered an issue where the token stored in local ...

Issues encountered when trying to access a POST endpoint with .NET Framework 4.6.2

I have developed a WEB API using .NET Framework 4.6.2, specifically in my AuthController where I have implemented a test endpoint that requires a parameter. Unfortunately, I am encountering issues in hitting this endpoint and receiving the following error ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Make sure to prevent the submit button from being activated if there is any white space present in the

<form name="regForm"> <input type="text" id="username" name="username" ng-model="username" required> <button ng-click="submitSignup()" type="submit" ng-disabled=" (regForm.username.$dirty && regForm.username.$invalid) || regForm.use ...

Arrays can be either recreated or modified at different times

I've been trying to integrate a multiple image file selector in my React application. Here is the code for my input element: <input type="file" multiple onChange={handleImageChange} /> {renderPhotos(venueImages)} These are the functions that ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

Parallel mapping with simultaneous multiple inserts

I am working on inserting a list of topics with unique slugs into a MongoDB database. Here are two example topics: { title: "my title" }, { title: "my title" } After generating the slugs, I need to insert the topics: // Insert each topic async.map( ...

What causes the scope to shift when incorporating a Lazy function within the module pattern in JavaScript?

Implementation 1: Working code in normal var foo1 = function() { var t1 = new Date(); console.log("initialize - one time only " + this); foo1 = function() { console.log("Executes every time after initializing (initialize should not e ...

Is CSS treated differently in a Rails application?

There's something peculiar happening with two sets of identical html and css files that I have. One set is being loaded through Rails' index.html.erb file via a controller, while the other is running through my public folder as a control. The pub ...

Verifying if a dropdown option has been chosen through validation in JavaScript

Currently, I am working on implementing a validation block in my JavaScript code to ensure that users have selected a value before proceeding. If a value is not selected, I want to display a pop-up message prompting them to do so. function validate(form) ...

What is the process for cancelling a jQuery 3.0 AJAX request?

What is the best way to cancel an AJAX request in jQuery 3.0? this.request = $.ajax(); The newer version of jQuery does not support the abort method in promises. if(this.request && this.request.state() == 'pending') { this.request.abort(); & ...

Utilize the hexadecimal color code as a string within the darken function

When working with a less style, I have a string variable. @colorString: 'DADADA'; I can convert it into a color: @color: ~'#@{colorString}'; Then, I am able to use @color to define a value in a style: div { color: @color } However ...

JavaScript Callbacks and Promises: Exploring Asynchronous Programming

For the past 2 days, I've been struggling to figure out my mistake. It seems that I can't get past the "undefined" returned value because I'm having trouble grasping callbacks or promises. Despite reading numerous posts and trying simple exa ...