Utilizing Horizontal Navigation to Showcase Content (JavaScript)

I'm using the Flickity CSS library to create a horizontal scrolling navigation bar. I've customized the carousel template so that when a cell is selected, it snaps to the center of the bar. The carousel has 5 cells named 'slide 1', 'slide 2', and so on. My challenge now is figuring out how to show the corresponding content only when its carousel cell is selected – otherwise, the content should be hidden.

 <nav>
 <div class="carousel" data-flickity>

            <div class="carousel-cell">
                <a href="#slide1">
                slide 1
                </a>
            </div>

            <div class="carousel-cell">
                <a href="#slide2">
                slide 2
                </a>
            </div>

            <div class="carousel-cell">
                <a href="#slide3">
                slide 3
                </a>
            </div>        

            <div class="carousel-cell">
                <a href="#slide4">
                slide 4
                </a>
                </div>

            <div class="carousel-cell">
                <a href="#slide5">
                slide 5
                </a>
            </div>    

 </div>
 </nav>    
 <!--Content-->
 <main>
 <div class="container">
          <div id="slide1">
            SLIDE 1
          </div>
          <div id="slide2">
           SLIDE 2
          </div>
          <div id="slide3">
           SLIDE 3
          </div>
          <div id="slide4">
           SLIDE 4
          </div>
          <div id="slide5">
           SLIDE 5
          </div>           
 </div>
 </main>

If you'd like to see my Codepen in action: https://codepen.io/loudenw/pen/jGaxzG

Answer №1

Check out the Flickity events documentation at

For jQuery event namespace, visit https://api.jquery.com/event.namespace/

I incorporated the use of the `select` event in the `flickity` namespace to display the element with an id of `slide` + `currentSelectedSlide + 1`. Keep in mind that script indexes start from 0 while IDs start from 1.

$(document).ready(function() {

  $('.carousel').on('select.flickity', function() {
    var selector = '#slide' + ($('.carousel-cell.is-selected').index()+ 1);
    $('.container').find('div').hide();
    $(selector).fadeIn();
  })

});
main .container {
  width: 100%;
  height: 100px;
  margin-top: 20px;
  background-color: red;
  text-align: center;
}

nav {
  width: 100%;
  height: 30px;
  background-color: #ffffff;
  text-align: center;
}

.hidden {
  display: none;
}

.carousel {
  background-color: #fff;
  width: 60%;
  margin: 0 20% 0 20%;
}

.carousel-cell {
  width: 50%;
  height: 30px;
  margin-right: 10px;
  background: #fff;
  border-radius: 5px;
  counter-increment: gallery-cell;
}

* {
  box-sizing: border-box;
}

.flickity-prev-next-button {
  width: 30px;
  height: 30px;
  background: transparent;
}

.flickity-prev-next-button:hover {
  background: transparent;
}


/* arrow color */

.flickity-prev-next-button .arrow {
  fill: #000;
}

.flickity-prev-next-button.no-svg {
  color: #000;
}

.carousel-cell {
  opacity: 0;
  transition: opacity .4s;
}

.carousel-cell.is-selected {
  opacity: 1;
}

.container>div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://unpkg.com/flickity@2/dist/flickity.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />



<nav>
  <div class="carousel" data-flickity='{"initialIndex": 4, "pageDots": false } '>

    <div class="carousel-cell">
      <a href="#slide1">
                    slide 1
                    </a>
    </div>

    <div class="carousel-cell">
      <a href="#slide2">
                    slide 2
                    </a>
    </div>

    <div class="carousel-cell">
      <a href="#slide3">
                    slide 3
                    </a>
    </div>

    <div class="carousel-cell">
      <a href="#slide4">
                    slide 4
                    </a>
    </div>

    <div class="carousel-cell">
      <a href="#slide5">
                    slide 5
                    </a>
    </div>

  </div>
</nav>
<!--Content-->
<main>
  <div class="container">
    <div id="slide1" class="slide-related-content">
      SLIDE 1 RELATED CONTENT
    </div>
    <div id="slide2" class="slide-related-content">
      SLIDE 2 RELATED CONTENT
    </div>
    <div id="slide3" class="slide-related-content">
      SLIDE 3 RELATED CONTENT
    </div>
    <div id="slide4" class="slide-related-content">
      SLIDE 4 RELATED CONTENT
    </div>
    <div id="slide5" class="slide-related-content">
      SLIDE 5 RELATED CONTENT
    </div>
  </div>
</main>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.js"></script>

