What is the best way to resize my JQuery image slider to match the width of the screen?

I've been working through a YouTube tutorial on creating a JQuery image slider, but I’ve hit a snag in my code and can’t seem to figure out the issue.

My goal is to have the images span the full width of the screen, similar to how Apple features them on their website. apple website

I attempted adjusting everything to 100% width, but unfortunately, this caused my slider to break.

$(function() {

  //variables 
  var width = $('img').width();
  var animationSpeed = 500;
  var pause = 4000;
  var currentSlide = 1;
  var interval;

  var $slider = $("#slider");
  var $slideContainer = $slider.find(".slides");
  var $slides = $slideContainer.find(".slide");

  function startSlider() {
    interval = setInterval(function() {
      $slideContainer.animate({
        "margin-left": "-=" + width
      }, animationSpeed, function() {
        currentSlide++;
        if (currentSlide === $slides.length) {
          currentSlide = 1;
          $slideContainer.css('margin-left', 0);
        }
      });
    }, pause);
  }

  function stopSlider() {
    clearInterval(interval);
  }

  $slider.on('mouseenter', stopSlider).on('mouseleave', startSlider);

  startSlider();
});
@import url(https://fonts.googleapis.com/css?family=Pacifico);
 body {
  margin: 0px;
  background: #e6e6e6;
  color: white;
}
header {
  width: 100%;
  background: rgba(0, 0, 0, 0.7);
  color: #e6e6e6;
  padding: 1px;
  position: fixed;
  z-index: 999;
  font-size: 100%;
  text-align: center;
}
nav {
  margin: 1;
  display: inline;
  white-space: nowrap;
}
#webSiteName {
  font-size: 1em;
  display: inline;
  padding: 40px;
  font-family: 'Pacifico', cursive;
}
.pages {
  font-size: 0.7em;
  color: white;
  list-style-type: none;
  display: inline-block;
  padding: 10px 40px;
  text-decoration: none;
  font-family: arial;
}
.pages:hover {
  color: #a6a6a6;
  cursor: pointer;
}
#slider {
  width: 720px;
  height: 400px;
  overflow: hidden;
}
#slider .slides {
  display: block;
  width: 6000px;
  height: 400px;
  margin: 0;
  padding: 0;
}
#slider .slide {
  float: left;
  list-style-type: none;
  width: 720px;
  height: 400px;
}
img {
  width: 720px;
  height: 400px;
}
/*# sourceMappingURL=stylesheet.css.map */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>Example Website</title>
  <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
</head>

<body>
  <header>
    <nav>
      <a href='' id='webSiteName' class='pages'>Example</a>
      <a href='' class='pages'>Page</a>
      <a href='' class='pages'>Page</a>
      <a href='' class='pages'>Page</a>
      <a href='' class='pages'>Page</a>
    </nav>
  </header>

  <div id="slider">
    <ul class="slides">
      <li class="slide">
        <img src="images/slider1.png" />
      </li>
      <li class="slide">
        <img src="images/slider2.jpg" />
      </li>
      <li class="slide">
        <img src="images/slider3.jpg" />
      </li>
      <li class="slide">
        <img src="images/slider1.png" />
      </li>
    </ul>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="js/script.js"></script>
</body>

</html>

Answer №1

Ensure to apply width:100% to specific elements like the slider, slides, and images.

#slider {
  width: 100%;
  overflow: hidden;
}
#slider .slides {
  display: block;
  width: 100%;
  height: 400px;
  margin: 0;
  padding: 0;
  float:left;
}

#slider .slide {
  float: left;
  list-style-type: none;
  width: 100%;
  height: 400px;
}
img {
  width: 100%;
  height: 400px;
}

For reference, view this JSFiddle which showcases the images in red at 100% scale.

Answer №2

Alright, here's the solution:

Begin by setting up all your width: 720px to a percentage of 100%. However, if you do this, your .slide will take up 100% of its parent (equaling 6000px), which is too large.

To address this issue, I included a reference size on #slider (by utilizing position:relative, its size becomes the 100%). By employing width: 100vw;, you create a connection to the viewport width (defined by the position:relative).

Now, you have an effective slideshow that scales properly to 100%. However, when users resize the window, adjustments are needed. Firstly, I incorporated a trigger for resizing to update the width variable and adjust the CSS accordingly. Secondly, I recalculated the margin based on the width and currentSlide to maintain relative margins during user resizes, preventing any extreme negative positions.

View Final JSFiddle Version

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

Determine the yearly timetable by comparing it with the present date in MVC4

