"Upon initial activation, the CSS animation will loop twice before coming to a stop

Is there a way to create a navigation bar that starts off transparent at the top of the page and then becomes opaque as you scroll down? I have tried implementing an animation for this effect, but it seems like the animation triggers twice when it should only trigger once. How can I resolve this issue?

window.onscroll = function () {
    var scroll = getScrollTop();
    var navbar = document.getElementById('navbar');
    if (scroll > 20) {
        navbar.classList.remove('onTop');
        navbar.classList.add('moved');
    }
    else{
        navbar.classList.remove('moved');
        navbar.classList.add('onTop');
    }
}
function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        return pageYOffset;
    }
    else{
        var B= document.body;
        var D= document.documentElement;
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}
body {
    background: linear-gradient(215deg, #d55724, #5259e2);
    background-size: 400% 400%;
    margin:0;
    padding:0;
    height:1000px;
}

.navbar {
    position: fixed;
    top:0;
    width:100%;
    height:50px;
}
.onTop {
    position: fixed;
    top:0;
    width:100%;
    height:50px;
    animation-iteration-count: 1;
    animation: NavBar-onTop .3s;
}
.moved {
    background-color: white;
    position: fixed;
    top:0;
    width:100%;
    height:50px;
    animation-iteration-count: 1;
    animation: NavBar-moved .6s;
}
@keyframes NavBar-moved {
    from {background-color: rgba(255, 255, 255, 0);}
    to {background-color: rgb(255, 255, 255);}
}
@keyframes NavBar-onTop{
    from {background-color: rgb(255, 255, 255);}
    to {background-color: rgba(255, 255, 255, 0);}
}
<div id="navbar" class="navbar">ExampleNavBar</div>

Answer №1

I have successfully resolved the issue.

$(window).scroll(function(){
    var scroll = $(window).scrollTop();
    if(scroll < 300){
        $('.navbar').css('background', 'transparent');
    } else{
        $('.navbar').css('background', 'white');
    }
});
function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers except IE before #9
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}
body {
    background: linear-gradient(-250deg, #1E3B70, #29539B);
    background-size: 400% 400%;
    margin:0;
    padding:0;
    height:10000px;
}

.navbar {
    margin-top: 0 !important;
    position: fixed !important;
    top:0 !important;
    width:100%;
    height:50px;
    transition:500ms ease;
    background-color: transparent;
}
.navbar.scrolled {
    background:white;
}
    <div id="navbar" class="navbar">TEST</div>
    <script src="https://code.jquery.com/jquery-2.2.4.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

Tips for creating a "sticky" button in Angular that reveals a menu when clicked

Is there a way to incorporate a feature similar to the "Get help" button on this website: The button, located in the lower right corner, opens a sticky chat menu. I am interested in adding dynamic information to the button (such as the number of tasks a u ...

I'm interested in concealing a div by resizing the window

Attempting to conceal a div using jQuery, I implemented the following code: $(window).resize(function(){ if ( window.innerHeight < 750 ) { $("footer").animate({'height' : '0px'}, 500); } if ( window.innerHeight > 750 ) ...

Steps for Displaying Error Message when Search Result is Not Found in a JavaScript Table

After creating a table using HTML to display student data like name, degree, and profession, I added a search bar for users to find information on a specific student by typing the student's name. If the student is not in the table, a message "Result n ...

Managing jQuery cookies through the click actions of various elements

Can anyone assist me in setting and removing cookies with a simple click event? This is my HTML structure: <button id="listing_123" class="add-listing">Add to Itinerary</button> <button id="listing_456" class="add-listing">Add to Itiner ...

Ensure that the TextBox field extends to the edges of the parent div, with full cross-browser compatibility

In the following code snippet, there is a challenge in ensuring that the TextBox field properly fits within the Width and Height of the div#chat-message. This seems to work well in Chrome but encounters issues in IE8 or Mozilla. Additionally, in Mozilla, t ...

Send data from HTML forms to PHP without needing to reload the page

I’m currently developing a website that showcases data retrieved from a database using PHP. The site includes checkboxes within a form, and based on the user's selections, I want the data displayed in a certain div to refresh when they click ‘appl ...

Tips for changing the state of a toggle button with JavaScript

I need help creating a toggle button. To see the code I'm working on, click here. In my JavaScript code, I am reading the value of a 'checkbox'. If the value is true, I add another div with a close button. When the close button is clicked, ...

The data in my database is not accurately displaying information for the fields of city, course, and second name

database showing other entries The data is not being displayed correctly in the database for some fields like first name, second name, course, and city. Despite this issue, I am still able to successfully log in. I have attempted to make changes to the co ...

What is the process for making a new post?

Having some trouble with using the form correctly. I've been trying to figure out how to create a post, but I'm encountering an issue; I can't seem to get posting to work properly. I am looking to save both POST and Image FILE. views.py @ ...

Troubleshooting base href issues in AngularJS routing

For a demonstration, I decided to try out this plunker from a tutorial that showcases tab routing across different pages. After downloading the entire zip file and running it as is (e.g. with all files in the same directory and utilizing CDN links), I enco ...

The process of uploading a file to the server directory via ajax is not functioning correctly. Despite attempts to upload the image, it does not successfully transfer to the designated upload

I am encountering an issue with uploading files to the server upload directory using AJAX. The image is not being successfully uploaded and I keep receiving a "connection reset" error. Can you please review my code below to see if there are any mistakes? T ...

Tips for transforming a hover menu into a clickable menu

The scenario above demonstrates that when hovering over the dropdown menu, it displays a submenu. However, I want the submenu to be displayed after clicking on the dropdown text. Could anyone provide assistance on how to change the hovermenu to a clickabl ...

Adding multiple variables in jQuery: A guide to mimicking the .= operator from PHP

Being new to jQuery, I'm a bit unsure of how to achieve this. Typically in php, I can accomplish something like this: $result = ''; $result .= 'Hi'; $result .= ' there'; echo $result; I'm simply wondering if there ...

The detailView feature in wenzhixin bootstrap-table is failing to initialize the child row

I am currently utilizing the wenzhixin bootstrap table and attempting to initialize another bootstrap table within a child row known as 'detailView' in the code. Previously, I was using datatables but found this method to be simpler and more dir ...

Using localStorage in an Angular template: a comprehensive guide

Currently, I am facing some issues with localStorage on a website as I am unable to get a * ngif directive to function as desired. To provide further context: When a user logs in, their information is stored in the localStorage under the 'identity&ap ...

Tips on how to round a whole number to the closest hundred using Javascript

Suppose there is a numerical value given let x = 890 and the objective is to round it off to 900. If the number is 820, then it should be rounded to 800. We can safely assume that the input number (x) will always be an integer. While manually checking ...

Arranging 2 divs side by side

As a beginner, I'm struggling to find the answer because I have no idea what search terms to use. Now, I have a form <form action="#" method="POST"> <div id="labels"> <label>CMS System</label><p> ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

What is the best way to capture source code and store it in a text file?

Can you assist me in extracting the source code of a webpage and saving it into a text file? My goal: Instead of going through the process of right-clicking on the page, selecting view source code, copying, and pasting into a text file... I want to simpl ...

GeoJson with timestamp and marked directional indicator

I am looking to create an animation of a boat traveling along a specific route. Currently, I am able to display the route as a line and the boat as a circle using TimestampedGeoJson: # circle with following line features = [ { 'type': ...