Change the information displayed on buttons when clicked and provide options for users to navigate between different

In order to change the content when a button or number is clicked, you can utilize the buttons "1,2,3,4" or the Next and Prev buttons shown in the snippet. Both methods allow access to the same article. If you want to switch between articles using the Next/Prev buttons or the numbered buttons, simply refresh the page first.

$(document).ready(function() {
  $(".btn-hover div").each(function(e) {
    if (e != 0)
      $(this).hide();
  });
  

  $("#next").click(function() {
    if ($(".content5 div:visible,.content6 div:visible").next().length != 0)
      $(".content5 div:visible,.content6 div:visible").next().show().prev().hide();
    else {
      $(".content5 div:visible,.content6 div:visible").hide();
      $(".content5 div:first,.content6 div:first").show();
    }
    return false;
  });

  $("#previous").click(function() {
    if ($(".content5 div:visible,.content6 div:visible").prev().length != 0)
      $(".content5 div:visible,.content6 div:visible").prev().show().next().hide();
    else {
      $(".content5 div:visible,.content6 div:visible").hide();
      $(".content5 div:last,.content6 div:last").show();
    }
    return false;
  });


$('.btn-hover').first().addClass('btn-active');
$('.btn-hover').click(function(){
  var $this = $(this);
  $siblings = $this.parent().children(),
  position = $siblings.index($this);
  console.log (position);
  
  $('.content5 div').removeClass('btn-active').eq(position).addClass('btn-active');
  $('.content6 div').removeClass('btn-active').eq(position).addClass('btn-active');
  $siblings.removeClass('btn-active');
  $this.addClass('btn-active');
});
});
<!doctype html>
<html lang="en">

<head>
</head>

<body>
  <!--Navbar-->
  <div id="section1-the-timeline" class="scrollNav">
    <div class="container-fluid section section_bg_grey">
      <div class="col">
        <div Class="button-wrap timeline  px-5">
          <a href="#section2-the-timeline" class="btn-hover">1</a>
          <a href="#section2-the-timeline" class="btn-hover">2</a>
          <a href="#section2-the-timeline" class="btn-hover">3</a>
        </div>
      </div>
    </div>
  </div>

  <div id="section2-the-timeline" class="section section_secondary_bg">
    <div class="container-fluid">
      <div class="row d-flex align-items-center">
        <div class="col-md-7">
          <div class="text-center section_content">
            <div id="content5" class="content5 pb-4">
              <div class="btn-content-1 btn-active">
                <p>1</p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet provident accusamus itaque suscipit adipisci</p>
              </div>
              <div class="btn-content-2">
                <p>2</p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet provident accusamus itaque suscipit adipisci ullam reiciendis beatae perspiciatis impedit quam nemo asperiores, deserunt, distinctio</p>
              </div>
              <div class="btn-content-3">
                <p>3</p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet provident accusamus itaque suscipit adipisci</p>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-5 img_wrapper">
          <div id="content6" class="content6">
            <div class="btn-content-1 btn-active"><img src="https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png"></div>
            <div class="btn-content-2"><img src="https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png"></div>
            <div class="btn-content-3"><img src="https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png"></div>
           
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="chevron">
    <div class="d-flex justify-content-center middle-chevron">
      <button id="previous" class="btn btn-chevron"><i class="fas fa-chevron-left"></i></button>
      <button id="next" class="btn btn-chevron"><i class="fas fa-chevron-right"></i></button>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  
  <script src="js/animation.js"></script>
</body>

</html>

Answer №1

  • Make sure to assign a specific ID to the element representing your pages
  • Add a DIV with data-tabs-pagination where desired in the document
  • Add a DIV with data-tabs-navigation wherever it's needed
<div data-tabs-pagination="#someElement"><!-- This will be filled by JavaScript --></div>

<div id="someElement" class="css-pages"&gт;
    <div>Page 1 Lorem</div>
    <div>Page 2 Ipsum</div>
    <div>Page 3 Dolor</div>
</div>

<div data-tabs-navigation="#someElement"><!-- This will be filled by JavaScript --></div>

