Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these IDs to the respective hrefs in the navigation menu. For example,

<a href="#about">About us</a>
takes you to the div with an ID of #about when clicked.

The scrolling effect works well, but there is an issue due to my fixed header - when scrolling to a section, the top part of the section gets cropped by the overlaying header. You can view a live preview here: www.loaistudio.com. How can I address this problem? Additionally, I want to enhance the JavaScript code below to add a class of 'Active' to the link in the navigation menu corresponding to the section currently being viewed.

$(document).ready(function () {
    $('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
                }, 700);
                return false;
            }
        }
    });   
});

Answer №1

Custom Scrolling Functionality

If you are looking to customize the scrolling behavior on your website, one simple solution would be to adjust the scrollTop property to factor in the height of the menu bar...

For example:

scrollTop: target.offset().top - 186

If the menu bar is not a fixed height, you can also calculate the height dynamically.


Implementing Active Links on Scroll

To highlight active links based on scroll position, you can use the following approach:

$(window).scroll(function(){
    var scrollHeight = $(window).scrollTop() + 186;
    
    // Define offset positions for different sections
    var welcomeOffset     = $('#Welcome').offset().top;
    var aboutOffset       = $('#About').offset().top;
    var portfolioOffset   = $('#Portfolio').offset().top;
    var endorsementOffset = $('#Endorsements').offset().top;
    var contactOffset     = $('#Contact').offset().top;
    
    // Customize colors for links
    var foreColor = "777";
    var backColor = "FAFAFA";
    
    // Highlight active link based on scroll position
    $('#mainMenu li a').css({background:"#FFFFFF", color: "#F58221"})
    if(scrollHeight >= welcomeOffset && scrollHeight < aboutOffset){
        $('#mainMenu :nth-child(1) a').css({background:"#"+backColor, color:"#"+foreColor})
    }
    // Add similar conditions for other menu items...
})

You can add the above code within <script>...</script> tags in your HTML file. Remember to include it before or after existing jQuery code.


Combining Scrolling and Link Navigation Functions

$(document).ready(function () {
            $('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
                }, 700);
                return false;
            }
        }
    });   
    });

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

An AngularJS error has been caught: [$injector:modulerr]

After implementing AngularJS in my application, I encountered an error when adding a configuration section for routing: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.9/$injector/modulerr?p0=demoApp&p1=Error%3A…nts%2FGitHub%2FS ...

Maintaining content after page refresh with jQuery Ajax

Utilizing jquery and ajax in my project. Here's a snippet of the code I plan to implement. If I refresh the page after receiving a response (in this case, a form), I lose all the content. Is there a way to store/cache the response data in a variable s ...

Advancing with Bootstrap 4: Progress Bar Evolution

It appears that Bootstrap 4 has introduced a new method for updating the progress of your progress bar. Aim: Dynamically update the progress bar percentage upon click <div class="progress"> <div id='progressBar' class="progress-bar" r ...

Show data from a Node.js server in its original format within an AngularJS application

Currently, I am using the angular fullstack generator to develop a web application. One issue I am facing is sending file data from the Node.js server to display on the front end. The problem arises because the data is being sent in an unformatted manner, ...

Enhance your user interface by customizing the expand icon in the React material

Currently, I am utilizing Material-table with a focus on Tree-data. You can find detailed information about this feature here: https://material-table.com/#/docs/features/tree-data. While attempting to implement the provided example, I am encountering diff ...

Ways to incorporate services into functions within Angularjs

I'm struggling to grasp the concept of dependency injection in AngularJS. Currently, I am attempting to inject $interpolate and $eval into my controller. However, after consulting the documentation, I realized that my lack of foundational knowledge i ...

Uncovering the "parent having two child elements" structure from HTML: A guide

I want to identify all parents with two children in an HTML document. Case 1 <parent> <child> <tag></tag> </child> <child></child> </parent> Case 2 <parent> <parent_and_child> <tag& ...

Why won't my Java servlet code execute?

included the directory structure To facilitate adding two numbers and displaying the result upon clicking a submit button, I developed a straightforward Java servlet. This servlet retrieves the necessary information when called. The development environmen ...

Replace the bullet icon with a double quote symbol

My HTML List needs a different look - I want to change the bullet icon into a double quote icon. A website that I found interesting is this one. Here's the CSS code I have: .listStyle li:before { list-style: none; content: "\00BB"; } < ...

NPM is having trouble locating a shell script

An error is encountered when running npm run build: '.' is not recognized as an internal or external command, operable program or batch file. Here is the npm file that contains relevant scripts: "scripts": { "postinstall": "jspm instal ...

Avoiding content resizing when using a drawer in Material UI

My project features a drawer that expands, but I am encountering an issue where the content inside the drawer resizes when expanded. However, this is not the desired outcome. I want the expanded drawer to overlay the content without resizing it. How can I ...

Determine the total number of hours along with the precise minutes

Could you assist me with calculating minutes? Here is an example: var time_in = '09:15'; var break_out = '12:00'; var break_in = '13:00'; var time_out = '18:00'; var date = '2018-01-31'; var morning = ( ...

Despite implementing the necessary middleware, the CSS file still refuses to load

My CSS files are not loading properly. When I inspect the element (F12) and go to Networks, my CSS file is not visible. I have added the middleware: app.use(express.static(path.join(__dirname, '/public'))); and required the path above it. I ha ...

Seamless blend of images with a stunning mosaic transition effect

I attempted to create a mosaic effect on my carousel similar to this example: , but not exactly like this. I want to include control buttons for next and previous, and have images in HTML tag. However, my attempt is not working and I need help. This is ...

Are your divs getting truncated?

Currently faced with a perplexing issue where inserting elements into a div causes scaling problems, resulting in most of the divs being cut off. This glitch occurs when two new elements are added. Despite changing page sizes and thoroughly debugging by o ...

There was an issue with rendering: "TypeError: Unable to access the 'name' property of an undefined object" [Vue alert]

I encountered the following error message: TypeError: Cannot read property 'name' of undefined Here's the snippet from the Vue file where the error occurred: <tr v-for="user in fields.data" :key="user.id"> <td>{{ user.id ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Having trouble viewing a dynamically adjusting Angular NVD3 graph embedded in bootstrap

I have been utilizing the NVD3 library along with bootstrap 3.0 for my project. I have two divs with the classes "col-md-6 col-sm-12" positioned side by side. My goal is to showcase charts in both of these divs. To ensure that the charts are displayed corr ...

The rotation function of the div element is malfunctioning

Exploring CSS has led me to a peculiar issue where transform:rotate is not functioning as expected. Here is an instance of the animation not triggering: jsFiddle CSS .close { width:100px; height:100px; background:#00f; ...

Confirmation for deletion in HTML form

Is there a way I can include a confirmation message for deleting an item on my form button? Any suggestions on which JavaScript code to use? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete ...