Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list. Any help would be greatly appreciated!

var Lst;

function changecolor(obj) {
  if (Lst) Lst.style.color = "#663399";
  obj.style.color = "red";
  Lst = obj;
}

<!--shows hyperlink and targets iframe-->
(function() {
  $('.menu a.nav-tab').on('click', function() {
    var href = $(this).attr('href');

    $('iframe').attr('src', href);
    $('.current-url').empty().append($('<a>').attr('href', href).append('"' + href + '"'));

    $('.menu a.nav-tab').removeClass('current');
    $(this).addClass('current');
    return false;
  });
})();
* {

  font-family: Helvetica, Arial, sans-serif;

  font-size: 12px;

}

a:link {

  text-decoration: none;

}

a:visited {

  text-decoration: none;

}

a:hover {

  text-decoration: underline;

}

a:active {

  text-decoration: underline;

}

iframe {

  width: 200px;

  height: 100%;

}

.hyperlinks {

  height: 25px;

  width: 250px;

  position: absolute;

  left: 265px;

  top: -4px;

  background: #ffffff;

}

.current-url {

  text-overflow: ellipsis;

  width: 250px;

  height: 15px;

  overflow: hidden;

  white-space: nowrap;

  padding-bottom: 3px;

  background: #ffffff;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="cycle_menu">
  <p>Previous</p>
  <p>Next</p>
</div>
<br>
<div class="hyperlinks">
  <p class="current-url"></p>

</div>

<div class="menu">
<!-- repeated menu link items here -->
  <a class="nav-tab tab1" href="http://www.dictionary.com" onclick="changecolor(this)">Menu item</a>
  <br/>
  <br/>

</div>

<iframe width="100%" frameborder="1"></iframe>

Answer №1

To make it easier, consider adding classes to your back and forward buttons, such as back and next. This will simplify setting an onClick event handler in your function:

 $('.back').on('click', function() {
    // Find the currently selected menu item and select the previous one
 }

You also need a function to determine which menu item is currently selected:

function getPosition() {
  var parent = document.getElementsByClassName("menu")[0];
  var children = parent.getElementsByClassName("nav-tab");

  var pos = 0;

  for (var i = 0; i < children.length; i++) {
        if (children[i].classList.contains('current')) {
          pos = i;
          break;
        }
    }
  return pos;
}

Create another function that removes the current class from all nav-tabs and sets it on the specified index:

$('.menu>.nav-tab').removeClass('current');

Then,

$('.menu>.nav-tab').each(function(pos, element) {
    if (pos == index) {
        $(element).addClass('current');
    }
});

Using the getPosition() function in your onClick() handlers and adjusting the index accordingly allows you to call the last function successfully.

If you are looking for similar examples, check out this recent question with a working jsbin link: javascript using a loop to change the display of every element that has a specific class

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

Tips for displaying the data on top of individual column bars: Hightcharts, Vue-chartkick, and Cube Js

Looking for assistance with adding value labels to the top of each column bar in a Vue chart using chartkick and highcharts. https://i.sstatic.net/c4Bwc.jpg Check out the image above to see my current output. <template> <column-chart lable= ...

The posenet TensorFlow model results in Node.js do not contain any position detail for coordinates "x" and "y"

I executed the posenet model on node v8.11.0. Below is the code snippet that I utilized. Unfortunately, the output results are not displaying the position of each pose; instead, it simply shows [Object]. It seems like there might be a canvas-related issue. ...

The 'props.p' navigation in react-native is undefined

I have gone through various forums and discussions regarding this issue, but none of the solutions seem to work for me. For some reason, I am facing difficulties passing props to react-navigation when I attempt to navigate, resulting in the following erro ...

How to Save Information to MySQL Database Using an HTML Form with Checkboxes

I recently set up an HTML form that includes checkboxes and successfully managed to store the values using an array in my database. After adding a name field to the form along with a corresponding column in my MySQL table, I hit a roadblock. The new name ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

Iterating through a series of AJAX requests in JavaScript until the variable equals "No" and then terminating the loop

After dedicating the past two days to my work, I am still struggling to find a solution. Any assistance would be greatly appreciated. My current setup involves nodejs and Vue. I need help figuring out how to break out of an AJAX call when receiving a "No" ...

Tips for successfully integrating jQuery UI datepicker in a form loaded through an ajax request

Having a calendar page with links that load forms using ajax into bootstrap popovers for each day. The loaded form includes start and end date fields, to which jQuery binds datepicker as follows: $( ".datepicker" ).datepicker({ changeMonth: true, chan ...

Steps for triggering a function when the 'Enter' key is pressed in a TextInput in a React Native application

I'm currently working on creating a Search Bar feature. I would like the user to input text into the TextInput field, and when they press 'Enter', I want it to trigger my function. <TextInput //when the user presses Enter, call the functi ...

Could it be that grid-area does not function properly with the attr function, or is this intentional?

The following examples showcase the functionality: It's impressive how I'm utilizing content: attr(class) to streamline the labeling process. Impressive! section { outline: 1px solid red; display: grid; grid-gap: 10px; grid-template-a ...

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...

Having trouble displaying image using absolute path in Express

Currently, I am developing a NodeJS application and have encountered an issue with a div element that has a background-image set in an external CSS file. Surprisingly, the CSS file functions perfectly when tested independently, and the background image dis ...

What is the significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...

Display item upon hovering and for an extended period upon clicking using jQuery

I am looking to create a functionality where hovering over an area displays item 2 for a certain duration, which is currently working fine with the existing code. However, I also want it to remain visible for a longer period if clicked, but this does not ...

Enhancing User Experience with Bootstrap V5 Form Validation and Sweetalert2: Displaying a Message of Success Upon Successful Submission

I am currently working on implementing a simple form using Bootstrap 5 that includes validation. My goal is to display an alert message when the form field is successfully submitted using Sweetalert2. Below is the code I have: HTML <form action=&q ...

Discover the simple steps to integrate a timezone dropdown feature into your WordPress website using the Contact Form 7 plugin

I am designing a website and I need to implement a query form with a customizable time zone selection. Are there any specific steps to add a time zone drop-down menu using Contact Form 7? Here is the desired result I'm aiming for: Your assistance wil ...

Steps to utilize a PHP include for displaying HTML content corresponding to the URL file name

I am currently working on a PHP script that utilizes PHP include to insert HTML content based on the filename from the URL. For instance, with the use of PHP include: - if the filename in the URL is dog.html, it will display dog within the HTML document. ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller: public class Controller extends HttpServlet { private Chooser chooser = Chooser.INSTANCE; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExcep ...

How can you position an element at the bottom of a div using CSS?

Could you please assist me in aligning an element to the bottom of a div using CSS? Below is a screenshot of my webpage for reference: http://prntscr.com/5ivlm8 (I have indicated with an arrow where I want the element to be) Here is the code snippet of m ...

transition-duration is ineffective in a particular div

Whenever I hover over the purple text, I want it to increase in size using the zoom property. Here is an example: I am facing two issues: The time duration does not seem to work even when I try to apply it within the hover and non-hover classes. Wh ...