Using jQuery to merge two events

As I work on developing a landing page with a fixed position navbar that changes color based on scroll positions, here's my current code snippet:

// Change Nav Colors on Scrolldown
var scroll_pos = 0;
jQuery(document).scroll(function(){
    scroll_pos = jQuery(this).scrollTop();
    if(scroll_pos > 730){
        jQuery('.top-menu-navigation').css({'background-color' : '#000000'});
    } else if (scroll_pos < 730){
        jQuery('.top-menu-navigation').css({'background-color' : '#ffffff'});
    }
});

The background color for .top-menu-navigation div changes accordingly. However, the link colors are defined in

.top-menu-navigation ul > li a
. I attempted to combine both by including
jQuery('.top-menu-navigation ul > li a').css({'color' : '#ffffff'});
within the same if statement, but it didn't produce the desired outcome. How can I unify these two actions?

For additional insights, here's the complete content of my file:

jQuery(document).ready(function(){

    // Create jQuery Tabs
    jQuery("#tabs").tabs().addClass('ui-tabs-vertical');


    // Sticky Top Nav

    var NavTop = jQuery('.top-menu-navigation').offset().top;

    jQuery(window).scroll(function(){
        if( jQuery(window).scrollTop() > NavTop ) {
            jQuery('.top-menu-navigation').css({position: 'fixed', top: '0px'});
        } else {
            jQuery('.top-menu-navigation').css({position: 'static'});
        }
    });

    // Change Nav Colors on Scrolldown

    var scroll_pos = 0;

    jQuery(document).scroll(function(){
        scroll_pos = jQuery(this).scrollTop();
            if(scroll_pos > 730){
                jQuery('.top-menu-navigation').css({'background-color' : '#000000'});
            } else if (scroll_pos < 730){
                jQuery('.top-menu-navigation').css({'background-color' : '#ffffff'});
            }
        })
    });

I'm interested in merging the Sticky Top Nav and Color Change functionalities, if feasible. Also, am I correctly invoking jQuery on the appropriate objects (document, window)?

I've chosen to use jQuery instead of $ specifically for this static landing page intended for a Wordpress site.

Relevant HTML section:

<nav class="top-menu-navigation">

    <ul>
        <li><a href="">Menu Item 1</a></li>
        <li><a href="">Menu Item 2</a></li>
        <li><a href="">Menu Item 3</a>
        ...

            </nav> <!-- end top-menu-navigation -->

Answer №1

Simply append one after the other and it should function properly.

// Creating a Sticky Top Navigation
var NavTop = jQuery('.top-menu-navigation').offset().top;

var scroll_pos = 0;
jQuery(window).scroll(function(){
    if( jQuery(window).scrollTop() > NavTop ) {
        jQuery('.top-menu-navigation').css({position: 'fixed', top: '0px'});
    } else {
        jQuery('.top-menu-navigation').css({position: 'static'});
    }

    // Adjust Navigation Colors on Scroll

    scroll_pos = jQuery(this).scrollTop();
        if(scroll_pos > 730){
            jQuery('.top-menu-navigation').css({'background-color' : '#000000'});
        } else if (scroll_pos < 730){
            jQuery('.top-menu-navigation').css({'background-color' : '#ffffff'});
        }
});

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

When using jquery.hide() and show(), the content within the div disappears momentarily before reappearing

Hello! I am experiencing an issue where the content of my div disappears after using a jQuery hide() and show() function. It seems to be gone. <li class="gg3"><a class="link" href="#" data-rel="content3">Link1</a></li> <div clas ...

Restrict the number of rows in a real-time search JSON data by utilizing the $.each method

