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

How to place a button in SwiperJs using React

Can anyone provide guidance on how to position the navigation buttons in a manner similar to the image below? The desired layout is for the buttons to appear on the outer edges of the swiper component. You can refer to this demo for more information. htt ...

No longer will popups be blocked

I've been trying to work with jQuery to create a popup. But I'm facing an issue where my code is being blocked by Google. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { var flag = true; ...

Rails does not transfer data-attributes in HTML5

I have a layout set up to show users: %table.table %tbody - @users.each do |user| %tr %td= avatar_tag user, {small:true, rounded:true} %td = username user .online-tag = user.online? %td= ...

Using HTML and JavaScript to verify email addresses

I have been working on an "Email Validation" code, but it seems to be malfunctioning. I can't figure out why. Would you mind taking a look at it? Thank you. I suspect that the issue lies with this line document.getElementById("custEmail").onchange = ...

Enhance the size of dynamically generated svg elements by scrolling the mouse wheel in and out

In my ASP.NET application, I have a view page where SVG elements are dynamically generated. Now, I want to implement zoom functionality for all the created SVG elements. Zooming in should occur when scrolling up and zooming out when scrolling down. <sv ...

Troubleshooting: The issue of receiving a 403 error when trying to access

I'm currently using Codeigniter 3 and have encountered an issue with a script. When the code is in my HTML file, everything works perfectly fine. However, if I move the code to an external file, I receive a 403 error. The location of my JavaScript fi ...

Unconventional border effect while hovering over image within navigation container of Bootstrap

Whenever I hover over the image inside the navigation bar, there is a strange white/gray border that appears. It's quite annoying. Does anyone know how to remove this border? Here is the code snippet causing the issue: <ul class ...

The HTML iframe is displaying blank content

I'm trying to embed a webpage within another webpage using an iframe. I attempted to do so with this simple code: <iframe src="http://edition.cnn.com/" id="i_frame"></iframe> JSFIDDLE However, nothing is displaying. Any thoughts on why ...

What is the best way to organize a form's checkboxes into an array using Node.js?

My goal is to design a form with multiple checkboxes where each checkbox has the same name, and only the selected values are submitted with the form. While I know how to achieve this using PHP as demonstrated in this SO question, I am facing difficulty imp ...

Elements within the DIV tag are not displaying in a linear arrangement as intended

I'm having trouble creating a navbar with Bootstrap 4. The items in my div tag are not inline, and I can't align my nav item to the right. Here is the HTML code: <nav class="navbar navbar-inverse "> <div style="display:inline"> ...

problem with the video pathway in the javascript document

I'm currently in the process of putting together a Video gallery playlist using HTML, CSS, and JavaScript. So far, I've set up the html and css files along with two js files. The first js file contains all the video information as shown here: ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

Easily center list item numbers vertically within fixed height containers

I am facing an issue with the alignment of ordered list item numbers in a list with fixed height and vertically centered content. The numbers seem to be positioned inaccurately. li { height: 80px; border: 1px solid black; } li > span { heigh ...

What is the best method to choose a random color for the background when a button is pressed?

Does anyone know how to create a button that changes the background color of a webpage each time it is clicked? I've been having trouble with the javascript function in my code. I've tried multiple solutions but nothing seems to work. Could someo ...

What steps should I take to ensure my Bootstrap CSS3 code is error-free and W3C validated?

My customer is requesting that I validate the HTML5 & CSS3 code using W3. I plan on incorporating Bootstrap 3.3.4 into the project, but after including it and checking at , I discovered 32 errors and 142 warnings. The W3C CSS Validator results for (C ...

Struggling to concentrate on the branding

I've been using materializecss for some time now and recently encountered an issue while trying to navigate my website using keyboard tabbing. The checkbox in materializecss is a custom CSS checkbox, but when I set the tabindex for the label of the c ...

The never-ending loading problem at the bottom of the Firefox screen seems

I am facing an issue while trying to open something in Firefox using window.open(). The loading screen seems to never stop, and I cannot pinpoint the reason behind it. Any advice on how to resolve this would be greatly appreciated. View Screenshot: This ...

Tips for disabling the default behavior by using preventDefault in JavaScript

I need help with removing the preventDefault() function and submitting the form in the else condition of my code. Does anyone know how to achieve this? if(email.val() != ""){ //check email e.preventDefault(); $.ajax({ ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...