Enhance Your Website with Jquery and Bootstrap 4: Imrpessive Navbar Effects for Resizing

Hello, I am facing a challenge that my novice mind is struggling to overcome. Utilizing Bootstrap 4 navbar and some jquery, I managed to create a transition where an initially invisible navbar transforms into a solid color when the user scrolls beyond a certain point. Despite searching for solutions, I haven't been able to find one. Here is my scroll code:

navScroll(){
    $(document).ready(function() {
        $(window).scroll(function(){
            if($(document).scrollTop() > 500) {
                $('.navbar').addClass('solid');
                $('.nav-link').addClass('black');
                $('.navbar-brand').addClass('black');
            }
            else{
                $('.navbar').removeClass('solid');
                $('.nav-link').removeClass('black');
                $('.navbar-brand').removeClass('black');
            }
        });
    });
}

My goal was to have the navbar turn solid white once the window width exceeds 700 pixels, maintaining this appearance while scrolling up and down. The JQ scroll code should only kick in when the window size drops below 700 pixels:

navWidth(){
    $(document).ready(function() {
        $(window).resize(function() {
            if($(document).width() < 700){
                $('.navbar').addClass('solid');
                $('.nav-link').addClass('black');
                $('.navbar-brand').addClass('black');
            }
        })
    })
}

However, I hit a roadblock here: Although I understand the need for a conditional statement, figuring out the next step has me stuck. Here's something I attempted, which had partial success but didn't fully work:

navCheck(){
    $(document).ready(function() {
        if($(document).width() < 700){
          $(window).resize(function(){
              $('.navbar').addClass('solid');
              $('.nav-link').addClass('black');
              $('.navbar-brand').addClass('black');
          })
      }
      else if($(document).scrollTop() > 500) {
          $(window).scroll(function(){
              $('.navbar').addClass('solid');
              $('.nav-link').addClass('black');
              $('.navbar-brand').addClass('black');
          })
      }
      else{
          $('.navbar').removeClass('solid');
          $('.nav-link').removeClass('black');
          $('.navbar-brand').removeClass('black');
      }
   })
}

Answer №1

Here's a way to achieve the desired result:

$(window).on("load resize scroll", function(e){
    if($(document).width() < 700 || $(document).scrollTop() > 500){ 
        $('.navbar').addClass('solid');
        $('.nav-link').addClass('black');
        $('.navbar-brand').addClass('black');
    } 
    else {
        $('.navbar').removeClass('solid');
        $('.nav-link').removeClass('black');
        $('.navbar-brand').removeClass('black');
    }
});

An alternative approach would be to only apply the changes on scroll past 500:

$(window).on("load resize scroll", function(e){
    if(($(document).width() < 700 && $(document).scrollTop() > 500)
       || $(document).scrollTop() > 500){ 
        $('.navbar').addClass('solid');
        $('.nav-link').addClass('black');
        $('.navbar-brand').addClass('black');
    } 
    else {
        $('.navbar').removeClass('solid');
        $('.nav-link').removeClass('black');
        $('.navbar-brand').removeClass('black');
    }
});

If you prefer, you can use individual event bindings like this:

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

This code will check for window width and scroll position on load, resize, or scroll events to determine when to show a solid navigation bar.

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

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

I am interested in designing a dynamic wave-themed background for a menu

I am looking to create a menu background that ripples like a wave when hovered over. Check out the first example here: https://i.sstatic.net/LoOWM.png I want to achieve the same effect. Can anyone help me with how I can do this? <ul> <li>likk ...

Can I increase the top margin by more than mt-5?

Seeking help to align elements on my website. I've applied mt-5 in the HTML, yet require additional margin space. Any suggestions on how to achieve this? ...

Sending input values to controller action parameters in CakePHP

I am working on an HTML form in which I need the URL output to be structured as follows: "example.com/mycontroller/action/mike/apple" Upon submitting the form using "post" method, the form values are not visible and can only be accessed through "_POST" ...

The execution of the function halts as soon as the player emerges victorious

In my attempt to create a basic game where players compete to click their designated button faster to reach 100%, I am in need of assistance with implementing a logic that determines the winner once one player reaches or exceeds 100. Essentially, I want ...

Encountering a situation where the data retrieved from Firestore in Angular TypeScript is returning as

I am encountering an issue with retrieving the eventID value from my Events collection in Firestore. Although I am able to successfully display all the events in my app, I require the eventID for additional functionalities. As someone new to TypeScript an ...

Special Bootstrap's hamburger menu

My website has a vertical navigation bar with a breakpoint set for medium-sized screens to display a hamburger menu. When the hamburger menu appears, I want to hide the text following the icons to save space and only show the icons. Clicking on the hamburg ...

The alignment of my divs is all out of whack -

Currently, I have styled my website to work perfectly in Firefox, but it's not appearing correctly in Chrome. You can see the layout at . My goal is to maintain the layout as seen in Firefox while also making sure it displays properly in Chrome and IE ...

Angular: The metadata version does not match for the module located in src/app/app.module.ts. A version of 3 was found when version

Recently, I made the transition from Angular 4.0.0 to 5.2.0. However, after implementing the recommended changes, I encountered a perplexing error message: ERROR in Error: Metadata version mismatch for module /home/khalidvm/Desktop/Workspace/Front/Migrat ...

Unexpectedly, the jQuery get function retrieves the entire webpage

I'm encountering difficulties when using .get requests to update elements through page load or button press. Here is the code snippet... $(document).ready(function() { //updateVariable(); $('#dannychoolink').html('<?php dan ...

What is preventing BODY from respecting min-height: 100% ?

Struggling to create a basic webpage with a container that extends to the bottom? Here's what I'm aiming for: #Main should be as tall as the viewport, but able to stretch further with additional content. body should match the viewport height, y ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

Is it achievable to use PHP to automatically scroll to the bottom of a container?

Is there a way to automatically scroll to the bottom of a div container using PHP code instead of javascript or CSS? While I haven't been able to find a solution using just CSS, I have come across some options utilizing javascript. However, since I a ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...