What is the best way to ensure that child elements within a container div are centered when scrolling left and right?

When attempting to handle the 'scroll' event, I noticed that the callback function only records the position of the div as the last position. I am looking for a way to determine if the div is in the center, which is my target.

const slide = document.querySelector(".slides")

slide.addEventListener('scroll', function(e) {
  const slide2 = document.querySelector("#slide-2")
  console.log(slide2.offsetLeft)
})
<div class="slider">
  <a href="#slide-1">1</a>
  <a href="#slide-2">2</a>
  <a href="#slide-3">3</a>
  <a href="#slide-4">4</a>
  <a href="#slide-5">5</a>
  <div class="slides">
    <div id="slide-1">1</div>
    <div id="slide-2">2</div>
    <div id="slide-3">3</div>
    <div id="slide-4">4</div>
    <div id="slide-5">5</div>
  </div>
</div>

I aim to determine if the user is on the right or left side of the div in order to activate dots for my slider. My approach is to stick with native JavaScript for this purpose :)

Check out my Codepen example https://codepen.io/lpllplp222/pen/BaRvwKm

Answer №1

In order to achieve the same functionality, I utilized the power of jQuery.

The position() function within jQuery allowed me to determine the current position of an element from its top and left. By utilizing the left value, I was able to calculate the active element and assign an active class to the corresponding dot.

const slide = document.querySelector(".slides")

$('#slider-dots a').on('click', function(event) {
  event.stopPropagation();
})

slide.addEventListener('scroll', function(e) {
  var scrollLeft = $('#slides-wrapper').scrollLeft();
  var currIndex = -1;
  $('#slider-dots a').removeClass('active');
  for(var i = 0; i<$('#slides-wrapper div').length; i++) {
    if($($('#slides-wrapper div')[i]).position().left >= 0 && currIndex === -1) {
      currIndex = i;
    }
  }
  $($('#slider-dots a')[currIndex]).addClass('active');
})
* {
  box-sizing: border-box;
}

.slider {
  width: 400px;
  text-align: center;
  overflow: hidden;
}

