What is the best way in JavaScript to target a specific element in a href attribute in order to create Previous and

<li><a href="/chapter-1.html">Ch. 1 - TitleHere</a></li>
<li><a href="/chapter-2.html">Ch. 2 - TitleHere</a></li>
<li><a href="/chapter-3.html">Ch. 3 - TitleHere</a></li>
<li><a href="/chapter-4.html">Ch. 4 - TitleHere</a></li>
<li><a href="/chapter-5.html">Ch. 5 - TitleHere</a></li>

These links lead to various static pages on my website, each identified by a number in the URL.

I am now looking to create buttons that link to the next and previous pages by adjusting the numbers in the URLs accordingly. However, I am struggling to find a way to target these numbers within the href attribute.

For now, I am simply setting up an alert function.

<button type="button" onclick="getURL();">Get Page URL</button>
    
    <script>
      var current = window.location.pathname;
        function getURL() {
        alert(current + 1);
      }
    </script>

Answer №1

Utilize the current URL to your advantage, as you are currently doing.

After obtaining the URL string, split it at the chapter- string. This will result in an array with two strings. The first element contains the full URL up to and including the / character before the chapter-, while the second element includes the number followed by .html. By removing .html from that element, you can extract the number.

To generate the URL when the user clicks the Next button, retrieve the number and if it's less than 5, increment it by 1. Create the desired (relative) URL by combining chapter- + the new n + .html. Then redirect to this URL using window location.

The process for the Previous button is similar, except the condition is that the number must be greater than 1 and then decrease it by 1.

<button type="button" onclick="previous();">Previous</button>
<button type="button" onclick="next();">Next</button>
    
    <script>
      const current = window.location.pathname;
      const twoParts = current.split('chapter-');
      var number = twoParts[1].replace('.html', '');
      function next() {
        if (number < 5) { alert(number); gotoChapter(++number); };
      }
      function previous() {
        if (number > 1) { gotoChapter(--number); }
      }
      function gotoChapter(n) {
          window.location = 'chapter-' + n + '.html';
      }
    </script>

You can also create the previous and next buttons using JS to exclude Next if the number is 5 or Previous if the number is 0.

Answer №2

To implement this functionality, you can utilize the dataset attribute in your HTML code. Simply include each page within your HTML as a dataset, then access this dataset using JavaScript to retrieve the corresponding page when a event is clicked. Subsequently, you can update your current variable by appending the value of the a tags' dataset that has been clicked.

const $li = $('li a')
$li.each(function(index, a){
  const current = window.location.pathname;
  function getURL(event) {
    event.preventDefault();
    alert(current + a.dataset.page);   
  }  
  a.addEventListener('click', getURL);  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li><a data-page="1" href="/chapter-1.html">Ch. 1 - TitleHere</a></li>
<li><a data-page="2" href="/chapter-2.html">Ch. 2 - TitleHere</a></li>
<li><a data-page="3" href="/chapter-3.html">Ch. 3 - TitleHere</a></li>
<li><a data-page="4" href="/chapter-4.html">Ch. 4 - TitleHere</a></li>
<li><a data-page="5" href="/chapter-5.html">Ch. 5 - TitleHere</a></li>

Answer №3

Typically, the common method involves utilizing page IDs on the server side. However, there is an alternative approach that can be implemented:

<button onclick="getURL()"></button>
<script>
// Extract the page number from "/chapter-ThisIsYourPageNumber.html", found between "-" and "."
var current = window.location.pathname;
var start = current.indexOf("-") + 1; //+1 to get the starting index of the page number
var end = current.indexOf(".");
var length = end - start;
var pageNumber = current.substr(start, length);
var nextPageNumber = parseInt(pageNumber) + 1;

function getURL() {
    alert("/chapter-"+nextPageNumber+".html");
}
</script>

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 to incorporate C-style includes in the Firebug or Chrome console?

Similar Question: How to include a javascript file in Chrome console? I'm wondering if there's a way to include a javascript file in the console from any location in my local filesystem. For example, like the C style #include "/path/to/scrip ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

Vertical stacking of Bootstrap cards is a common design practice

Good day everyone! I'm in the midst of a personal project that involves utilizing the bootstrap framework and PHP. My goal is to fetch data from my MySQL database and have it displayed in horizontal rows of 4 individual cards within a bootstrap card e ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

Unable to reference C# class within Javascript file in Unity

I am relatively new to Unity and I'm struggling to pinpoint the cause of this bug. It seems that I have a class of static constants in my project where I store various boolean checks. Additionally, I have implemented a smoothFollow Script in my projec ...

Using HTML and JavaScript to automatically update one input date based on changes made to another

Currently, I am developing an Angular application and encountered a challenge with two date input fields: <div class="col-lg-3"> <div> {{ dataInizioLabel }} </div> <input required type="datetime-local" ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

A bar graph fails to display on d3 visualization

I am struggling with rendering my bar graph using activity tracking data. Even though I believe my data structure is correct, the rects are not being displayed on the graph. Unfortunately, I cannot identify the mistake I might have made. The dataset is ava ...

The text input is malfunctioning in the IE web browser

For my project, I am incorporating AngularJS but encountering an issue with the input type text in IE browsers specifically IE 11 and IE 10. The problem arises when clicking on the input box - while the focus is triggered, the cursor does not appear insid ...

Merge the properties of two class instances deeply

What is the best method for deep merging two instances of ES6 classes similar to lodash? The end result should be an instance of the same class with a deep merge of both instances' properties. ...

Encountering problem with JSON transmission to Controller Action

Currently, I am facing a challenge with sending JSON data to my Controller Action. JQuery function SendData() { debugger; var CardConnection = { ConnectionDetails: [] }; var allConn = jsPlumb.getAllConnections(); var totalCon ...

Acquire user input using AngularJS

Is it possible to retrieve the value of an input text using AngularJS without utilizing a Controller? If so, what approach would achieve this? I have come across some resources discussing similar queries, but they all involve .controller here is one such ...

Identifying absence of search results in jQuery UI auto-complete feature

Despite reading through several posts on the same topic, I am still perplexed as to why this particular code is not functioning correctly. My objective is to identify when the autocomplete feature returns zero results. Here's the snippet of code: $ ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Scaling the ion-spinner to fit your specific needs

In my Ionic application, I am utilizing the ion-spinner. However, I have encountered an issue with resizing the spinner. While custom CSS works well with default spinners, it does not function properly with Bubbles, Circles, and Dots spinners. CSS .spin ...

Integrating information from an API into the Document Object Model

const url = `https://catfact.ninja/fact?max_length=140`; const getFact = () => { return fetch('https://catfact.ninja/fact?max_length=140') .then(res => res.json()) } const createFactDiv = (fact) => { const factContainer = documen ...

Apply a tint to the specified section

I'm looking to add a semi-transparent color overlay to my HTML section, but I'm facing an issue where it doesn't cover the entire section. Here's what I have so far: #main { padding-top: 50px; padding-bottom: 50px; backgr ...

A step-by-step guide on inserting a distinct identifier into a class using JavaScript/jQuery

In a JavaScript scenario, I encountered the following situation: case 'code': var multiline = $(TextArea).hasSelection().indexOf('\n') >= 0; if (multiline) { var ...

Is it possible to delegate jQuery to itself?

My current project is utilizing an older version of the jQuery library (1.4.2) and I am hesitant to update to version 1.7 due to the time it would take to address any bugs that may arise during the transition. As a result, I am in need of a solution that w ...