Shifting between classes in jQuery only takes effect after scrolling occurs

There seems to be an issue with the transition effect in my jQuery code that changes the background color of the .navbar upon scrolling. Even though it is supposed to start with a transparent background, it always begins with a yellow background. I have found a temporary solution by quickly moving down and then back up, but this is not ideal.

Is there a mistake in my implementation?

Thank you!

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    var scrollPos = $(window).scrollTop(),
      navbar = $('.navbar');

    if (scrollPos > 50) {
      navbar.addClass('alt-color');
    } else {
      navbar.removeClass('alt-color');
    }
  });
});
.navbar {
  background-color: transparent !important;
  -webkit-transition: all .5s;
  transition: all .5s;
}

.navbar.alt-color {
  background-color: yellow !important;
} 

.demo {
  width: 10%;
  margin: 0 auto;
  margin-top: 100px;
}
<head>
  <!--Botstrap 3 CSS-->
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  </head>


    
      <nav class="navbar navbar-default navbar-fixed-top alt-color">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
            <a class="navbar-brand" href="#">Brand</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
              <li><a href="#">Link <span class="sr-only">(current)</span></a></li>
              <li><a href="#">Link</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#">Separated link</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
            </ul>
            <form class="navbar-form navbar-left">
              <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
              </div>
              <button type="submit" class="btn btn-default">Submit</button>
            </form>
            <ul class="nav navbar-nav navbar-right">
              <li><a href="#">Link</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#">Separated link</a></li>
                </ul>
              </li>
            </ul>
          </div>
          <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
      </nav>
      
      
<!-- ignore-->
    <section>
      <div class="demo">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse augue velit, vehicula eu pretium in, semper sit amet sem. Suspendisse tortor quam, tincidunt id nisi ut, hendrerit sodales lectus. Proin quis mauris id arcu molestie euismod.
          Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
        </p>
      </div>
    </section>



    <!--jQuery-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!--Botstrap 3 JS-->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Answer №1

Simply delete the alt-color class from your navigation element

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    var scrollPos = $(window).scrollTop(),
      navbar = $('.navbar');

    if (scrollPos > 50) {
      navbar.addClass('alt-color');
    } else {
      navbar.removeClass('alt-color');
    }
  });
});
.navbar {
  background-color: transparent !important;
  -webkit-transition: all .5s;
  transition: all .5s;
}

.navbar.alt-color {
  background-color: yellow !important;
}

.demo {
  width: 10%;
  margin: 0 auto;
  margin-top: 100px;
}
<head>
  <!--Bootstrap 3 CSS-->
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

</head>



<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container-fluid -->
</nav>


<!-- ignore-->
<section>
  <div class="demo">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse augue velit, vehicula eu pretium in, semper sit amet sem. Suspendisse tortor quam, tincidunt id nisi ut, hendrerit sodales lectus. Proin quis mauris id arcu molestie euismod. Pellentesque
      habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
    </p>
  </div>
</section>



<!--jQuery-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!--Bootstrap 3 JS-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

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

Modify the appearance of certain text within an input field

I need some help adding style to specific text within an input field. For example, if the user types in "Hello world" and the special text is "world" I want to achieve this result: https://i.sstatic.net/Ozd6n.png This is what my HTML code looks like: & ...

Absence of peer dependencies

As a novice in the world of npm and angular projects, I have encountered an issue while using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89ebe6e6fdfadddbf8ed9aa7beb1aea1b0">[email protected]</a> in my package. ...

Having trouble aligning my fixed div to the center of the screen

I have scoured numerous resources in search of a solution to my problem, but nothing seems to work for me. I have created a simple portfolio site where I want the word 'Developer' to be the first thing visible upon loading, followed by the portfo ...

The PHP script executed through Ajax fails to load further data once the browser is closed

Currently, I am working on a website where a PDF is generated based on the input provided by the clients. To ensure a smooth user experience, I have decided that the PDF generation process will start only after the purchase is complete. This is because the ...

Unable to retrieve the value of a particular index within an array containing JSON data

Code to add items to an array: var allItems = []; $.getJSON(url, function(data) { $.each(data, function(i) { allItems.push({ theTeam: data[i]["TeamName"], thePlayer: data[i]["TeamPlayer"], }); }); }) When u ...

The Controller consistently receives a NULL value for the String variable passed from the View

I'm trying to send data from the View to the Controller using an Ajax call. However, the current code is passing NULL every time. Can someone please advise me on what I might be doing wrong? Here's the code in Index.cshtml: <input type="subm ...

What causes images to shift when resizing in Chrome, but not in Firefox or Safari?

My layout includes images - one on the left and two on the right. As I resize the browser window, the images scale accordingly. The issue arises when viewing my layout in Chrome: the image positions shift as I resize the browser, unlike Safari and Firefox ...

CSS styling not rendering consistently across various web browsers

Hey everyone! I've encountered an issue with my webpage. Feel free to check out the code on my CodePen here. When I view this page on Safari, everything looks perfect. However, when I switch over to Chrome or Firefox, the layout is all messed up. Ele ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

I'm curious about how I can leverage jQuery to update the options inside a select element whenever the user clicks on the arrow icon

I have a select element that looks like this: <select name="rowKey_1" id="rowTopic_1"> <option value="00">Topic 1</option> </select> In my table grid, I have multiple similar selects. What I am trying to achieve i ...

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

Navigate to the specified text in the dropdown menu based on the ul li selection

Is it possible to achieve a functionality similar to that of a select box, where typing a keyword that matches an option in the select box will automatically move the pointer to that option? I am looking to implement a similar feature in my HTML code: < ...

Determine the loading time for every page within an application using C#

I am seeking a solution that will allow me to track ajax calls and button events on multiple pages, calculate the load time of each page, and save this data (including page name and event name) in a database. Has anyone successfully implemented something l ...

What is the best method for positioning span content above all other elements without having it wrap around them?

Each form element on my page is accompanied by a span that displays an error message, if applicable. The layout consists of two columns: left and right. I am struggling to make the span display seamlessly from the left column all the way across the page wi ...

What is the best way to animate various sprites using distinct buttons in HTML and CSS?

I've been experimenting with animating a sprite by using different onClick button triggers. I encountered an issue where only one of the buttons works correctly in the fiddle. However, in my local file version, the other buttons work but only once and ...

Ways to Validate Success Data in jQuery

After successfully calling a PHP function using jQuery, I encountered an issue with the Ajax success function where I am unable to reset the form data upon successful submission. I attempted using the if(data.status == 'success'){ } format as we ...

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

Saving users' dark mode preference on my website

I recently implemented a dark mode feature on my website. However, I noticed that when I enable dark mode and then refresh the page or navigate away, the preference resets. To address this issue, I am looking to store the user's preference as a cookie ...

Perform an Ajax request upon clicking on the dropdown list item

I recently created a drop-down list using some JavaScript code. Here's how I did it: <script> $('.menu').dropit(); </script> <ul class="menu"> <li> <a href="#">Product_name</a> ...