.slides {
  display: flex;

  overflow-x: auto;
  scroll-snap-type: x mandatory;

  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;

  /*
  scroll-snap-points-x: repeat(300px);
  scroll-snap-type: mandatory;
  */
}
.slides::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
#slider-dots a.active {
  color: violet;
  background-color: #000;
}
.slides::-webkit-scrollbar-thumb {
  background: black;
  border-radius: 10px;
}
.slides::-webkit-scrollbar-track {
  background: transparent;
}
.slides > div {
  scroll-snap-align: start;
  flex-shrink: 0;
  width: 300px;
  height: 200px;
  margin-right: 50px;
  border-radius: 10px;
  background: #eee;
  transform-origin: center center;
  transform: scale(1);
  transition: transform 0.5s;
  position: relative;

  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 100px;
}
.slides > div:target {
/*     transform: scale(0.8); */
}
.author-info {
  background: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 0.75rem;
  text-align: center;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  margin: 0;
}
.author-info a {
  color: white;
}
img {
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.slider > a {
  display: inline-flex;
  width: 1.5rem;
  height: 1.5rem;
  background: white;
  text-decoration: none;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin: 0 0 0.5rem 0;
  position: relative;
}
.slider > a:active {
  top: 1px;
}
.slider > a:focus {
  background: #000;
}

@supports (scroll-snap-type) {
  .slider > a {
    display: none;
  }
}

html,
body {
  height: 100%;
  overflow: hidden;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom, #74abe2, #5563de);
  font-family: "Ropa Sans", sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider" id='slider-dots'>
  <a href="#slide-1">1</a>
  <a href="#slide-2">2</a>
  <a href="#slide-3">3</a>
  <a href="#slide-4">4</a>
  <a href="#slide-5">5</a>

  <div id='slides-wrapper' class="slides">
    <div id="slide-1">
      1
    </div>
    <div id="slide-2">
      2
    </div>
    <div id="slide-3">
      3
    </div>
    <div id="slide-4">
      4
    </div>
    <div id="slide-5">
      5
    </div>
  </div>
</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

Flexbox: changing the order and arranging columns in a vertical stack

At a specific screen size, I need to rearrange three columns on my website. Currently, the layout consists of two columns that are 1/4 width each with a 1/2 width column in between them. I want to change the two 1/4 width columns into 1/2 widths and stac ...

Mastering the art of horizontal alignment in forms

So, within my render function, the following code is used: render() { <div> <form id="one"> <TextField id="t1" ... /> <Button id="b1" /> </form> <div id="empty"><div ...

Get tabular information in xlsx format by utilizing the xlsx npm package for download

I have been attempting to convert my json-like data into an xlsx file format. I utilized the xlsx npm package and followed various code samples available online, however, when trying to open the file in Excel, I encountered the following error: https://i.s ...

`Exploring the magic of CSS image overlay feature`

I would appreciate it if you could walk me through the implementation of this overlay code... .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ...

What are the steps for displaying multiple input fields using the onchange method?

$(document).on("change","#noofpack",function(){ count = $(this).val(); for(i=1;i<=count;i++){ $("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">'); ...

Jquery animate - callback is triggered before animation finishes running

Is there a way for the element to first expand in height and then apply a background image once the height change is complete? Currently, I am experiencing laggy performance as the background image is applied before the height animation finishes. Can som ...

The data being transmitted by the server is not being received accurately

Hey there! I've recently started using express.js and nodejs, but I've encountered an issue where my server is sending me markup without the CSS and JS files included. const express = require('express'); const app = express(); const htt ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Easily done! Using JavaScript to generate a blinking cursor on a table

Working on a project to develop a dynamic version of the classic game Tic-Tac-Toe... However... Every table cell is displaying an irritating flashing cursor, almost like it's behaving as an input field. Any insights into why this is happening...? O ...

As the number of lines increases by x%, CSS gradients gradually fade away during the generation process

Is there a way to create a gradient that displays a red line every x% without the colors fading into white? As I add more lines, the red stripes seem to lose their intensity and blend into a white background. The .four-stripes selector creates a good resu ...

Retrieve every HTML element that is currently visible on the screen as a result

I have a dynamic HTML table that updates frequently, with the potential for over 1000 rows. Instead of replacing the entire table each time it updates, I am exploring options to only update the visible rows. My initial approach involved iterating through ...

"Change opacity smoothly with the FadeToggle feature for a

I have a question that might seem silly, but I can't quite figure it out. How can I extend the duration of the fade effect? window.switchIn = function() { $('.red').fadeToggle(function(){ $('.blue').fadeToggle(function() { ...

sending data from an AngularJS application to an MVC controller in JSON format containing multiple arrays

Currently, I am working on a project that involves using AngularJS and MVC. I am transferring data from an AngularJS controller to my MVC controller using $http.post(). At the moment, I am using a single object or JSON array to retrieve data as follows: pu ...

An issue has been discovered where IE8 is unable to print an image within the :before pseudo

Is there a way to display an icon image before text without using HTML tags like <img> that may interfere with our JavaScript code if the structure of the HTML changes? I came up with the following code which successfully displays the icon on IE8 an ...

Fading Out with JQuery

My page contains about 30 same-sized divs with different classes, such as: .mosaic-block, .events, .exhibitions, .gallery, .sponsors, .hospitality, .workshops, .lectures { background:rgba(0, 0, 0, .30); float:left; position:relative; overf ...

What is the best approach in Ruby for managing an unordered list with split columns and counting each

I am currently in the process of strategizing the layout for a webpage utilizing Bootstrap 4 within Ruby on Rails. Specifically, I need to create a sidebar submenu that can expand and collapse, feature bullet points, and include a counter. The desired out ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

Can integers be used as keys in a JavaScript object's storage?

Currently, I am in the process of creating a JSON index file to serve as a database index for a javascript application that is currently under development. The structure of my index will resemble the following: { "_id": "acomplex_indice ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

Wait for the definition of a variable before returning in React Native

I am currently receiving data asynchronously and displaying it within the render() function using {data}. My dilemma is how to ensure that the render() function waits until the variable is defined. Currently, the placeholder variable remains the same or d ...