Creating a stunning image slideshow with CSS-Grid and JavaScript

Having trouble creating a slideshow of images? I've checked the JavaScript code and there are no errors, but it just doesn't seem to work. Not sure what's going wrong.

$( document ).ready(function() {
    $('.work').scroll(function() {
        var $this= $('h2');
        $('.image').each(function () {
            var hT = $(this).offset().top,
            hH = $('h2').outerHeight(),
            wH = $('.work').height(),
            wS = $this.scrollTop();
            console.log((hT-wH) , wS);
        if (wS > (hT+hH-wH)){
                $('#count').text($(this).data('index'));
        }
        });
    });
});

function smallscreen() {
    if (window.innerWidth < 959) {var workSlide = document.querySelector('.work');
        var sliderImages = document.querySelectorAll('.work h2');
        var prevButton = document.querySelector('.prev');
        var nextButton = document.querySelector('.next');
        var counter = 1;
        const size = sliderImages[0].clientWidth;

workSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
/* more code here */
}
}
window.onload = window.resize = smallscreen;
@media only screen and (max-width: 959px) /*and (orientation:portrait)*/ {
    /* CSS styles for responsive design */
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DesignLover-Question</title>
</head>
<body>
    <div class="main">
        <div class="header">
            <div class="logo">
                <a href="https://www.example.com"><img src="example.jpg" alt="Logo"></a>
            </div>
            <h3><span id="count">1</span>/17</h3>
        </div>
        <div class="body">
            <div class="about">
                    <h1>Lorem ipsum dolor sit amet...</h1>
            </div>
            <div class="work">
                <!-- Images for slideshow -->
            </div>
            <div class="buttons">
                <button class="prev">PREV</button>
                <button class="next">NEXT</button>
            </div>
        </div>
        <div class="footer">
                <div class="phone">
                        <p>+31 123 12 12 12</p>
                </div>
                <ul class="media">
                    <li><a href="#" target="_blank">Example Link</a></li>
                    <li><a href="#" target="_blank">Another Link</a></li>
                    <li><a href="#" target="_blank">More Links</a></li>
                    <li><a href="#">Contact Us</a></li>
                </ul>
            
        </div>
    </div>
    <script src="JS/script.js" type="text/javascript"></script>
</body>
</html>

Answer №1

To achieve the desired effect, ensure that you are transitioning the elements within the .work class and not the .work class itself.

Below is a simplified version of an image carousel that you can use as reference:
(You can also view it on JSFiddle)

class Slider {
  constructor(el) {
    this.el = el;
    this.activeIndex = 0;
    this.numItems = this.el.children().length;
    // auto-advance slider
    this.interval = setInterval(() => this.next(), 5000);
  }
  
  prev() {
    this.activeIndex--;
    if(this.activeIndex < 0)
      this.activeIndex = this.numItems - 1;
    this.updateDom();
  }
  
  next() {
    this.activeIndex++;
    if(this.activeIndex >= this.numItems)
      this.activeIndex = 0;
    this.updateDom();
  }
  
  updateDom() {
  this.el.children().css('transform', `translateX(-${this.activeIndex}00%)`)
  }
}

$(() => {
  let slider = new Slider($(".work"));
  $(".prev").click(() => slider.prev());
  $(".next").click(() => slider.next());
});
.work {
  /* Specify the size of the image box (can be in any unit you want)*/
  width: 500px;
  height: 300px;
  overflow: hidden;
  display: flex;
}

img {
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
  will-change: transform;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="work">
  <img src="https://picsum.photos/500/300?1">
  <img src="https://picsum.photos/500/300?2">
  <img src="https://picsum.photos/500/300?3">
  <img src="https://picsum.photos/500/300?4">
  <img src="https://picsum.photos/500/300?5">
</div>
<button type="button" class="prev">
  PREV
</button>
<button type="button" class="next">
  NEXT
</button>

If you require a more robust solution for production, consider utilizing one of the following existing libraries:

  • slick
  • swiper
  • lightslider
  • Owl Carousel

Edit:
Here is a functional JsFiddle link with your code.

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 Vuex and Jest - Accessing undefined property <getterName>

Currently, I am attempting to utilize Jest for testing a Vue component that relies on a getter in Vuex. The getter is structured to return a function that ultimately provides an array: questions: state => pageNumber => state.pages[pageNumber].questi ...

Jasmine - What is the best way to simulate a finally block?

After creating a controller in my test, I encountered an issue with the updateActionList function... this.createScope = function(scope) { if (scope) { this.scope = scope; } else { this.scope = $rootScope.$new(); } this.contro ...

Is there a way to position the drop-down menu in front of the slider?

Hey there, I'm currently experiencing some issues with the drop-down menu on my index page. The drop-down items are hidden below my image slider, which is directly underneath my navigation bar. I would really appreciate any help in fixing this so that ...

You are not allowed to have a union type as the parameter type for an index signature. If needed, consider using a mapped

I'm attempting to implement the following structure: enum Preference { FIRST = 'first', SECOND = 'second', THIRD = 'third' } interface PreferenceInfo { isTrue: boolean; infoString: string; } interface AllPref ...

Tips for designing seamless pagination on a mobile-friendly website with responsive design

My goal is to make pagination easily accessible on mobile devices for users of my website, similar to UIScrollView with paging enabled in iOS. However, it's important that the website remains functional and visually appealing on desktops as well. I h ...

JavaScript's efficient way to target multiple class names

My goal is to extract and process JSON data into specific instances of a class named "slide_content" I want to achieve something like this: slide_content[0] Unfortunately, JS does not offer a method like getElementByClass(). The relevant API data can b ...

Using a Svelte click event to toggle a boolean value in an array from a div

How can I modify the toggle functionality to work on any click event, not just on a button, in order to trigger a state change regardless of the element clicked? ToolBar.ts export default class ToolBar { options:Array<ToolBarOptions>; const ...

When using React, the auto-fill suggestions in forms are not displayed

Looking to enhance a React panel for adding new products, I've developed a separate auto-complete class. This special class should display an input field along with a list of suggested autofill items below. However, it seems that only the input elemen ...

Rewrite: "Rewriting URL POST requests in Node.js

Within my JavaScript file, I have this function: exports.authentication = function(req, res) { // .. // user validation // .. res.redirect('/login'); }; I'm looking to modify all POST requests to a different path, such as / ...

Utilizing React for captivating full-size image backgrounds

As a novice, I am faced with the challenge of making a full image background in my react portfolio project. Despite my efforts, I have been unable to achieve the desired outcome. How can I implement a full image background in React for my portfolio showca ...

Utilizing function arguments in ReactJS

Currently, I am in the process of learning ReactJs and have an inquiry about the code snippet below. Would someone be able to clarify the functionality of the removeTour code and why the id parameter is being used within the function? const removeTour = (i ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

I am having trouble with the CSS Hover and Active styling on my website

Below is the code for my navigation bar: <ul> <li><a href="index.html">HOME</a></li> <li><a href="portfolio.html">PORTFOLIO</a></li> <li><a href="resources.html">RESOURCES</a ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Display or conceal Div elements depending on the selected Radio Buttons, with their values retrieved from a database

How can I dynamically Show/Hide Divs based on Radio Buttons with checked values retrieved from a PHP and SQL database? <input type="radio" name="status" value="Ongoing" checked="checked">Ongoing<br> <input type="radio" name="status" value ...

Using Sequelize to create or update data with associated models

I am encountering an issue while attempting to add data to my database using Sequelize. I have two tables with the following association: const Price = sequelize.define('prices', { close: { type: Sequelize.INTEGER }, ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

Require an additional button to dynamically load more content and shift all existing elements further down the page

I am looking to implement a "load more" button for an Instagram feed on my website. My current approach involves increasing the height of a specific section while moving the rest of the page down. This is what I have tried: <script> $(document.ready ...