According to the documentation, it's recommended to use `$flickity.data('flickity').selectedIndex` instead of the jQuery `index()` method, but in my case, the former didn't work as expected.

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

Personalized radio button tags

Is there a way to ensure that all blocks are uniform in size with a 10px margin between them? Recently, the radio button was swapped out for a radio label, but now there is an issue with inconsistent sizes due to varying word lengths. How can this be res ...

Content overflowing beyond the boundaries of the parent DIV in Internet Explorer 6

Take a look at the code snippet below: <div style="width: 50px; border: 1px solid green;"> <div style="position: absolute;"> add whatever text you'd like </div> </div> The display in modern browsers (such as I ...

Angular modifies the structure of a JSON string

Currently, I am attempting to display data on my screen utilizing AngularJS, ASP.NET, and JSON.NET. I have noticed that when I make a call to $.getJSON, it returns a standard JSONArray. However, when I assign this data to a variable inside my Angular contr ...

Understanding conditional statements in JavaScript can greatly enhance your programming skills

Here's a search component that I've been working on. I'm trying to figure out how to handle the scenario where there are no items in the array. Should I use an if statement or is there another approach I should take? Any help would be greatl ...

Steps to set up a MessageCollector on a direct message channel

Hey everyone, does anyone have any tips on setting up the message.channel.createMessageCollector function for a direct message? I attempted to use message.author.dmChannel.createMessageCollector but it didn't work for me. Any advice? ...

Creating sleek HTML5 applications in the Windows 8 Metro style

Is it possible to develop a metro style Windows 8 HTML5 application without having Windows 8 OS installed? I know how to work on VS2012, but since it's a web application, I don't see the need for Windows 8 OS. Please let me know if it's nece ...

What causes the undefined value of "this" in the Vue Composition API setup function?

A Vue component I've created is using v3's composition API: <template> <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" /> <labe ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

Encountering timeout issues while implementing routes in VueJS

Currently, I am utilizing VueJS to send data to the server and then navigate to another route. I attempted the following code: saveSupportArea: function () { this.toast("success"); var that = this; setTimeout(function(that){ that.$rou ...

Updating textbox values with ajax results in the page refreshing and the newly assigned values being lost

I'm currently working on updating a section of my webpage using AJAX instead of C#, as I don't want the page to refresh. All I need to do is execute a SELECT query to retrieve the current client from the SQL database and populate the correspondin ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Struggling to populate React Components with JS objects only to encounter the error message "Functions cannot be used as React children"?

I'm still getting the hang of React, so please bear with me if this is a simple issue. My goal is to utilize a JavaScript Object: const gameCardData = { "university": { "elemental-wars": { "imgAlt": "Elemental Wars Start Screen", " ...

Enhancing Bootstrap with VueJS for better component ordering

I've been struggling with Vue components in Bootstrap lately. I am attempting to create collapsible Bootstrap content in Vue, and here is the current code: HTML <div class="col-sm main-content" id="main-content"> <p&g ...

What is the best way to display a template after submitting data via AJAX in the Flask framework?

Encountering an issue where I am unable to open render_template after posting data with ajax. Below is my ajax code: if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'neg ...

Function for editing a button in an AngularJS single page application

I am a beginner in AngularJS and I'm currently working on a project to create a single page application for tracking expenses. However, I'm facing some challenges with my code. Although I have successfully implemented most of the functions, I am ...

Looking to create a unique custom popup in your React JavaScript project with the power of HTML5

I attempted to access the following links: http://codepen.io/anon/pen/zxLdgz Unfortunately, they didn't work in: I inserted this code in a jsx file <a href="#openModal">Open Modal</a> <div id="openModal" className="modalDialog"> ...

Utilizing AngularJS to dynamically inject HTML content into $scope

In my possession are the following files: index.html //includes instructions for passing arguments to the btnClick function in app.js <div ng-bind-html="currentDisplay"></div> app.js app.factory('oneFac', function ($http){ var htm ...

Direct back to the current page post deleting entry from mongodb

After removing data from MongoDB, how can I redirect to the same view (handlebar)? I tried using res.render, but it shows that the website cannot be reached. Thank you for your assistance. Controller Logic var express = require('express'); va ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Currently experiencing difficulties while attempting to create a Simon game in JavaScript. Seeking assistance to troubleshoot the issue

var buttonColor = ["red", "blue", "green", "yellow"]; var userClickedPattern = []; var gamePattern = []; var totalKey = []; var level = 0; $("*").on("keydown", function(m) { var key = m.key; totalKey.push(key); var keyLength = totalKey.leng ...