It's important that the data-tabs-* attribute matches the target element ID selector for proper control.

An example of using this script could look like:

// Example:
const myTabs = new Tabs("#someElement", {
  page: 1, // Start from second page (Page index 1),
  btnPrev: {innerHTML: "&larr;", className: "btn"},
  btnNext: {innerHTML: "&rarr;", className: "btn"},
  onChange() {
    console.log(this);
  }
});

// Additional functions you can use:
myTabs.show(0);           // Display page at index (First page = 0)
myTabs.next();            // Move to next page
myTabs.prev(2);           // Go back two pages
myTabs.next().next();     // Progress forward two pages (via method chaining)
console.log(myTabs.page); // Get current page index

By following this structure, you can incorporate multiple tabs or slideshows within one document utilizing the same script:

class Tabs {
  constructor(selector, options = {}) {
    Object.assign(
      this, {
        EL: document.querySelector(selector),
        page: 0,
        selector,
        btnTabs: {},
        btnPrev: {},
        btnNext: {},
        classActive: "is-active",
        onChange: () => {},
      },
      options
    );
    this.EL_pages = this.EL.children;
    this.EL_pagination = document.querySelectorAll(`[data-tabs-pagination="${this.selector}"]`);
    this.EL_navigation = document.querySelectorAll(`[data-tabs-navigation="${this.selector}"]`);
    this.total = this.EL_pages.length;
    this.EL_prev = this._ELNew("button", {
      type: "button",
      textContent: "Prev",
      onclick: () => this.prev(),
      ...this.btnPrev,
    });
    this.EL_next = this._ELNew("button", {
      type: "button",
      textContent: "Next",
      onclick: () => this.next(),
      ...this.btnNext,
    });
    this.EL_buttons = Array.from(Array(this.total)).reduce((arr, _, i) => {
      const EL_btn = this._ELNew("button", {
        type: "button",
        textContent: i + 1,
        onclick: () => (this._page = i),
        ...this.btnPagination,
      });
      arr.push(EL_btn);
      return arr;
    }, []);
    this._init();
  }

  _ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});

  _mod = (n) => ((n % this.total) + this.total) % this.total;

  _init() {
    this.EL_pagination.forEach((EL) => EL.append(...this.EL_buttons));
    this.EL_navigation.forEach((EL) => EL.append(this.EL_prev, this.EL_next));

    this._page = this.page;
  }

  prev(n = 1) {
    this._page -= n;
    return this;
  }

  next(n = 1) {
    this._page += n;
    return this;
  }

  show(idx) {
    this._page = idx;
    return this;
  }

  set _page(n) {
    this.page = this._mod(n);
    [...this.EL_pages, ...this.EL_buttons].forEach((EL) => EL.classList.remove(this.classActive));
    [this.EL_pages[this.page], this.EL_buttons[this.page]].forEach((EL) => EL.classList.add(this.classActive));
    this.onChange.call(this);
  }

  get _page() {
    return this.page;
  }
}


const mySectionTabs = new Tabs("#section-a", {
  onChange() {
    console.clear();
    console.log(`Current page index: ${this.page}`);
  }
});
/*
  The actual CSS styling is customizable based on your needs.
  Just remember JS applies ".is-active" to both:
  - the currently displayed page / slide
  - the current pagination button
*/

.css-pages > div {
  display: none;
}

.css-pages > div.is-active {
  display: block;
}

[data-tabs-pagination] > button.is-active {
  color: #0bf;
}
<div data-tabs-pagination="#section-a"></div>
<div id="section-a" class="css-pages">
  <div>Page 1 Lorem</div>
  <div>Page 2 Ipsum</div>
  <div>Page 3 Dolor</div>
</div>
<div data-tabs-navigation="#section-a"></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

How can one extract information from an ASP.NET MVC on a separate webpage?

Experimenting with ASP.NET MVC for the first time here, so bear with me if this comes across as textbook-like. A basic content management system has been developed using ASP.NET MVC. The URL to retrieve a list of content, specifically announcements, looks ...

Incorrect input

