Navigate to a specific section on a different page while excluding a distance of X

I've implemented the script below to execute the action mentioned in the title.

    <script type="text/javascript">
              var jump=function(e)
      {
         if (e){
             e.preventDefault();
             var target = $(this).attr("href");
         }else{
             var target = location.hash;
         }

         $('html,body').animate(
         {
             scrollTop: $(target).offset().top
         },1000,function()
         {
             location.hash = target;
         });

      }

      $('html, body').hide();

      $(document).ready(function()
      {
          $('a[href^=#]').bind("click", jump);

          if (location.hash){
              setTimeout(function(){
                  $('html, body').scrollTop(0).show();
                  jump();
              }, 0);
          }else{
              $('html, body').show();
          }
      });
      </script> 

The functionality works perfectly, but I encounter an issue with my fixed header overlapping the div after scrolling. To address this, I aim to adjust the scroll target by subtracting 80px. How can I update the code to achieve this modification?

You can view a live version of this on

robertkoh.net/Electrotemp/index.html

If you click on 'ducted vacuum systems', it will direct you to the products and services page and scroll to the relevant section. However, you'll notice that the fixed header partially covers the content.

Answer №1

Solution 1: Deduct 80 pixels without resetting location.hash

To achieve this, simply modify the code snippet below:

 $('html,body').animate({
     scrollTop: $(target).offset().top
 }, 1000, function() {
     location.hash = target;
 });

With the following updated code:

 $('html,body').animate({
     scrollTop: $(target).offset().top - 80
 }, 1000);
  • The addition of - 80 subtracts 80 pixels from the scrolling distance.
  • By removing location.hash = target;, you prevent the page from jumping back to its previous position after the animation completes. This behavior was triggered by resetting the hash tag, causing the browser to scroll back up. Note that internal hash links within the site will no longer update the URL bar hash tag.

Solution 2: Place your content in a separate scrollable <div>

  • Create a new <div id="container"> starting after <!--end slideMenu--> and before </body>.
  • Replace $('html,body').animate({ with $('#container').animate({.
  • Remove margin-top: 70px; from the .titlebar style.
  • Apply the following CSS for the #container element:

    #container {
        position: fixed;
        top: 70px;
        bottom: 0;
        left: 0;
        overflow: auto; /* enable scrolling */
    }
    

This approach offers several benefits:

  • No need for the - 80 adjustment.
  • No requirement to remove location.hash = target;.
  • Browsers without JavaScript enabled can still navigate to the correct position smoothly.

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

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Extension for Chrome that enhances YouTube video playback experience

I'm struggling to figure out why this isn't functioning. I've reviewed the Google extension dev docs and examined some sample code. Checked various Stack Overflow questions and answers, but haven't received any helpful feedback or res ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Error: The term "Worker" is undefined in a new Nextjs project

I'm currently looking into an issue where I am attempting to import a webpacked javascript file into a NextJS project that utilizes Worker, but I keep encountering the error message ReferenceError: Worker is not defined. I've simplified it down t ...

New to JavaScript and Bootstrap - eager to learn by using Bootstrap 4 Chart Template, just need help with a small issue in the code

I am eager to dive into Bootstrap 4 and data visualization charts. I want to replicate the visualizations found in the link below. However, after copying and pasting the code into Atom, it's not functioning as expected. I ensured that I copied the HT ...

Refresh the form fields using PHP_SELF after submission

How can I pass a calculated value to another form field using php_self to submit a form on the same page? The $title_insurance field is not getting populated, any suggestions on what might be causing this? <?php if(isset($_POST['submit'])) { ...

Remove movable element from react-dnd

I am working with react-dnd and I am trying to figure out how to remove a draggable object once it has been used. I modified the react-dnd multiple type example by adding a delete feature when an object is dropped. Here is the current behavior: 1. Drag a ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

Integrating DHTMLX Scheduler with Node JS for seamless scheduling solutions

Having diligently followed the DTHMLX Scheduler guide, I've encountered an issue with the db.event.insert() function not working, as the associated route fails to trigger. Interestingly, data from my MongoDB displays correctly when inserted via the sh ...

Establishing a TCP connection to a server using Javascript

Currently, I have developed a server daemon that generates various data, such as messages. However, my main focus is on client monitoring. For instance, I have a webpage and I aim to maintain a constant TCP connection to the server in order to display all ...

Words next to picture

Can someone help me with aligning different images of varying widths but the same height inline with text next to each image? I tried to do it, but it doesn't look good on responsive screens. Any suggestions on how to fix this? And if there's a b ...

What is the best way to reach a link using Selenium?

Challenge : Unable to interact with a link using JavaScript through Selenium. Attempted Solutions: element = driver.find_element_by_css_selector(a {href: "javascript:void(0)"}) resulted in a SyntaxError. element = driver.execute_script("ja ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

A guide on using jQuery to iterate through 3 separate div elements

Seeking assistance with creating a dynamic loop for multiple divs (3 or more) using jQuery. The desired outcome is to have the main image div on the homepage rotate with other divs, changing both the background image and links within each div. I initially ...

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem: For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string. If there are less than k characters remaining, reverse al ...

Flickering effects in THREE.js using Frame Buffer Objects

I've encountered a strange flickering issue while working on a THREE.js scene that involves using a Frame Buffer Object. The flickering disappears when I comment out the line: mesh.material.uniforms.fboData.value = renderTargetA.texture. THREE.FBO ...

Does a Javascript event get triggered when the currentSrc attribute of an <img> element is modified?

Let's imagine we have an image tag like this: <img id="my_tag" src="/default.jpg" srcset="/small.jpg 500w, /medium.jpg 1000w, /large.jpg 2000w"> Upon loading the page, JavaScript can determine which source from t ...