Is there a way to implement a shrinking header with a shadow effect while scrolling by utilizing Bootstrap and jQuery?

I am currently in the process of developing a website using Bootstrap 4 and jQuery. I am trying to implement a header that reduces in size and adds a shadow effect as the user scrolls down the page. Although I have written some code that is partially working, I am not achieving the seamless transition I desire, and the shadow effect is not consistent.

Challenge:

- The header and logo should shrink while scrolling down. - A shadow should be displayed under the header when scrolling. - The transition should be smooth, but mine appears choppy.

Below is the HTML, CSS, and JavaScript code I have been working on:

<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
    <div class="container">
        <a class="navbar-brand" href="#">
            <h6 id="logo" class="display-7 font-weight-bold text-dark">
                Mahyar<br>ART<br>GALERIE
            </h6>
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
            aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item"><a class="nav-link" href="#">Home</a></li>
                <li class="nav-item"><a class="nav-link" href="#">About</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Services</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
            </ul>
        </div>
    </div>
</nav>

CSS:

#logo {
    font-size: 2.5rem;
    transition: font-size 0.3s ease-in-out, padding 0.3s ease-in-out;
    padding: 10px 0;
}

.shrink #logo {
    font-size: 1.5rem;
    padding: 5px 0;
}

.navbar {
    transition: padding 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
    padding: 20px 0;
}

.shrink .navbar {
    padding: 10px 0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

JavaScript:

#logo {
    font-size: 2.5rem;
    transition: font-size 0.3s ease-in-out, padding 0.3s ease-in-out;
    padding: 10px 0;
}

.shrink #logo {
    font-size: 1.5rem;
    padding: 5px 0;
}

.navbar {
    transition: padding 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
    padding: 20px 0;
}

.shrink .navbar {
    padding: 10px 0;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

My Concern:

The transition is not as smooth as I would like, particularly on slower devices. At times, the shadow effect under the header does not display correctly or flickers. What I've Tried:

I have made adjustments to the transition timing but still notice choppiness. I have tested on various browsers, but the shadow problem persists. Question: How can I achieve a smoother transition and ensure the shadow effect is consistent across different devices and browsers?

Answer №1

The Javascript code you used to toggle the shrink class on the scroll event was not provided, making it difficult to understand the current behavior in comparison to any suggested solutions.

Considering you have existing CSS transitions, I updated a selector to better match the logo and included the necessary JavaScript to add/remove the shrink class from the .navbar element.

It seems to be functioning as expected:

//on DOM ready
$(document).ready(function() {
  //adds the window scroll event handler
  $(window).scroll(function() {
    //that will add/remove the shrink class to the .navbar according to the scrollbar relative to threshold
    const threshold = 50;
    if ($(this).scrollTop() > threshold) { 
      $('.navbar').addClass('shrink');
    } else {
      $('.navbar').removeClass('shrink');
    }
  });
});
#logo {
  font-size: 2.5rem;
  transition: font-size 0.3s ease-in-out, padding 0.3s ease-in-out;
  padding: 10px 0;
}

.shrink #logo{
  font-size: 1.5rem;
  padding: 5px 0;
}

.navbar {
  transition: padding 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  padding: 20px 0;
}

