Adjust the position of an anchor tag when clicked with a fixed header

I found a similar question on stackoverflow and was able to derive my solution from there. However, I am facing a slight issue with it.

In my case, I have a small fixed submenu at the top of the page. When I click on an anchor link, I want the scroll position to be adjusted after the submenu.

Here is my code snippet that mostly works:

function offsetSubmenu() {
    if(location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - submenuHeight);
    }
}
$(window).on("hashchange", function () {
    offsetSubmenu();
});
window.setTimeout(function() {
    offsetSubmenu();
}, 1);

The code gets executed when the page loads and whenever the URL hash changes. It functions as expected in those scenarios. The problem arises when the hash remains unchanged. For instance, clicking on the first Hashlink, scrolling around, and then clicking on the same link again causes the browser to jump to the anchor without accounting for the submenu offset.

Using a click listener like $("a").click(..) does not work because it executes before the browser navigates to the anchor element.

Does anyone have any suggestions on how to handle the offset for anchors when the URL hash remains the same?

Answer №1

In the scenario where the $("a").click(...) function is triggered before the browser navigates to the anchor, you can introduce a slight delay to the offsetMenu function in order for it to be called after the jump has occurred. This can be achieved by using a setTimeout function like so:

setTimeout(offsetSubmenu, 1)

This ensures that offsetSubmenu is executed consistently, even after the initial trigger.

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

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...

What is the best way to update a Google Ad Manager ad after a javascript event, such as an ajax postback, has been triggered on a website?

Is there a way to reload an embedded admanager advertisement on a webpage after a user clicks an ajax link, essentially showing them a new page and generating another impression? I'm looking for a solution that doesn't involve placing ads in an ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...

Pass the full path of the Dropzone file to the Rails controller

I'm currently working on extracting the complete file path from a dropped folder in Chrome's Dropzone. All file upload data is being transferred correctly, but I also need to capture the full path of the uploaded file. Despite my efforts, I&apos ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

Using the GetElementByID method to target a textarea element

I attempted to submit form data through TinyMCE, but the script is returning the old value instead of the new one. Here's the form code: <form> <textarea id="tml" name="template_content" class="editor_large">{$template_content|escape ...

data not being transferred successfully to the SQL input from forms

The data from this input form is not being properly transferred to the SQL database when using the sqlAddUser.php file available at pastebin.com/W9BH0D3s. The form includes the following fields: <form action="sqlAddUser.php" method="post"> <div c ...

Confirm Submission Issue in HTML Form

During my testing of the blacklist confirmation dialog, I encountered an issue where clicking the OK button did not submit the form as expected. Instead, it seemed to be stuck in a loop where clicking the button had no effect and the dialog remained on scr ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Attempt to import Recharts into React was unsuccessful

I am currently exploring the use of recharts in a React project, but I am facing difficulties when trying to import components from its library. I have added it to my package.json file as follows: "recharts": "^2.0.9", However, I am ...

Unravel JSON using JavaScript on the web

I encountered an issue while running this code and trying to decode it: var data = JSON.parse({"forms":[{"url":"example.com/example","name":"example"}]}) document.getElementById("name").innerHTML=data.forms.name Instead of the expected value, the returne ...

Enhance the appearance of radio buttons using CSS and incorporate images to create a

Is there an easy and straightforward method to customize radio buttons using only CSS, allowing me to click on an image instead of a traditional bullet point? For example, like thumbs up/thumbs down. I have two radio buttons that need to track which one i ...

How can I design an avatar image within a button similar to Facebook's style?

I'm currently working on a project that involves adding an avatar and a dropdown menu for account settings to my navigation bar. I've already created the dropdown, but I'm having trouble styling the avatar within the button. The button is ta ...

Designing a logo atop a Jquery tab

In the layout I have designed, there is a header followed by a jQuery Tab navigator. The tabs have padding on the left side, and I want the header image to overlap this area. Currently, the image is hidden behind the tab panel. Which CSS property can be us ...

What is the reason for the error message "ReferenceError: categories is not defined" appearing in my AngularJS code?

I don't understand why I am encountering this error and cannot access the data from the Json file, even though $scope.categories is already defined. Can someone help me with this issue? Below is my controller code: (function(){ app.controller(&a ...

Images in the background that adapt to the screen size

Hello, I am a beginner in React and looking for assistance with my home.js code: I am attempting to use an image as a background for my page, but I am struggling to make it adjust to the window size. I have tried using properties like background-repeat: n ...

Difficulty arises when attempting to create JSON using the Array.push() function from the data received via Ajax. The generated JSON is not successfully populating the tbody element

I am facing an issue while populating my tbody with data using the code below: function adaptSelectedBanks(banks) { console.log(banks.length); $(function() { banks.forEach(function (ba) { var c ...

Exploring Attachments in ASP.NET Core MVC Views

I have placed attachments in a Shared Folder on a server. I attempted to access them using the <a> tag <a href="file:///C:">Open Attachments</a> Unfortunately, this method did not work in ASP.NET Core MVC for unknown reasons. I ...

Having an issue with deleting a table row using jQuery when the button is clicked

I am facing an issue where clicking on a button does not delete the table row despite both the tr id and button id having the same value. Can someone please guide me on what might be going wrong? <tr id="<?php echo $result->id;?>"> <t ...