ignore any anchors beyond the second index

I am working with a django-qcm that has dynamic sections triggered by anchors and utilizes the scroll snap type property.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        - styling omitted for brevity -
        </style>
        
        
        <section>
               
            <div id="1" class="container">
                - content removed for simplicity -
            </div>
        
            <div id="2" class="container">
                - content removed for simplicity -
            </div>
        
            <div id="3" class="container">
                - content removed for simplicity -
            </div>
            <div id="4" class="container">
                - content removed for simplicity -
            </div>
        
        </section>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script>
             function scrollToAnchor(ind){
        
        const aTag = $("#"+ind);
        $('body,section').animate({scrollTop: aTag.offset().top},'slow');
    }

    //scrollToAnchor('2');

    var container_page = document.getElementsByClassName('container')
    

    // JavaScript functionality simplified for clarity 

        </script>
</body>
</html>

The functionality behaves as expected up to the second anchor, where it stops working. The scrollToAnchor(3) method functions correctly when executed in the console. Adjustments were attempted to target different DOM parameters related to the container ID but without successful outcomes, only encountering errors.

Answer №1

It appears that the issue lies in retrieving the ID of the .container instead of using the number associated with the clicked .rep.

You can try a solution similar to this:

let x = parseInt($(rep).index()) + 1

Answer №2

If your JS is messy, it's time for a clean up! Check out this tutorial that provides a well-coded solution using both JS and CSS to create an Instagram stories clone component. Get the full guide here.

Answer №3

Below is the solution I used to resolve the issue:

var containerElem = document.getElementsByClassName('container')
 
const repsList = document.getElementsByClassName('rep');
[].forEach.call(repsList, function(rep) {
  $(rep).click(function() {
    if (!rep.querySelector('.check')) {
      [].forEach.call(repsList, function(repToDelete) {
        if (repToDelete.querySelector('.check')) {
          repToDelete.querySelector('.check').remove()
          $(repToDelete).css("border", "1px solid white")
        }
      })
      $(rep).last().append('<div class="check"><object data="{% static "img/Coin-Magpharm-V3.png" %}" width="20" > </object></div>');
      $(rep).css("border", "2.5px solid white");

      var xValue = parseInt($(rep).closest('.container').attr('id'));
      document.getElementById((++xValue).toString()).scrollIntoView({
        behavior: 'smooth' 
      });

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

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Column 1 with fixed headers

Is there a way to make sticky headings in a single column scroll without them overlapping? Currently, my h1s are overlapping when I scroll down. Update: I would like the headings to stack on top of each other as I scroll, instead of being pushed off scree ...

Issue with clicking on Jquery Autocomplete search results link

I am currently implementing the jquery autocomplete feature on my website to retrieve search results from a database. When I start typing in the search box, I receive suggestions. However, when I click on these suggestions, I am unable to redirect to the s ...

Issues with DotNetNuke not Loading jQuery Tabs

The functionality of JQuery tabs and panels seems to be encountering issues in DNN version 08.00.03. Interestingly, it appears to work flawlessly only when a user is logged into the system. Once the user logs out, all the panels and tabs cease to function. ...

Boosting the specificity of Material UI override styles

I came across a question about Material UI Overriding styles with increased specificity that seemed related to my issue, but I couldn't apply the solution to my problem. My problem involves a vertical Slider with marks, and I am trying to remove the ...

browsing through the latest updates and news feed box

I have reviewed these three websites: www.foursquare.com www.untappd.com www.getglue.com The main page features a scrolling down most recent activity box. How can I create something similar to this? Is this achieved through jquery or another method? ...

Why isn't the externally loaded JS file executing properly?

My javascript code functions properly when it's embedded within the HTML file. However, I encounter issues when I try to import it externally. The Google Developer Tools indicate that the file has been loaded successfully, but there seems to be no vis ...

Encountered a NoReverseMatch error during rendering

Encountered NoReverseMatch error while rendering: Reverse for 'accounts.views.new_fn' with arguments '()' and keyword arguments '{'student_pk': *****}' was not found. (The asterisks represent actual numbers, but have ...

The functionality of cropping is not supported within a Bootstrap modal

I have been using ngimgcrop successfully to crop images within my application. However, I encountered an issue when trying to display the cropped images inside a uibmodal (AngularJS modal). Despite trying various solutions, such as using ng-init, I was una ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

"Navigate back with just a click - XSL button

My expertise in this area is limited. After some searching, I couldn't find exactly what I need. Hopefully, the solution is simple. I am currently developing a software control system with a built-in web server. Certain points during navigation requi ...

The Canvas drawn using JavaScript is not being resized and painted correctly on Safari mobile and Firefox mobile browsers

I created an HTML page that features a canvas element where I am drawing a roulette using JavaScript After checking the CanIuse website, I learned that canvas functionality is supported in Firefox 68 and Safari 4 to 13 <!DOCTYPE html> <html> ...

What is the best way to bring a "subdependency" into ES6?

I am dealing with a situation where I have a package called react-router, which relies on another package called path-to-regexp. The challenge is that react-router does not provide its own import of path-to-regexp. So, I am wondering how I can import the e ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

Executing JavaScript code upon clicking a menu item involves creating event listeners for each menu

Currently, I am working on a Squarespace website that includes a navigation bar. I am looking to incorporate a JavaScript code as a link within the navigation bar. The specific JavaScript code is as follows: <div> <script type="text/javascript ...

What is the closest context when using JQuery's on change event?

One of my form fields needs to be changed when the select field is altered. This is how my HTML code looks: <div class="ajx" id="ajx_1"> <fieldset> <legend>Inhalt</legend> <select id="u_article" ...> ...

Enhancing data with Django REST framework through AJAX requests

I'm encountering an issue where attempting to send data from the frontend to the serializer results in a HTTP 400 error. Strangely, when I make the same request directly via the DRF browsable API, it works perfectly fine: Here's my model setup: ...

List of null variables

I'm having trouble grasping the concept of an array filled with empty values like this: let arr=[,,,]; When I attempt to log the length, it shows 3 instead of 4. let arr=[,,,]; console.log('length',arr.length); console.log('arr[1]&a ...

Utilize Android accelerometer data to bring objects to life with animation

Utilizing an Android app, I am streaming accelerometer data to a Python script on my PC. The data is then saved to a text file. My goal is to utilize Javascript and jQuery to animate a 3D CSS cuboid (representing the device) to replicate the movements capt ...

Consistent sizing for Bootstrap thumbnail images

In my current project, I am implementing a Bootstrap thumbnail feature where each thumbnail consists of an image and a heading. However, a problem arose as the images do not have the same size, resulting in thumbnails with varying dimensions. To resolve th ...