Let's consider this scenario: We have a workspace website similar to Google Drive. (Remember that) There is a Delete .icon on my files list to delete a file. When I request the delete file WebMethod using Ajax, I also want to retrieve the updated ...

Utilizing Codeigniter for transmitting JSON data to a script file

When querying the database in my model, I use the following function: function graphRate($userid, $courseid){ $query = $this->db->get('tblGraph'); return $query->result(); } The data retrieved by my model is then encoded in ...

The VueRouter is unresponsive and not functioning as expected

I have been delving into Vue. Through the npm install vue-router command, I added vue-router to my project. Subsequently, I incorporated VueRouter and defined my URL paths within the VueRouter instances located in the main.js file. I created an About compo ...

Mixing CSS layers

Applying this particular css: .addProblemClass{ width:300px; height:300px; /*width:25%; height:40%;*/ border:solid 1px #000000; margin: 5px; background-color:#FFFFFF; padding:5px; opacity:0.9;/*For chrome and mozilla*/ ...

Is there a way to make the header reach the full width of the page?

Is there a way to make my header extend across the entire page? I attempted using margin-left and right, but it didn't yield the desired outcome. Header.css .header{ background: green; height: 70px; width: 100%; display: flex; ju ...

What is the best way to include temporary attributes on a mongoose object solely for the purpose of a response, without saving them to the database

I am looking to add extra temporary properties with additional data to the response but have encountered some difficulties. 'use strict'; var mongoose = require('mongoose'); var express = require('express'); var app = expres ...

Can you list out the directives that are responsible for generating child scopes in AngularJS?

I recently discovered that when using ng-if, it actually creates a child scope, leading to some confusion on my end. I'm curious about the reasons or benefits behind ng-if's scope creation. Can you also tell me which other built-in directives cre ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

Is it possible to disable the "super must be called before accessing this keyword" rule in babelify?

My current setup involves using babelify 7.2.0 with Gulp, but I've encountered an error when working with the following code snippet: class One {} class Two extends One { constructor() { this.name = 'John'; } } The issue at hand i ...

Switching the mouse cursor when the mousedown event occurs

I'm trying to implement a feature where holding down the mouse will change the cursor to an image, and when releasing the mouse it should revert back to its default. However, the code I have isn't working properly - you have to right click then l ...

Manipulating text alignment and positioning in CSS

Can someone help me achieve this CSS result? img1 This is what I have so far: img2 I'm struggling to center the elements and add a line in CSS. Any advice? I thought about using margin: auto, but I'm not sure if that's the best approach ...

Prevent the Append button from being clicked when a duplicate entry is detected in jQuery

Hi there! I'm currently in the process of learning jQuery coding. Could anyone advise me on how to disable an entry or trigger an alert if it duplicates another APPENDED row? Below is the script I use for appending rows: var rowCount = 1; $('# ...

Encoding data using Angular

I have encountered a situation where my code needs to retrieve table numbers using Javascript and PHP as the database connector. However, when the code works successfully, it displays both the parameter name and value, but I only need the value. How can I ...

Is it possible to refresh the Dictionary using data from localStorage?

I attempted to retrieve all key/value pairs from the localStorage and use them to update my dictionary named keywordDict in the following manner: $(document).ready(function() { var store = allStorage(); console.log(store); $.ajax({ url: '/m ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

Can you identify any issues with this Basic authentication code for an HTTP-Get request?

My setup consists of node.js restify as the backend for running a REST API server, and angularjs as the front-end for making HTTP GET calls. The REST server is configured with HTTP Basic Authentication using the username foo and password bar. To confirm t ...

Is it possible to design and implement Materialize CSS inputs without relying on Materialize CSS?'

Is there a method to implement Materialize CSS input elements that include placeholders and icons without directly using the Materialize CSS framework? I prefer not to mix frameworks in order to avoid potential conflicts, as I am already utilizing anothe ...

Static Header - Halts Animation on Downward Scroll, Resumes when Scrolling Ceases

I've implemented a fixed menu on my website. Everything seems to be working fine, but here's the issue: When I scroll down and the fixed menu starts animating, if I continue scrolling quickly, the animation pauses. It only continues when I stop ...