Applying a class in jQuery to an element when the data attribute aligns with the current slide in Slick

I need to compare the data-group attribute of the current slide to the equivalent attribute in a navigation list. If they match, the anchor element in the navigation list should be given an active class.

How can I achieve this using jQuery?

Navigation List HTML

<nav class="timeline__nav">
  <ul>
    <li class="item">
      <a href="#" data-group="group1">1984 to 1988</a>
    </li>
    ... (omitted for brevity)
  </ul>
</nav>

Timeline Slider HTML

<div class="timeline__slider">
  <div class="slick-slide slick-current slick-active">
    <!--Timeline item-->
    <div class="timeline__item" data-group="group1">
    </div>
    ... (omitted for brevity)
</div>

Unsuccessful jQuery Attempt

$('.timeline__slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {
  $('.slick-current .timeline__item').each(function() {
    if ($(this).attr('data-group') == $('.timeline__nav a').attr('data-group')) {
      $('.timeline__nav a').addClass('foobar');
    }
  });
});

$('.timeline__slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {
  if ( $('.slick-current .timeline__item').attr('data-group') == $('.timeline__nav a').attr('data-group') ) {
    // Add active class to .timeline__nav a element
    // Update when data-group changes
    $('.timeline__nav a').addClass('foobar');
  }
});

Answer №1

Here is a slight adjustment made to your code snippet:

$('.timeline__slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {
    // Remove foobar class from any anchor elements within .timeline__nav that have the foobar class.
    $('.timeline__nav a.foobar').removeClass('foobar');

    $('.slick-current .timeline__item').each(function() {
        // Add the foobar class to anchor elements within .timeline__nav
        // where the data-group attribute value matches the data-group attribute of the current slide.
        $('.timeline__nav a[data-group="' + $(this).attr('data-group') + '"')
            .addClass('foobar');
    });
});

If desired, you can substitute .slick-current with .slick-active in order to apply the foobar class to all currently visible slides, not just the single selected slide.

Answer №2

Here's a suggestion: Search for all instances of .timeline__item that have the specified data-group attribute and check the length of the result.

$('.timeline__slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {
  let dg = 'data-group="' + $('.timeline__nav a').data("group") + '"';
  let ok = $('.slick-current .timeline__item[' + dg + ']').length>0;
  if (ok) $('.timeline__nav a').addClass('foobar');
});

Answer №3

Simply by utilizing the corresponding index of the current slide in the order they are presented, you can achieve what you need.

const $navLinks =  $('.timeline__nav a')

$('.timeline__slider').on('afterChange', function(event, slick, currentSlide, nextSlide) {

   $navLinks.removeClass('active-slide')
            .eq(currentSlide)
            .addClass('active-slide')
    
});

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

Guide to displaying a component within the Vue instance

I am currently in the process of developing a Nuxt module that will not interfere with the main Nuxt application. My approach involves creating a separate Vue instance and mounting it as a child node under the body element, similar to a child node to the _ ...

Facing an "error: JSON object access not defined" issue? Read on to find

$(document).ready(function() { var output = "<div>"; $.getJSON('https://search-a.akamaihd.net/typeahead/suggest/?solrformat=true&rows=20&callback=noCB&q=*%3A*+AND+schoolid_s%3A1255&defType=edismax&qf=teacherfirstna ...

Unveiling the Secret: Empowering a Span to Secure its Territory Amidst an Adv

I have a comment section header where I want the senders name(s) (on the left) and time (on the right) to align at the top. <div style="float:left;">John Doe, Suzie Q</div><span class="pull-right"> Jan 30 at 10:29 PM</span> On s ...

Looping through Jquery Ajax requests

Currently, I am developing a SQL converter that converts MySQL to MongoDB. The user interface for this converter is being created with the help of Ajax. Ajax is crucial for handling large conversions. Due to the limitations of MySQL select code, the conve ...

What steps can be taken to ensure a function operates even when the mouse is stationary?

$(document).ready(function() { var score = 0; $("body").mousemove(function() { score++; $("#result").val(score); console.log(score); }); }); As I move my mouse, the score keeps increasing. But, I'm wonde ...

Retrieve events triggered by each element

Currently, my research centers around digital marketing and user experience. In order to gather the necessary data for this study, I must collect event logs from all components within a UI to create datasets on usability patterns. In a web interface, such ...

What is the best way to upload a file without finalizing the form submission?

I have been working on a task to upload a file using ajax and php without refreshing the page when submitting. My code seems to be functioning well and alerts a valid message when I use the preg_match function. However, when I include the rest of the valid ...

What is the best way to make JavaScript display the strings in an array as bullet points on different lines?

We were assigned a task in our computer science class to analyze and extend a piece of code provided to us. Here is the given code snippet: <!DOCTYPE html> <html> <head> <title>Example Website</title> </head> <body& ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

"JavaScript: Issue Encountered While Converting Hexadecimal to Decimal

I've been working on a custom function to convert hexadecimal to decimal in my Scratch project: function Hex2Decimal(hex){ var deci = 0; var num = 1; var hexstr = String(hex); hexstr = hexstr.toLowerCase(); var expon = 0; for( ...

Utilizing data attributes over classes for styling in CSS

Programming Languages <span data-bar> ... </span> JavaScript span[data-bar]{ ... } Do you agree with this coding practice? Are there any potential pitfalls? I believe implementing the data- attribute is beneficial when dealing with a large ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...

Can the data from these JSON elements be obtained?

Suppose I have a JSON file with the following structure: { "update" : { "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a6aea2aaaf83a4aea2aaafeda0acae">[email protected]</a>":{ "1234": {"notfication" ...

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

How can an array be concatenated using tabs?

I am currently in the process of integrating with an old system that requires a value to be sent via a GET request as a tab delimited string. I have my data stored in an array, but I am facing difficulty when attempting to properly format it using the join ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

What is the best way to implement Facebook-style friend tagging in a text input field?

Looking to implement a Facebook-style friend tagger feature on a blog post creation application. When a user types the "@" symbol and then starts typing a friend's name from a user table, the application will search for that name and allow the user to ...

Display the Angular UI grid containing data from the textboxes once the information has been submitted

I recently started working on an angularjs application and I am facing some challenges in finding the solution. Any advice or suggestions would be greatly appreciated. My goal is to dynamically display an angular UI-grid based on the text selected in the ...