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

Request made to Ajax fetching complete webpage content

I have a page full of random tips at http://www.javaexperience.com/tips To display these tips on other pages of the website, I am using an ajax call to add the content returned by the call to a specific div's HTML. The code for the div is: <div ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

Struggling with showcasing Trips in my React Native project and looking for guidance on the best approach to implement it beautifully

API: app.get('/trip', async (req, res) => { try { const employeeId = req.query.user; const empId = new ObjectID(employeeId); // Retrieving Fleet associated with the driver's ID const fleet = await Fleet.findOne({ a ...

When hovering, apply style 1 to all elements with the same id, and style 2 to the hovered element

I'm working with some user-generated divs that I want to dynamically highlight when hovered over, while simultaneously blurring the other divs. My challenge is figuring out how to change the style of the hovered div separately from all the others. Th ...

The Angular factory function was unable to be initialized

I recently started learning how to integrate Angularjs with ROR using this helpful tutorial While working on adding a new function to retrieve all posts from the database, I encountered a problem. The page no longer loads when I run the code and the HTML ...

Click on the radio button to delete all selected entries in the option dropdown

After spending the entire day trying to find a solution, I am still struggling with a simple task - how do I clear all selections from a group of select option drop downs at once without removing them? I want the selections to revert back to their default ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

Clicking on links will open them in a separate tab, ensuring that only the new tab

Is there a way to open a new tab or popup window, and have it update the existing tab or window whenever the original source link is clicked again? The current behavior of continuously opening new tabs isn't what I was hoping for. ...

Adding vibrant colors to the expansion panel within Material UI to enhance its visual appeal

How can I customize the color of the expansion panel in material ui when it is open? Is there a way to override this in material ui? Feel free to check out the code example at this link ...

Sending Objects Array in POSTMAN using Hapijs: A Step-by-Step Guide

Could you please assist me on how to send a POST request in POSTMAN for the given array of objects and then validate it using Joi in a hapi server? var payload = [{ name: 'TEST Name 1', answer: 'TEST Answer 1', category: &a ...

Utilizing ReactJS onBlur event for email field validation

Currently, I am using a MaterialUI Textfield for email input validation upon leaving the field. To achieve this, I have implemented a function triggered when the onBlur event occurs. My intention is to display an error message using helpertext. Here' ...

Can two controllers be used for the main-app and sub-app with the same URL using angular ui-route?

I have implemented two controllers, 'BaseController' and 'SubController', for my main application and sub-application. Both controllers are configured to point to an empty URL. Below is the configuration for the main application:- ang ...

Using jQuery in CodeIgniter for form validation and AJAX form submission is an effective way to ensure

Whenever I submit the form, errors show perfectly. However, when I submit it again, the data enters the database but the else condition does not work as expected. I want to hide the form and display a success message. The first time, an error response occ ...

Changing Float Attributes to String in Google Earth Engine

I am trying to export data from Google Earth Engine to my Google Drive. To name the file, I am using information from its data properties which results in 2019.0_1.0. However, I would like the file name to be in a different format - '2019_1'. Bel ...

Creating a smooth sliding textarea in HTML

I am working on creating an HTML table with numerous text input areas (textarea) that expand downwards when clicked. Currently, the textarea element expands properly but disrupts the layout of the table. My goal is to achieve a design like this Instead o ...

Using Node.js to convert a file name to a timestamp

I need to change a filename into a timestamp in my Laravel application. let test = "/2020-05-16_11-17-47_UTC_1.jpg" I attempted using split and join to replace the -, but I don't believe it's the most efficient method. The desired output should ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...

How can we show a varying number of textfields based on user selection using hooks and updating values dynamically through onChange events?

Currently, I am in the process of setting up a form that includes a Material UI select field ranging from 1 to 50. My challenge is how to dynamically display multiple textfields for "First Name and Last Name" using Hooks each time the user selects a number ...

Accessing data from a Vue component externally

Utilizing Vue loaded from a script (not a CLI) in a file named admin.js, I have multiple components that interact with each other by emitting events. No Vuex is used in this setup. Additionally, there is another file called socket which creates a websocket ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...