What could be causing my JavaScript to malfunction after clicking on anchor links?

My website's JavaScript has a bug where clicking the links in the static header causes scrolling to become buggy and unbearable. What can I do to fix this issue? Thank you in advance.

Here is my code:


$(window).load(function(){
    
    $(window).scroll(function() {
        var hT = $('#scroll-to').offset().top,
        hH = $('#scroll-to').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
        
        if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
            $('#static-bar').addClass('view2')
        }
        else {
            $('#static-bar').removeClass('view2');
        }
    });
});
// More JavaScript code here...

Answer №1

Your issue lies in the fact that setting your location.hash causes the page to immediately jump to the hash, which is not the desired behavior. Fortunately, there is a helpful thread discussing how to update the location.hash without causing this jumping effect.

To resolve this problem, simply replace

location.hash = href

with

    if(history.pushState) {
        history.pushState(null, null, href);
    }
    else {
        location.hash = href;
    }

This should solve the issue for you.

Answer №2

The reason for your JS errors can be traced back to these two lines of code:

let href = $(anchors[i]).attr('href');
location.hash = href.slice(href.indexOf('#') + 1);

It seems that the anchor tag directly below the <a href="#home"> does not have an href attribute, causing the JavaScript to fail on the href.slice line.

A quick solution would be to merge the two adjacent anchors together.

Therefore, you should make the following change:

       <a class="link" href="#home"></a>
       <a class="selector"></a>

Change it to:

       <a class="selector link" href="#home"></a>

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

Are there any instances where CSS is overlooking certain HTML elements?

In the following HTML code snippet, the presence of the element with class ChildBar is optional: <div class="Parent"> <div class="ChildFoo"></div> <div class="ChildBar"></div> <!-- May ...

Are the JQuery appended elements exceeding the width of the parent div?

I have an HTML div that is styled using the Bootstrap class span9. <div class="span9"> <div id = "selectedtags" class="well"> </div> <button class="btn" type="button" id="delegatecontent">Generate report</button&g ...

The functionality of Bootstrap's Modal feature seems to be malfunctioning

I'm attempting to test the sample modals for my project, but even the codes from jfiddles are not working for me. When I click the button, it only gives me a dimmed window. I have also tried searching on Google for a solution, but to no avail. Below ...

Unable to adjust the top padding of the navbar to 0 pixels

Having recently started learning HTML and CSS, I am encountering an issue with the padding on my navbar. I am unable to get it to align with the top of the site as there is a persistent space between the navbar and the top. Below is my HTML code: <!do ...

Tips for postponing the initiation of multiple carousels on a single page?

On my webpage, there are several bootstrap 5.3 carousels that I want to start with a delay. The plan is for each carousel to begin at different intervals – the first one after 1 second, the second after 2 seconds, the third after 3 seconds, and so forth. ...

The chosen filter will be displayed in the list of active filters

My website displays various products, and like many other similar sites, I am attempting to implement filters for the search results. One of the filters I have is for colors. I am showcasing color thumbnails, and when a user selects a color thumbnail, the ...

What is the reason for multiple ajax functions being triggered when submitting a form through ajax?

I have a Drupal form with an AJAX submit. Additionally, I have another jQuery $.get function that sends a request every 2 minutes and inserts the response into an HTML element. The form and this JavaScript code are independent of each other, performing sep ...

Next.js production mode prevents CSS from loading properly

Issue Upon building and launching a production build of our application, the CSS fails to load. Inspecting the devtools reveals a multitude of errors and warnings: https://i.sstatic.net/R07q3.png Possible Causes The problems do not occur when running th ...

Attempting to align a FieldSet in the middle of the page

Having trouble aligning a field set within a div. The first two elements are centered right next to each other, but the third one is justified left and I'm struggling to center it within the div. JSP <tr> <th> <span onclick="toggleDiv ...

jquery for quick search

<form method="post" action="search.php"> Commence search: <input id="search" type="text" size="30" > <div id="search_results"></div> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code. ...

Strange Behavior When Floating Right in Chrome

There's a strange issue that I'm facing, only in Chrome. It seems to be adding some extra space on top of an element with float: right, but only when the browser window is resized (you can see how the name then shifts under the header): This pro ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Having trouble with jQuery selecting a specific span class?

I'm attempting to use the (.class) selector to select the span element, but for some reason it's not working as expected. <div class="text-wrap"> <div class="text-list"> <div class="text-suggestion"> <span class="text ...

Issue with page refreshing not functioning on localhost in Rails and AngularJS collaboration

I recently encountered a strange issue while working on my Rails 4.2 + AngularJS 1.5 project. Whenever I attempt to refresh (F5) the main web-page, there's about a 9 out of 10 chance that the refresh doesn't happen correctly. In these cases, all ...

Trouble generating document with Firebase setDoc()

In my current project, I am successfully creating a new user with authentication and then using the generated UID to create a new document. Here is the code snippet: const currentUser = await auth.createUserWithEmailAndPassword(email, pass); consol ...

What is the reason behind individuals choosing to minify assets instead of minifying the HTML

Have you ever wondered why people emphasize the minification of web assets like CSS and JavaScript, yet rarely mention doing the same for markup? It's interesting to note that CSS and JavaScript are often reused across multiple pages, whereas markup i ...

Timeout causes failure in AngularJS jasmine promise testing

I need help testing my login controller, here is the structure of it: describe('LoginController', function() { beforeEach(module('task6')); var $controller, LoginService; beforeEach(inject(function(_$controller_, _LoginSe ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

Exploring the power of Jquery's id selector in Javascript

Recently, I came across a unique approach to using the ID selector in jQuery: $("*[id*=foo]").val() I'm curious about why this method is being used and how it compares to the standard id selector in jQuery. What sets this implementation apart from t ...

Using JQuery to Customize Navigation Menu Targeting

On my website, I am trying to make an href button and a menu fade in as the page loads. However, I am struggling to find the correct code due to its placement within multiple tags, especially since I am new to JS and JQuery. I have provided a fiddle with a ...