I'm looking for a way to calculate the annual date by considering the current date in an MVC project. Specifically, I want to display the date "2017/mar/24" in my textbox based on the current date. Do you know if there is any possible solution using C ...

Accessing session values using JavaScript

For my asp.net project, I have incorporated an external javascript file. Is there a way to access the session value within this javascript file? Appreciate any guidance on this matter! ...

Using a PHP array as a parameter in a link for an AJAX function

I am attempting to pass a PHP array to an AJAX function in order to populate dynamically created tables. To achieve this, I need to pass the values in an array all at once to avoid the issue where only the last dynamic table is populated. However, it see ...

Learning SQL and PHP is essential for displaying data from a database in a dynamic table on a web page. In order to select specific columns from the database and arrange them in

I am working with a sql table called res that contains various rows and columns. Here is an example of the data: Sno RegNo Name sub1 sub2 sub3 total percent result color 1 1DU12CS100 s1 10 10 10 30 50 fail danger 2 ...

Obtain the total sum and count of values stored in a VueJS checkbox data attribute

<tr v-for='(women, index) in womenServices' :key="index"> <td class="text-center" style="width: 30px;"> <div class="custom-control custom-checkb ...

Split the list items based on their heights if they exceed the height of the unordered list

I'm exploring ways to transform dynamic content into slides. Essentially, I have a <ul> element that is sized 300x100 pixels. As the list items within it exceed the height of the <ul>, I aim to group these overflowing items into divs, crea ...

The React functional component fails to display on the screen

When the validate function is called, it is expected to return an element if the getConjugation function does not return an error. However, even when valid input is passed to getConjugation, it only displays nothing in the browser. import React from &apos ...

Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game. The obj ...

Flexible DIV Grid Design with Overlapping Absolute Div Elements

My goal is to replicate the layout shown in this screenshot view screenshot here I want the layout to be responsive, with DIV B moving below DIV A when the screen is resized. DIV B is positioned absolutely to cover content and DIV C. Both DIV C and DIV ...

Modify KendoUI Donut chart series label color to match the series color

Currently, I am utilizing kendoUI in combination with angular to create a Kendo Donut chart. Below is the representation of my chart. <div class="center-pad" kendo-chart k-theme="['material']" k-chart-area="{height: 325, width: 480}" k- ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Bidirectional data flow in AngularJS Directives

In an effort to create a dynamic form with different "widgets" based on field types and parameters stored in a database, I have been exploring directives for handling layout changes in response to various scenarios. After experimenting with some examples, ...

What is the impact of using overflow: hidden on block elements?

HTML <div class="top"><p>hello</p></div> <div class="bottom"><p>hello</p></div> CSS .bottom { overflow: hidden; } While delving into the world of CSS, I encountered an interesting qu ...

What is the best way to find elements in a jquery array that match any part of the text within a div?

I'm almost there in getting this to work. I just need to figure out how to check if a specific item from an array is present in the text inside div containers with a particular class. This is what I attempted to do using the indexOf method to search ...

Press the mouse button to position the camera close to an element in Three.js

Trying to implement a click to zoom feature with Three.js, I have a canvas and an object loaded in it. When clicking, I want to position the camera near the point of intersection for a zoom effect. Here is my current code, but it's not working as exp ...

The Model.function method is not a valid function that can be used within a router

Currently facing a challenge with my router setup. I have exported the function as shown in the code snippet below. This is the Model I am using: "use strict"; var mongoose = require('mongoose'); var bcrypt = require("bcryptjs"); var Schema = m ...

Leverage TypeScript generics to link props with state in a React class-based component

Can the state type be determined based on the prop type that is passed in? type BarProps = { availableOptions: any[] } type BarState = { selectedOption: any } export default class Bar extends React.Component<BarProps, BarState> { ...

Inserting POST request data into subdocument arrays of a database

I am struggling to add data to a nested mongoose sub-document when creating a new schema from the client side. Only the data that is not nested inside another schema/array is being sent over to the database. My database setup includes MongoDB with Mongoos ...

The Discord bot seems to be stuck in time, relentlessly displaying the same start time without any updates in between. (Built with Node.js and Javascript

const Discord = require('discord.js'); const client = new Discord.Client(); var moment = require('moment'); const token = '//not telling you this'; const PREFIX = '!'; client.on('ready', () =>{ con ...

Guide on declaring package.json during library publication in Angular 6

Building node modules using Angular6 should be a breeze. The Documentation outlines the following steps: ng generate library YOUR-LIBRARY ng build YOUR-LIBRARY --prod cd dist/YOUR-LIBRARY && npm publish By following these steps, a new project wi ...