Once it hits the fourth tab, it must not cycle back to the first one

  • Hi there, I'm new to JavaScript
  • I noticed that when I click the left and right arrows, the tabs circle back to the beginning
  • However, I would like the circle to stop. When it reaches the fourth tab, it should not go back to the first.
  • This should also apply for the left arrow.
  • Here is my code snippet:

Check out my code on CodePen

 function move(to) {
    var current = $('li.current').index();
    var total = $('.tabs .tab-link').length;
    var add;
    switch (to) {
      case 'left':
        add = -1;
        break;
      case 'right':
        add = 1;
        break;
    }
    $('.tabs li.tab-link').eq((current+add)%total).click();
  }

Answer №1

Here's the revised code snippet:

function move(to) {
  var current = $('li.current').index();
  var total = $('.tabs .tab-link').length;

  var add;
  switch (to) {
    case 'left':
      current > 0 ? add = -1 : add = 0;   // No decrement if already at leftmost tab
      break;
    case 'right':
      add = 1;
      break;
  }
  $('.tabs li.tab-link').eq((current+add)).click();   // Index doesn't wrap back to 0
}
  • In case 'left':, I added a condition to avoid further decrements when on the leftmost tab (index 0).
  • I removed the modulus (%) operator in
    $('.tabs li.tab-link').eq((current+add)).click();
    to prevent the index from wrapping back to 0 after clicking the right arrow with the rightmost tab active.

Answer №2

I implemented a solution in your function to stop execution early if the end tab is reached:

if (to === 'right' && current === (total - 1)) {
  return;
} else if(to === 'left' && current === 0) {
  return;
}

To see it in action, check out this working example: https://codepen.io/anon/pen/RZeNWq?editors=0001

On another note, I recommend considering the broader context when selecting DOM elements. For instance, in your code snippet:

var current = $('li.current').index();

An li element with the class current is quite general - if there happens to be an unrelated li tag with the same class elsewhere on your page, it could cause issues. What if you had a navigation bar where menu items also used the class current? Or if your page featured two sets of tabs, this code wouldn't accommodate that.

A more resilient approach would be something like:

var current = $('.tab-link.current').index();

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

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

Learn how to seamlessly update broken images on a webpage with a placeholder error image using the MooTools 1.2 framework

Currently working on a project with PHP, MySQL and utilizing Mootools 1.2 as the JavaScript framework. I am trying to find a way for all broken images to automatically be replaced with a designated error image. Any suggestions on how I can achieve this? ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

What could be the reason for my CSS selector with :target not functioning properly?

I tried to implement the instructions I found online for using :target, but it's not working as expected. My goal is to change the background color and font color of #div1 when the first link is clicked, and to change the border of #div2 when the seco ...

Creating an interactive draggable box with jQuery-UI is as easy as pie

Is it possible to make the innerDropzone div draggable in the following code snippet? div.example { width: 560px; height: 750px; display: block; padding: 10px 20px; color: black; background: rgba(255, 255, 255, 0.4); -webkit-border ...

Transforming the add to cart button into a view button within the product listings: an easy guide

I am currently developing a unique ecommerce website called bookslab.in. To enhance the user experience, I would like to replace the "add to cart" button with a "view details" button when users view the list of available products. Furthermore, when users c ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Utilizing MySql in HTML Buttons Using PHP

PHP $con=mysqli_connect("localhost","root","","mmogezgini"); $menuler = mysqli_query($con,"SELECT * FROM menuler"); while($menu = mysqli_fetch_array($menuler)) { echo "<button class=\"ust_link\" onClick=\"window.location.href ...

The Material UI slider vanishes the moment I drag it towards the initial element

After moving the Material UI Slider to the initial position, it suddenly vanishes. via GIPHY I've spent 5 hours attempting to locate the source of the issue but have not had any success. ...

The Gulp task is not being recognized when I open the project in Visual Studio Code

Whenever I open gulp, I encounter an error related to minifying css and js files using gulp tasks. Despite my efforts to find a solution, the problem remains unresolved. Error Message: assert.js:374 throw err; ^ AssertionError [ERR_ASSERTION]: Task fu ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Adjusting the content of mat-cards to fill in blank spaces

I have encountered an issue with the alignment in a list using mat-card. Here is my current layout: https://i.stack.imgur.com/VKSw4.jpg Here is the desired layout: https://i.stack.imgur.com/8jsiX.jpg The problem arises when the size of content inside a ...

Issues with applying styles to custom components in styled-components

I attempted to customize the inner elements of react-id-swiper using the code below: import Swiper from 'react-id-swiper'; import styled from 'styled-components'; const MySwiper = ({ className, children }) => ( <Swip ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Prevent the layout from shifting with CSS

I am faced with a challenge regarding a grid of images that are dynamically generated on the screen. The number of images in each row of the grid is dependent on the size of the page. While everything functions properly when the page is at a certain size, ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...