Why won't the JavaScript work when linking to a carousel slide from another page?

Trying to follow this 6-year-old guide, but my JavaScript isn't triggering when the URL contains #slide_ - have things changed?

Linking to a specific Bootstrap carousel slide from another page

My code on page 2:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
    
    <!-- Core theme CSS (includes Bootstrap)-->
        <link href="css/styles.css?v20221223=1" rel="stylesheet" />
</head>

<body>

         
<!-- Carousel Wrapper-->

        
<div id="myCarousel" class="carousel carousel-dark slide" data-bs-interval="false" data-ride="carousel" data-pause="hover">
  
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.w3schools.com/bootstrap/chicago.jpg" alt="..." class="d-block img-fluid">
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap/la.jpg" alt="..." class="d-block img-fluid">
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap/ny.jpg" alt="..." class="d-block img-fluid">
    </div>
   </div>
</div>
</div>
<!-- END Carousel Wrapper-->

<!-- Bootstrap core JS - versionas as of Dec 2022-->
        <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d4e4918a978a9489c5c8d4cc">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- JS for loading a particular slide from another page -->
        <script>
            
            function qs(key) {
                key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); 
                var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
                var slide = match && decodeURIComponent(match[1].replace(/\+/g, " "));
                if (Math.floor(slide) == slide && $.isNumeric(slide))
                    return parseInt(slide);
                else
                    return 0; 
                }
            //why is this not working???
            $('#myCarousel').carousel(qs('slide'));
        </script>
    
</body>
</html>

And the link on page 1

<a href="page1.html#slide=2">slide 2</a>

Feeling stuck...

Answer №1

When you provided your example, the JavaScript was added on page 2, yet the link directed the user to page 1. It's crucial to ensure that your URLs are correct. Following your example, the link should be

<a href="page2.html#slide=2">slide 2</a>
on page 1.

Additionally, the function function qs(key) {..} extracts the hash on ?, not on #.

However, achieving what you desire is simple. I have provided a brief example for your reference.

Explanation of the snippet below:

You can achieve the desired functionality without relying on jQuery.

In my demonstration, I introduced a function named getSlideNumber(). This function first checks for the existence of the location hash, retrieves its value, splits it using = to access the slide number, then converts the extracted value into an integer using parseInt(). To safeguard against malicious hashes, I ensured the slide number is indeed an integer by utilizing Number.isInteger().

We invoke this function to obtain the slide number and utilize Bootstrap's method getOrCreateInstance to access the carousel instance on our page and cycle it to the specified slide number using to().

It's really as straightforward as that!

Usage:

Due to limitations in extracting a hash within a snippet, I did not call the function getSlideNumber() in my example. Therefore, make sure to remove the line const slideNumber = 2 and uncomment the line above it when integrating this code into your project. Here's how:

  const slideNumber = getSlideNumber(); 
  const element = document.querySelector('#carouselExample')
  const caroursal = bootstrap.Carousel.getOrCreateInstance(element).to(slideNumber);

Remember, the initial slide of a carousel has an index of 0, aligning with an array structure.

Lastly, feel free to customize the carousel HTML according to your preferences. For my demonstration, I utilized the basic example outlined in the documentation provided byBootstrap.

The code snippet:

... (Rest of the text remains unchanged)

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

Absence of reactions visible

I am eagerly awaiting responses to a message. The member begins typing, then the bot responds, and the user is expected to react to the bot's message. I attempted to execute this code, however, when it reached the console.log("OK"), nothing happened. ...

Include the document when the query results in zero documents

Struggling to figure out how to add a document to a collection if a query returns no results. The current query lacks operators for checking the length or size of the result. How can this be achieved? The query in question: this.monthCollection = this.af ...

display and conceal a division by clicking a hyperlink

How can I make a hidden div become visible when clicking on a specific link without using jQuery? Javascript function show() { var a = document.getElementsByTagName("a"); if (a.id == "link1") { document.getElementByID("content1").style.v ...

Examining an array to identify palindromes

Is there a way to loop through an array and check if each word is a palindrome, instead of manually passing an argument for each word? If a word is a palindrome, return the word; otherwise, return 0. var myArray = ['viicc', 'cecarar', ...

Is it possible to transform all scripts into a React component? (LuckyOrange)

I am currently working on converting the script for a specific service (http://luckyorange.com/) into a component. The instructions say to place it in index.html within the public folder, but that appears to be insecure. I'm uncertain whether this tas ...

Pagination malfunction on AngularJS md-data-table is causing issues

I have been working on a project that involves retrieving data from an API and displaying it in a table. I am using AngularJS and the md-data-table library by Daniel Nagy. Following the setup instructions, I was able to display my data successfully. Howeve ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

What is the best way to achieve this particular grid layout using html and css?

I have a CSS grid of icons and I am trying to create a divider between each cell that fades in opacity towards the edges, similar to an airbrush effect. However, I want the cells themselves to remain transparent so that the background pattern is still visi ...

Methods for removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

The IISNode website displays directory contents instead of launching the server.js file

Having trouble configuring IISNode to automatically serve the main server.js application file for my node application. Currently, when I navigate to http://localhost:80/ where my app is hosted, it just displays the folder contents instead of running the se ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Creating numerous Facebook posts using jQuery technology

I am currently facing a challenge when attempting to publish multiple facebook posts on a webpage using jQuery. Although I have managed to successfully post the first facebook post, I am encountering difficulties when trying to post another one. What coul ...

Looping through an object with AngularJS's ng-repeat

Upon receiving an object as the scope, which has the following structure: https://i.sstatic.net/hiBaw.png The controller function is defined as follows: module.controller('ActiveController', ['$scope','$http', func ...

Tips for extracting title and image from someone else's blog posts to share on your own website

Currently, I am in the process of creating a website where I can showcase my personally curated content. I have been struggling to figure out how to seamlessly integrate this content into my site without relying on an API. My initial idea was to manually ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Is it possible to utilize curly brackets in JavaScript for dividing code segments?

Check out this code snippet. I'm curious if there are any potential drawbacks to using it. //some example code var x = "hello"; { var y = "nice"; function myfunction() { //perform tasks... } } One advantage I see in utilizing t ...