.navbar.shrink {
  padding: 10px 0;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

section {
  height: 2000px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/css/bootstrap.min.css" integrity="sha512-rt/SrQ4UNIaGfDyEXZtNcyWvQeOq0QLygHluFQcSjaGB04IxWhal71tKuzP6K8eYXYB6vJV4pHkXcmFGGQ1/0w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
  <div class="container">
    <a class="navbar-brand" href="#">
      <h6 id="logo" class="display-7 font-weight-bold text-dark">
        Mahyar<br>ART<br>GALERIE
      </h6>
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" href="#">Home</a></li>
        <li class="nav-item"><a class="nav-link" href="#">About</a></li>
        <li class="nav-item"><a class="nav-link" href="#">Services</a></li>
        <li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>

<section>
  ...PAGE CONTENT...
</section>

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

Styling an image with dual attributes using CSS

I'm looking to customize two img classes with different properties. For instance, in my CSS, I want to define: img { padding-left: 15pt; float: right; } and then: img1 { padding-left: 15pt; float: left; } where img1 would serve as a tag fo ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

Display only the offcanvas button

Having trouble with Bootstrap 5 offcanvas? The offcanvas doesn't hide when I click the button again. <button data-bs-toggle="offcanvas" role="button">Add to Cart</button> Every time I click the button again, the offcan ...

Preventing the elements within a div section from shifting position

I am facing an issue with a div section that contains multiple <a href=""> tags. When I shrink the div section on the page, the contents move when a user tabs into it. Is there a way to lock the div section so that its contents do not move? For exam ...

Locating the value of a data attribute from a distant parent div using jQuery

How can I access the closest div from an anchor tag that has a data-id attribute without using multiple parent() methods? Even though .parent().parent().parent() works, I am trying to find a better solution. <div class="panel panel-default" data-id="@ ...

How to Disable a Dynamically Generated <li> Element Using jQuery on Click Event

Script Query: Creating <li> Elements Dynamically echo '<div class="pagination"><ul>' . "\n"; // Previous Post Link. if ( get_previous_posts_link() ) { printf( '<li>%s</li>' . "\n", get_previ ...

CSS styling failing to meet desired expectations

Two different elements from different panels are using the same CSS styles, but one displays the desired text while the other does not. The CSS file in question is named grid.css. To see the issue firsthand on my live website, please visit: I am uncertai ...

Is there a way in Python using Selenium to scroll to the position of a page where a specific element is visible?

I have been attempting to navigate to the center of the page using this code snippet, but it does not seem to be functioning correctly. driver.execute_script("window.scrollTo(0, document.body.scrollHeight/2);") In addition, I am experimenting with elem ...

Position an image at the center within a footer widget

I am attempting to position an image at the center of a footer widget. I have gone through various solutions recommended here, but I am unsure if I am implementing the code correctly. Here is my CSS: #footer img.center { display: block; margin-le ...

Issue with background image positioning in IE 7 while scrolling

I am struggling with creating nested divs where the middle one has a fixed background image that remains static while the rest of the content scrolls. My solution works in Firefox, Chrome, and Opera but I'm encountering issues in IE7. Despite knowing ...

Styling text using SVG in HTML

I'm trying to underline a text element in SVG using the text-decoration attribute, but I'm running into an issue with the color of the line not changing. Here is the code snippet I am working with: <svg id="svg" viewBox="0 0 300 ...

Calculating the sum of all elements in an array

Hi, I am currently attempting to retrieve the total value from an array (such as Arr[1] + Arr[2], and so forth). Unfortunately, I am struggling to find a solution. Below is my existing function: this.hourlyTotals = function() { var custsperhour = Math ...

Is it possible to execute a function within an HTML page simply by clicking on it?

As someone who is new to the world of HTML, CSS, and JS, I'm currently facing a challenge: On my website's page1.html, I have implemented a feature that allows users to sort different articles on the page by selecting a sub-menu from the navigat ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

How to eliminate the vertical scroll indicators in Material UI's TextField

I'm currently working on customizing the styling of a Material UI textfield and I need to remove the top-down arrows. Below is the code snippet I have so far: const theme = createMuiTheme({ MuiInput: { root: { "&::-webkit-outer-spin-bu ...

Utilizing encoding and decoding techniques in PHP and JavaScript with robust data attribute validation

I am utilizing data attributes to transfer information from HTML to JavaScript. The data attributes are derived from MySQL data, so they may contain spaces, resulting in validation errors since spaces are not permitted within attributes. My proposed solut ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

What is the best way to resize an HTML element to fill the remaining height?

I'm struggling with adjusting the height of a node-webkit app to fit the current window size. See below for an image depicting what I am aiming for. Intended Goal : HTML Markup : <body> <div class="header"> THIS IS A HEADER W ...

Unleash the power of AJAX to dynamically load additional content on

I am in need of a straightforward method to incorporate a "load more" button into my JSON results. Here's the relevant snippet of code: // GETTING JSON DATA FOR TIMELINE $UserTimeline = 'MYSITE/TimelineQuery.php?id='.$UserPageIDNum.'&a ...

Collapse all Bootstrap accordions with a single click of a button

Is there a simple way to toggle the collapse/expand functionality of all accordions with just one button click? I attempted to achieve this by using a basic button that would remove the 'active' class and add it back, but unfortunately, it didn&a ...