Is there a way to limit the number of rows returned in live search JSON data through URL? I attempted to count the table rows and return false, but it did not work. Any suggestions on how to achieve this? $(document).ready(function() { $.ajaxSetup ...

I am unable to close the hamburger menu by clicking on it

I am facing an issue with the hamburger icon functionality. The menu opens when I click on it, but it is not getting closed when clicked again. I have been trying to debug the code, but I can't figure out what's causing the problem. If anyone has ...

Improving user experience through real-time form validation in CodeIgniter with the

As I am working on a form with fields such as Fullname, Password, and Mobile no, each field is initially displayed individually on the page. When a user clicks on a button, the next field should be displayed while setting AJAX validation on it. The goal is ...

Expanding the Bootstrap 4 carousel on the right side

Could use some help with adjusting the space to the right on my Bootstrap 4 carousel. It's not aligning properly with the page layout. Here's an example: http://jsbin.com/wakuyiqebu. The issue is more prominent on mobile devices. <div class=" ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Refreshing a page occurs every 30 seconds or upon the user submitting a form

My PHP page consists of various includes for different sections of a video website. One of these sections is a comments area where users can submit their feedback to a database successfully. However, I want to ensure that only the specific included page/di ...

CSS mandates the inclusion of the required tag on input fields, however it may not always be necessary

Currently, I am using Google Chrome which is vital for my work. Utilizing CSS and jQuery, I have developed adorable 'placeholders' that transition into labels. You can view the codepen here. //HTML <div class="form-group col-lg-6 field"> ...

Seeking guidance on resolving issues with this div table

After almost getting everything set up, I encountered some strange issues that have been difficult to resolve. The challenges I'm facing include: The spacing on the right side is too large. Tables always appear stacked without any spacing in bet ...

Dealing with ASP.NET forms that involve a javascript plugin generating substitute input

I'm facing an issue with my ASP.NET MVC webpage where I submit a form using AJAX in the following way: function ValidateFormAndAjaxSubmit(formId, callingElement) { if (IsNotDblClick(callingElement.id)) { var _form = $("#" + formId); ...

modify rectangular section in drupal rather than numerical block

Currently, I am attempting to modify blocks within my Drupal 7.x website using the Zen base theme. While I have been successful in adjusting the CSS styles of the blocks based on their numbers in the block.css file, I find this method quite confusing. Is ...

Steps to trigger a modal (bootstrap 5) in react upon clicking a cell within the Full Calendar interface

My goal is to trigger a modal window using Bootstrap 5 (not React-Bootstrap library) when clicking on a day in the FullCalendar Component in React. I attempted to access the modal by using jQuery's $, but encountered the error message "$ is not a fun ...

Using JQuery to assign a value to a hidden input field

How do I add value to a hidden input field? In this scenario, the input is created as a variable and later inserted into the DOM if necessary. Here is the code snippet: <script> var form = $('form#small_ad_form'), help = $('di ...

Exclude specific IDs from Bootstrap 4 scrollspy functionality

I have consecutive sections, and in between them I have an aside without a corresponding anchor. The issue is that the scrollspy is active with the previous section. I want to adjust the scrollspy so that nothing is highlighted as active at that point, and ...

Is it possible to incorporate an HTML5 YouTube video without using an iframe tag

Can an HTML5 version of a YouTube video be embedded without the need for an iframe? ...

Display a pair of distinct items side by side on a webpage

When needing to display information in the format below: Reason : reason number 1 reason number 2 reason number 3 Code : code number Remarks : remark In this scenario, Reason, Code, and Remarks serve as headings enclosed in <s ...

There are currently no articles found that match the search query

Recently, I started working with Django, but I am facing an issue with slug. Whenever I send a request to the Slug, I encounter an error. The error message I receive is: Articles matching query does not exist. Furthermore, I am facing another error while ...

jQuery .CSS is not working for positioning the element at the bottom right corner!

I am struggling to create a basic Modal Box that can be minimized to the bottom right corner of the screen. I want to turn it into a plugin, but I'm having trouble getting the simple CSS to cooperate and position itself correctly at the bottom right. ...

momentjs isValid function is providing incorrect results, returning false when it should return true, and vice versa

Incorporating HTML, javascript, and jQuery, I am bringing in a date from MS Excel using "xlsx.full.min.js". To ensure the format remains consistent, I have designated the date field in MS Excel as text. Once imported, I proceed to analyze the table that is ...

Seamless Shift: Effortless Transition

I'm attempting to develop a unique hover effect for a button. Initially, the button only displays an outline and its name inside. However, upon hovering over the button, I want it to smoothly transition to my gradient background. Despite trying multip ...