Struggling with nested functions or seeking advice on a more efficient approach?

Seeking assistance in changing the logo and shrinking the navbar on scroll using Bootstrap 4. However, I want this effect to apply only when the screen size is greater than 992px. I've been trying to implement a nested function without much success.

I am open to alternative suggestions and would appreciate any help...

Here's my current code:

function adjustNavbar(x) {
    if (x.matches) { // If media query matches
      $('.navbar-brand img').attr('src','../img/eventlogo_2019-white.svg');
    } else {
      // Collapse Navbar & Change Logo on scroll
  var shrinkNavbar = function() {
    if ($("#mainNav").offset().top > 100) {
      $("#mainNav").addClass("navbar-shrink");
      $('.navbar-brand img').attr('src','../img/eventlogo_2019-white.svg');
    } else {
      $("#mainNav").removeClass("navbar-shrink");
      $('.navbar-brand img').attr('src','../img/eventlogo_2019.svg');
    }
  };
  // Auto-collapse navbar if page isn't at the top
  shrinkNavbar();
  // Collapse the navbar during scrolling
  $(window).scroll(shrinkNavbar);
    }
  }

  var x = window.matchMedia("(max-width: 991px)")
  adjustNavbar(x) // Call listener function at run time
  x.addListener(adjustNavbar) // Attach listener function on state changes

Answer №1

This solution should simplify things for you. Here, the function MyFunction will run when: 1) The document is ready, 2) The window is scrolled.

function myFunction() {
    var x = window.matchMedia("(max-width: 991px)");
    if (x.matches) { // If media query matches
        $('.navbar-brand img').attr('src','../img/eventlogo_2019-white.svg');
    } else {
    // Collapse Navbar & Change Logo on scroll
        if ($("#mainNav").offset().top > 100) {
            $("#mainNav").addClass("navbar-shrink");
            $('.navbar-brand img').attr('src','../img/eventlogo_2019-white.svg');
        } else {
            $("#mainNav").removeClass("navbar-shrink");
            $('.navbar-brand img').attr('src','../img/eventlogo_2019.svg');
        }
    }
}

// Call myFunction on document ready event
$(document).ready(myFunction);

// Call myFunction on scroll event
$(window).scroll(myFunction);

Answer №2

Forget about using complex JS solutions for what you want to achieve. With just a touch of CSS and minimal JS (for storing scroll position), you can get the desired result. Check out this simple code snippet:

// store the scroll position on the HTML element so css can react to changes
document.addEventListener('scroll', () => {
  document.documentElement.dataset.scroll = window.scrollY;
});
html,
body {
  padding: 0;
  margin: 0;
}
<!-- use a media query to prevent the change to the header on smaller devices -->
@media only screen and (min-width: 992px) {
  <!-- You can check the data-scroll attribute on the HTML node to see if the user has scrolled and set the appropriate styles then, this add a padding to the top of the document -->
  html:not([data-scroll='0']) body {
    padding-top: 3em;
  }
  <!-- this changes the header to fixed and changes the image -->
  html:not([data-scroll='0']) header {
    position: fixed;
    top: 0;
    background-image: url(https://png.pngtree.com/thumb_back/fh260/back_pic/02/65/14/5957873074946eb.jpg);
  }
}
<!-- this is the default style for the header -->
header {
  background-image: url(https://cdn.pixabay.com/photo/2015/11/02/18/34/banner-1018818_960_720.jpg);
  width: 100%;
  background-position: left;
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0;
  padding: 0;
  height: 3em;
}

h1 {
  padding: 0;
  margin: 0;
}
<!-- initialize the data-scroll attribute on the HTML element -->
<html data-scroll="0">

<head>
  <title>Sample </title>
</head>

<body>
  <header>
    <h1>
      I am your header
    </h1>
  </header>
  <section>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
    <p>
      I am your content
    </p>
    <p>
      There is a lot of me so i can scroll
    </p>
  </section>
</body>

</html>

Feel free to resize the window to see the effects here.

Note - The code may appear distorted in the snippet viewer, but it works perfectly fine when tested on jsfiddle.

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 is the best method for retrieving the array response in Node.js after finishing the foreach loop?

I have encountered an issue with my code where it is returning an empty array after running a foreach loop and trying to send data to the client. The problem seems to be related to the global declaration of a variable. Specifically, I need to push the loan ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Tips for customizing the appearance of the Android status bar in Nativescript?

I am facing a challenge in styling the status bar in NativeScript and have not yet found a solution. I attempted to use this package but encountered issues when inserting the following line into the main-page.xml file: <x:StatusBar android:barStyle=&quo ...

In Java, the output of jsExecuteScript returns null, whereas in the browser console, it returns a String value

While running a script in the console of the browser on the aforementioned page, I encountered the following: document.querySelector('.subscribe_form input').value The placeholder value displayed was "Enter your email address." However, when at ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Why does col-sm-12 not fill the entire width on smartphones? Am I missing something?

SASS Breakpoints Definition: /* For the grid */ $grid-breakpoints: ( xs: 0, sm: 576px, md: 768px, lg: 992px, xl: 1200px, xxl: 1440px, xxxl: 1660px ); Structure of My Columns: <div id="footer_lower_menus" class="row"> ...

Incorrect date format sent to backend through API

Within my Angular + Angular Material application, I am facing an issue with a date range picker. My goal is to send the selected start and end dates in a formatted manner through an API call. However, when the date values are sent over the API as part of t ...

In the event that the `algorithms` option is not defined, an error will be thrown stating that `algorithms` must be specified: `Error: algorithms should be

Currently, I am diving into the world of Nodejs, but I have hit a roadblock in my learning journey. I recently installed a new library from npm called express-jwt, but it seems to be throwing an error when I try to run it. Below is the snippet of my code a ...

how to assign values to objects in angularjs select box

Here is my Angular code: angular.module("myApp",[]) .controller("myCtrl",function($scope){ $scope.projectObj = {"proId":"33","proName":"samal"} $scope.projectArr = [{"proName":"samal","proId":"33"},{"proName":"aaa","proId":"47"},{"proName":"sdf","proI ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

What methods can be used to prevent the appearance of the ActiveX warning in IE7 and IE8 when dealing with drop

I have a dilemma with my website where I am using JavaScript to modify CSS on hover for specific items. Interestingly, in Firefox everything runs smoothly without any ActiveX message popping up. However, in IE8, I encounter a warning stating "To help prote ...

What impact does including or excluding classes from html elements have on the onclick and equivalent functions associated with those elements?

My code is quite simple and uses jQuery. I have two elements with a specific class assigned to them, one of which also has an additional class called b1. The class b1 has an onclick property attached to it. However, when I try to remove the class b1 from ...

Unlocking the Secrets of Json Data with Knockout: A Guide

I'm struggling to create a Typewriter Effect using knockout because I can't seem to store my data inside the table properly. Despite researching for weeks, I lack the fundamental knowledge to solve this issue on my own. This is my first time seek ...

How to resolve logic issues encountered during Jasmine testing with describe()?

I am encountering an issue while testing the following code snippet: https://i.sstatic.net/ImwLs.png dateUtility.tests.ts: import { checkDayTime } from "./dateUtility"; describe("utilities/dateUtility", () => { describe("ch ...

Which specific HTML5 video event is triggered when the current playback time of the video is updated?

My goal is to give users the option to skip the preroll ad after a specified time (e.g. 5 seconds into the ad) and then transition to playing the regular video content. How can I make this happen? Below is an outline of my current approach: var adManager ...

Ajax success is causing me some trouble

Does anyone know why the following code, which is supposed to display an alert message, is not working? Everything else seems to be functioning correctly except for the alert() function. <script> $(document).ready(function(){ var baseUrl = ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- https://i.sstatic.net/DF8Wn.png $(docum ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

One common issue popping up in Webpack logs is the error message "net::ERR_SSL_PROTOCOL_ERROR" caused by a call to sock

Using react on the front-end and .net core 3.1 on the back-end. Running webpack on localhost:8080 for client-side development. Configuring proxyToSpa in Startup.cs: applicationBuilder.UseSpa(spa => { spa.UseProxyTo ...