Enhance your website's user experience with jQuery by implementing smooth scrolling alongside

I have a fixed header at the top of my page. When it scrolls, I want to ensure that it does not cover or hide any of my content, especially the top portion of the section.

 // This code enables smooth scrolling (source: css-tricks)
$('a[href*="#"]:not([href="#"])').click(function() {

    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);

        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});

For example, you can view a screenshot here.

I have made some CSS changes by adding padding and margins, but I am not completely satisfied with the result.

If possible, I would like the height of the fixed header to act as a top offset.

You can see the desired result similar to what I want in this example image.

Answer №1

To adjust the smooth scrolling effect, simply add your header height after scrollTop: target.offset().top. For example, you can modify it like this:

scrollTop: target.offset().top-100
. Remember to determine your header height and set the appropriate offset value.

// Smooth scrolling script from css-tricks

$('a[href*="#"]:not([href="#"])').click(function() {

    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);

        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top-100
            }, 1000);
            return false;
        }
    }
});
.header {
    position: fixed; 
    top:0; 
    left: 0; 
    right: 0; 
    background: #000; 
    height: 40px; 
    padding: 20px 40px;
}
a { 
    color: #fff; 
    float: left; 
    padding: 10px; 
}
.section { 
    height: 400px; 
    background: green; 
}
.section.add { background: red; }
.section.add3 { background: #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div class="header">
    <a href="#section1">scroll</a>
</div>

<div class="section"></div>
<div class="section add" id="section1"></div>
<div class="section add3"></div>

Answer №2

I finally found a solution to my issue by creating a new variable.

var fixedMenu = $('#fixedtopheader').height():

Instead of using scrollTop: target.offset().top - fixedMenu,

Everything is working perfectly now!

Answer №3

If you're looking for some code assistance, I've got you covered! Just follow this link: https://jsfiddle.net/6mujyLw3/. Within the code, each section is separated for easy navigation.

Here's the HTML snippet:

<div class="m1 menu">
<div id="menu-center">
    <ul>
        <li><a class="active" href="#home">Home</a>

        </li>
        <li><a href="#portfolio">Portfolio</a>

        </li>
        <li><a href="#about">About</a>

        </li>
        <li><a href="#contact">Contact</a>

        </li>
    </ul>
</div>
</div>
<div id="home">
  <h1>Home </h1>
</div>
<div id="portfolio">
   <h1>Portfolio</h1>
</div>
<div id="about">
  <h1>About</h1>
</div>
<div id="contact">
 <h1>Contact</h1>
</div>

And here's the accompanying CSS:

//CSS styles go here

Last but not least, the JavaScript functionality:

//JavaScript functions are defined in this part

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

Access a webpage outside of your domain using htaccess and PHP functionality

When a request is made to my website like this: my1stdomain.com/request-1/ my1stdomain.com/any-another-request/ The corresponding web pages should open on: my2nddomain.com/folder/request-1.php my2nddomain.com/folder/any-another-request.php To achie ...

Adjusting Font Size for Buttons on Mobile Devices in HTML

I am currently working on a website that I want to ensure is mobile-friendly. When testing it on my phone and in Chrome's device mode, I noticed that the majority of the text on the screen was displayed at an easily readable size without needing to zo ...

Disabling and enabling a link before and after an AJAX call using jQuery

I have been trying to disable a link before making an ajax call and then re-enable it right after receiving the response. However, my current approach doesn't seem to be working as expected: jQuery(this).prop('disabled', false); Here is my ...

retrieving an HTML webpage using an AJAX jQuery request

After deploying my application to the production server, I encountered an error with the AJAX jQuery calling my webmethod. It is working fine in the development environment but throwing the following error on the production server: < !DOCTYPE html PUBL ...

Check for compatibility of overflow:scroll with mobile browsers

Is there an easy JavaScript method that works across different devices and libraries? I am looking to assign a class to the html element in order to enable scrollable containers on mobile devices when needed. I want to follow a similar approach to Modern ...

Variable assigned by Ajax no longer accessible post-assignment

Recently, I've written a script to fetch data from a SQL database and now I'm in the process of creating a JS wrapper for it. Utilizing certain functions, I call the script and extract information from the DB as soon as it becomes available. var ...

Tips for focusing on a background image without being distracted by its child elements

I am trying to create a zoom effect on the background-image with an animation but I am encountering issues where all child elements are also animated and zoomed. When hovering over the element, I want only the background part to be animated and zoomed, and ...

Learn how to set up webpack or Next.js to generate a CSS file from custom Material styles and automatically inject it into the header

One of the things I've done is define some custom material styles, like this: import {createStyles, makeStyles, Theme} from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => createStyles({ fab ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

Ways to limit access to the jQuery AJAX method from the browser console window

Looking for ways to prevent unauthorized access through the browser console to manipulate the jQuery ajax method. The issue at hand is that anyone can easily access the console and execute a script to repeatedly make requests, causing potential security r ...

Revealing elements with AngularJS ng-show directive prior to concealing them

Currently, I am in the process of implementing a slide effect for bootstrap badges to showcase hierarchical data relationships using AngularJS. My goal is to have a slider-effect that smoothly reveals new sub-categories while concealing previously open su ...

What is the solution to incorporating a scrollbar in a popup when I increase the zoom level?

When trying to add a scrollbar to the popup, I am facing an issue where the scrollbar does not appear when zoomed in to 75% or 100%. It works fine for fit screen but not on zoom. Can anyone help me identify what is wrong with my code and suggest how to han ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Discover how to prevent a link or text from appearing if a user has already browsed a particular webpage

Is there a way to hide a link to another page if the user has previously visited that page? For example, I have 3 options - A, B, and C. If a user selects option A, links to pages B and C are displayed at the bottom of the page. However, if they then navi ...

The setInterval() function within a jQuery dialog continues running even after being destroyed or removed

I'm facing an issue with a jQuery dialog that loads an external page and runs a setInterval() function querying the server continuously every second via AJAX. The problem arises when I close the dialog, as the setInterval keeps running. Below is the ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...

Combine the filter and orderBy components in AngularJS ng-options for a customized select dropdown menu

I am facing a challenge with my AngularJS dropdown that uses ng-options. I want to apply both the filter and orderBy components together in the ng-options section. The filter for the select is functioning correctly, but it seems like the OrderBy component ...

Incorporating jquery-ui in a Rails application does not lead to an error even with a fictional alias

I'm currently working on integrating the jquery-ui-rails gem into my rails application. The app is based on Spree version 3.0. $ bundle list | grep jq * jquery-rails (4.0.5) * jquery-ui-rails (5.0.5) Despite attempting various solutions in the a ...