Issues with the functionality of a jQuery slider after converting it to vanilla JavaScript

While working on a slider project, I wanted to steer clear of using jQuery and instead focus on vanilla JavaScript for the implementation.

The original jQuery code snippet that needed conversion:

setInterval(function() {
  var $curr = $('#slider1 input[type=radio]:checked');  
  var $next = $curr.next('input');
  if(!$next.length) $next = $('#slider1 input[type=radio]').first();
  $next.prop('checked', true);

}, 2000);

Below is my attempted conversion to vanilla JavaScript, which unfortunately didn't work as intended. Can you help me identify what's causing the issue?

setInterval(() => {
  let $curr = document.querySelectorAll('#slider1 input[type=radio]:checked'),
    $next = $curr.nextSibling;

  if (!$next.length) {
    $next = document.querySelectorAll('#slider1 input[type=radio]').firstChild;
  }
  $next.setAttribute('checked', true);
}, 3000);
(CSS styles excluded for brevity)
<div class="csslider infinity" id="slider1">
  <input type="radio" name="slides" checked="checked" id="slides_1" />
  ... (additional input elements) ...
</div>

View on Codepen.


Edit

After some troubleshooting, I crafted this revised solution:

setInterval(function() {

  var currentID = document.querySelector('input[name="slides"]:checked').id;
  var idNoArr = currentID.split('');
  var intIdNo = parseInt(idNoArr[1]);
  var nextIdNo = intIdNo + 1;
  var NextId = idNoArr[0] + '' + nextIdNo;
  var NextInput = document.getElementById(NextId);

  if (!NextInput) {
    NextId = idNoArr[0] + '_1';
  }

  document.getElementById(NextId).checked = true;

}, 1000);

Answer №1

Various issues need to be addressed, such as:

  1. nextSibling is not restricted to inputs and can select white spaces between elements.
  2. Elements do not have a length property.
  3. When setting an attribute, it only applies the default state, not the current state.

I suggest choosing all input elements using querySelectorAll and iterating through them based on an index. To control the index within proper limits, I use the remainder of the current index divided by the total number of inputs.

Edit:

Your jQuery code determines which input is checked before changing the slide. This functionality allows the automatic rotation to resume where the user left off after manually selecting a slide. I have adjusted my code accordingly.

You may also want to include a feature that stops or delays the automatic rotation if the user selects a slide manually. When a user clicks on a specific slide, you could consider pausing the automatic rotation for a few seconds or halting it completely. Just a suggestion.


Check out this example in action:

// select node list of all inputs
var allInputs = document.querySelectorAll('#slider1 input[type=radio]');

// function to determine index of "checked" input in the list
function getCheckedIndex(list) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].checked) {
      return i;
    }
  }
}

// start the interval
setInterval(() => {

  // determine index of "checked" input
  let index = getCheckedIndex(allInputs);

  // determine the next index
  index = (index + 1) % allInputs.length;

  // set the "checked" property
  allInputs[index].checked = true;

}, 1000);
.csslider {
  -moz-perspective: 1300px;
  -ms-perspective: 1300px;
  -webkit-perspective: 1300px;
  perspective: 1300px;
  display: inline-block;
  text-align: left;
  position: relative;
  margin-bottom: 22px;
}
/* CSS properties continue... */
<div class="csslider infinity" id="slider1">
  <input type="radio" name="slides" id="slides_1">
  <input type="radio" name="slides" id="slides_2">
  <input type="radio" name="slides" id="slides_3" checked>
  <input type="radio" name="slides" id="slides_4">
  <input type="radio" name="slides" id="slides_5">
  <input type="radio" name="slides" id="slides_6">
  <ul>
    <li>Slide 1</li>
    <li>Slide 2</li>
    <li>Slide 3</li>
    <li>Slide 4</li>
    <li>Slide 5</li>
    <li>Slide 6</li>
  </ul>
  <div class="arrows">
    //* Labels and arrows HTML code continues... *
  </div>
  <div class="navigation">
    //* Navigation buttons HTML code continues... *
  </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

