Personalized jQuery Slider with automatic sliding

I am currently working on creating my own image slider without relying on plugins.

1st inquiry : How can I achieve horizontal animation for the slider?

2nd inquiry : I want the images to cover both the height and width of their container while maintaining their original proportions. The images may be partially displayed. How can I accomplish this?

3rd inquiry : If anyone has any suggestions on optimizing and refining the slide code to make it more lightweight and elegant, please share your insights.

$(function(){
  setInterval(function(){
    var displayed = $(".img-header.displayed");
    displayed.animate({opacity : 0}, 500, function() {
      displayed.css("display","none");
      displayed.addClass("not-displayed").removeClass("displayed");

      if(displayed.next(".img-header.not-displayed").length == 0){
        $(".img-header:first").css("display","inline-block").css("opacity","1");
        $(".img-header:first").addClass("displayed").removeClass("not-displayed");
        $(".img-header:first").animate({opacity : 1}, 500);
      }
      else{
        displayed.next(".img-header.not-displayed").css("display","inline-block").css("opacity","1");
        displayed.next(".img-header.not-displayed").addClass("displayed").removeClass("not-displayed");
        displayed.next(".img-header.not-displayed").animate({opacity : 1}, 500);
      }                  
    });
  }, 4000);
});
#slider-container{height: 200px; width: 200px;}
#slider-container img.img-header{ width: 100%; height: auto;}
.displayed{display: inline-block;}
.not-displayed{display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
  <img class="img-header displayed" src="https://i.stack.imgur.com/AIHnl.png" />
  <img class="img-header not-displayed" src="https://i.stack.imgur.com/XQrms.png" />
</div>

Answer №1

It seems like you are searching for a solution that looks something like this.

The slider is set to have position:relative; with top:100px;, which can be adjusted according to your needs. It is recommended to keep it positioned relatively.

The slider has dimensions of width:700px and height:500px;, but these can be customized based on the aspect ratio of the images you are using. The setup will work well for images with different aspect ratios.

There is an array designated for loading images in sequence from one location, so some additional context on that may be helpful. I've left a comment about this in the JavaScript file.

You also have the flexibility to change the slider speed and delay to suit your preferences.

When you hover over an image, the slider will pause, and then resume once you move away from the image.

Snippet :

$(document).ready(function(){

  var noPannel = document.getElementsByClassName("pannel").length;
  var i;
  var imgArr = [ ];
  var pannelWidth = $(".slider_holder").width();
  var totalWidth = noPannel*pannelWidth;

  for (i=1;i<=noPannel;i++)
  {
    imgArr[i] = "http://www.picget.net/background/" + i + ".jpg"; //if you have somewhere on other path

    //imgArr[i] = " " + i + ".jpg"; //use this if you have image in same folder/path.
  }
  for(i=1;i<=noPannel;i++)
  {
    $(".pannel:nth-child("+i+")").css("background","url("+imgArr[i]+")");
  }
  function jsslider()
  {
    var curScroll = $(".slider").scrollLeft();
    var endScroll = totalWidth - (pannelWidth*2);

    if(curScroll<=endScroll)
    {
      $(".slider").animate({scrollLeft: '+=' + pannelWidth +'px'},900,"swing");// Replace 900 for speed
    }
    else
    {
      $(".slider").animate({scrollLeft: '0px'},500,"swing"); // Replace 500 for speed to go bck to first
    }
  }

  var interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
  $(".pannel").hover(function () {
    clearInterval(interval);
  }, function () {
    interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
  });

}); // document.ready ENDS
html, body, *
{
  margin:0px;
  width:100%;
  height:100%;
}

.slider_holder
{
  margin-left:auto;
  margin-right:auto;
  display:block;
  position:relative;
  top:100px;
  width:1024px;
  height:768px;
  background:#eee;
  overflow:hidden;
}

.slider
{
  width:auto;
  height:100%;
  width:100%;
  white-space: nowrap;
  overflow:hidden;
}

.pannel
{
  margin:0px;
  display:inline-block;
  width:100%;
  height:calc(100% - 1px);
  /*border:1px solid red;*/
  background-size:cover !important;
  background-repeat:no-repeat;
  background-position:50% 50% !important;
  position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="sliderFunc()">
  <div class="slider_holder">
    <div class="slider">
      <span class="pannel"> </span>
      <span class="pannel"> </span>
      <span class="pannel"> </span>
      <span class="pannel"> </span>
      <span class="pannel"> </span>
    </div>
  </div>
</body>

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

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Tips on applying the "activate" class to a Bootstrap navbar in Angular 2 when implementing page anchor navigation

As I work on my single-page website using Angular 2 and Bootstrap 4, I have successfully implemented a fixed navbar component that remains at the top of the page. Utilizing anchor navigation (#id), the navbar allows smooth scrolling to different sections o ...

Exploring the integration of Django Rest Framework with Angular

I am just starting out with Django Rest Framework (DRF) and AngularJs. I am trying to figure out the best way to integrate these two technologies. Combining DRF and AngularJs in one project (Most of the tutorials recommend this) Using DRF as the backend ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...

Transferring shapes from a two-dimensional equirectangular view to surfaces in A-Frame

Currently, my goal is to create a hotspot editor for 360-degree images using A-Frame. The concept behind this project involves allowing users to draw on an equirectangular panorama and then having the tool convert those drawings into planes using THREE.Sh ...

Press the button to retrieve the div ID needed for a jQuery modal dialog box

I am currently utilizing a jQuery modal dialog box in the following manner: <div class="dialog-form" id="dialog-form1" title="Edit Invoice"> <form> .... inputs & selects </form> </div> <button class="dialog-but ...

Substitute all instances of <table> with <div> tags, making sure to include specifications for

Currently, I find myself immersed in a project that relies heavily on tables, which isn't exactly ideal but is what the marketing department insists upon... To tackle this issue, I have implemented jQuery to convert all tables into DIVs, and so far, ...

A concern arises with security when utilizing jQuery alongside json for requesting data from a service

When calling a service with jQuery, there may be concerns about exposing the service call to savvy users who could intercept it using tools like Fiddler or custom web applications. $.ajax({ url: SERVICE_URL?Q1=eee&Q2=sss, dataType: "application/ ...

Discovering the oldest date in an array with JavaScript

Is there a way to identify the earliest date, also known as the minimum date, within an array using JavaScript? For instance: ["10-Jan-2013", "12-Dec-2013", "1-Sep-2013", "15-Sep-2013"] The desired output would be: ...

Using flexbox to adjust the height of a block in the layout

Is there a way to modify the height of .half-containers1 and .half-containers2? Additionally, how can I create the triangle shape that is shown in the image? Is it achievable with CSS alone or do I need to use an image? Check out my fiddle for reference ...

The background of the ACTK Modal Popup vanishes after multiple instances of scrolling up and down

The issue I'm facing is with the AJAX Control ToolKit Modal Popup's background (the blind curtain) disappearing after scrolling up and down several times. I have attempted to resolve this by applying various CSS styles, but unfortunately, none of ...

Bug causing connection issues in Node.js when dealing with IP redirection

I recently encountered an issue with NodeJS while using a kafka node on a node-red instance installed on my RPI3. Let me paint you the scenario: I have a cluster set up with a functioning Kafka instance. The machine hosting the Kafka broker has a private ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

The fetch API does not retain PHP session variables when fetching data

After setting session variables in one php file, I am attempting to access those values in another php file. session_start(); $_SESSION['user'] = $row['user']; $_SESSION['role'] = $row['role']; However, when ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

How can I determine if a user has reached the end of a non-scrollable div by utilizing HostListener and directives within Angular?

In my Angular project, I have designed a main layout using flex display with specific height and overflow settings. The main content div inside this layout has its own unique styling to ensure consistent appearance for any components inserted within it. By ...

Exploring the capabilities of HTML5's file API along with Octokit.js to work with

I have been trying to create a form that allows users to upload binary data to GitHub using octokit.js. However, every time I attempt to do so, the data ends up corrupted on the GitHub side. Here is a minimal working example: http://jsfiddle.net/keddie/7r ...

The AJAX response doesn't seem to be halting

My AJAX request looks like this: $.ajax({ url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid", type: "POST", timeout: 3000, data: JSON.stringify(sendingdata), ...