Utilizing previously written HTML code snippets

While working on a page within a legacy application, I find myself repeatedly reusing a large HTML block of code. The entire HTML and JavaScript codebase is quite old. The specific HTML block in question spans over 200 lines of code. My current strategy in ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

Convert HEX to RGB color format

Is it possible to utilize jQuery to call a function that converts a HEX value to RGB and then insert the HTML? Here is the JavaScript code: function convertHexToRGB( color ) { var r, g, b; if ( color.charAt(0) == '#' ) { color = ...

Overriding CSS with Autofill

Hey there, I could really use some guidance with CSS while working on my project using Next.js 13.4 and Typescript. Currently, I'm dealing with a form that consists of two input fields for login and password. While testing on Google Chrome and Mozill ...

Function triggered twice upon checkbox being selected

Below is the code snippet I am using: $("#cc1").unbind('click').click(function(e) { //somefunction }); This code works perfectly fine for executing a function after clicking the cc1 button. However, when I use the following code: $("#cc1" ...

Having issues with jQuery's .hover and .mouseleave functions causing unintentional looping. Any suggestions on how to resolve this

What I want to achieve: When hovering over the image, it fades out. Text should fade in after the image fades out. Text should fade out when the mouse leaves. The original image should fade back in. End with the original image and no text displayed. Iss ...

Building dynamic 3D scenes using JSONLoader in Three.js and Angular4

Having trouble integrating a JSON file into an Angular 4 environment using a JSONLoader. The path to the JSON file is correct, but I can't add it to the scene. I'm receiving an error "cannot set property 'mesh' of undefined" on the line ...

Vue 2 failing to retain component data upon page refresh

I've encountered a peculiar issue with Vue (v2.6.14) where I'm trying to create a new array based on one received as a prop. Here's the code snippet that's causing the trouble: props: { employees: Array }, data() { return { sorted ...

Verification of three-dimensional password format with the use of AngularJS

I am trying to implement password validation in Angular.js that requires a combination of alphabetical, numerical, one upper case letter, one special character, no spaces, and a minimum length of 8 characters. How can I achieve this using Angular.js? Here ...

Unable to detect any errors in the CSS file

Using RSpec to write some feature tests, I encountered an error in my application where a pre-purchased template with numerous styles is causing issues. Upon running the specs, the following error occurred: ActionView::Template::Error: Invalid CSS ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

Aligning a label in the center of a horizontal layout's vertical axis

Struggling with centering a QLabel vertically in a QHBoxLayout. Here's the relevant part of my code: QFrame* topBar = new QFrame(); topBar->setStyleSheet("background-color: #2c3d50;border-bottom: 3px solid #2c92b6;"); topBar->setSizePolicy(QSiz ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Is it necessary to include `load` events if scripts are placed at the bottom of the body?

Is it necessary to enclose code in the following: window.addEventListener('load', () => {}) If your scripts are already loaded at the end of the body tag? Wouldn't this ensure that the DOM has been fully loaded, rendering a load event li ...

What steps can I take to ensure the proper formatting of the `select` input on Mac OS?

How can I maintain consistent formatting for my form across different operating systems? Currently, the form looks good on Windows, but I want to ensure that the select input appears consistently on Mac OS, iOS, and Android devices as well. The image bel ...

Conceal the navigation bar as the user scrolls, allowing it to disappear naturally instead of using animation

When it comes to hiding the navbar while scrolling, simply adding a class with "top: -50px" may seem like an easy solution. However, it doesn't provide a very natural experience. It would be much more seamless if the navbar disappeared as you scroll, ...

Automatically Click after Appending Data using Jquery

After writing this code on document ready, it's still not working. $('body').append('<a id="lnkHidden" href="http://www.google.com.tr" target="_blank">Go To Google</a>'); $('#lnkHidden').trigger('click&a ...

Selenium and C#: Issue with ExecuteAsyncScript command

Trying to execute JavaScript using Selenium Driver but encountering an exception stating that the input string is in an incorrect format. The provided path contains the necessary JavaScript function, which is essentially an onclick without parameters, re ...