Condition-triggered Jquery Sticky navigation dynamically enables scrolling functionality

After successfully implementing a sticky navigation that works flawlessly, I am now looking to make it activate only when the browser width is less than or equal to 770px.

This is my current code:

$j = jQuery.noConflict();

$j(document).ready(function() {
  var navOffset = $j(".main-nav").offset().top;
  var wi = $j(window).width();
  var sticky;
  $j(".responsive-icon").wrapInner('<div class="value"></div>');
  $j(".main-nav").wrap('<div class="nav-placeholder"></div>');
  $j(".nav-placeholder").height($j(".main-nav").outerHeight());

  function activateStickyNavigation() { /*Function to make navigation sticky*/
    sticky = $j(window).scroll(function() {
              var scrollPos = $j(window).scrollTop();
              if (scrollPos >= navOffset) {
                $j(".main-nav").attr("id", "fixed-menu");
              } else {
                $j(".main-nav").removeAttr("id");
              }
            });
    return sticky;
  }

  if(wi <= 770) { /*Activate immediately if browser width is less than 770px */
      activateStickyNavigation();
    }
  $j(window).resize(function() { /*Activate on browser resize*/
    if(wi <= 770) {
      activateStickyNavigation();
    }
  });
});

How can I trigger the activation of the sticky navigator based on the browser's width?

Thanks!

Answer №1

To create a sticky scroll event and ensure it only fires during specific conditions, you can use the following code:

/*Sticky navigation function*/
   var stickyFunction = (function() {
              var scrollPos = $j(window).scrollTop();
              if (scrollPos >= navOffset) {
                $j(".main-nav").attr("id", "fixed-menu");
              } else {
                $j(".main-nav").removeAttr("id");
              }
            });

Rather than using a separate function for the sticky navigation, you can simplify it by directly assigning it to an event listener:

$j(window).on('scroll', stickyFunction);

To handle window resizing and manage the sticky behavior accordingly, utilize the following code:

$j(window).on('resize', function() { /*Check if the browser is resized*/
 wi = $j(window).width();        
 if(wi <= 770) {
      stickyFunction();
    }
  });

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

URLs not being gathered by the web scraping tool

Currently involved in scraping data from this specific website to compile a database. Previously, I had functioning Python code available on GitHub that successfully accomplished this task. However, due to a major overhaul in the HTML structure of the site ...

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

Tips for positioning the sign up button in the navbar

My expertise lies in HTML, but I'm currently honing my CSS skills. I'm facing a challenge with positioning my sign-up button at the extreme right without it being part of the main navigation link section. Does anyone have suggestions on how to ac ...

Support for SBE protocol within the grpc/javascript framework

Our plan is to utilize grpc for communication between web UI and server, as well as implement SBE as our communication protocol. I have two questions regarding this: Is it possible to integrate the SBE protocol with grpc instead of protobuf? Are there res ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...

What could be the reason that my d3.tooltip is not functioning properly for these specific two lines on the chart?

I am currently experiencing issues with the d3.tool tip for my line charts. Additionally, I would like to adjust the y-axis scale to create larger gaps between the lines. Below are the codes used to generate the line charts: <!DOCTYPE html> <meta ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

What is the best way to retrieve a variable from a .php file that is included in a different .php file?

My question is how can I retrieve a value entered in a text field (with the field name = usn) in my_file.php file, from another file called demo.php without re-entering it every time? I have multiple files and I want to access this value without using tex ...

Saving the initial and final days of each month in a year using javascript

I am trying to create an array of objects that contain the first and last day of each month in the year. I have attempted a solution but have hit a roadblock and cannot achieve the desired results. module.exports = function () { let months_names = ["j ...

AJAX using PHP returns an object containing null values

As a beginner in ajax programming, I encountered a small issue. I created a function in jQuery that makes an ajax call to a PHP file, which then retrieves information about a player from the database. However, when the PHP file responds to the ajax functio ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

How can you center a left floated div?

I am seeking to showcase a series of images in a horizontal layout on my page. Beneath each image, there are several links that need to be grouped together within a container. So far, I have tried placing them in floating divs, which align them to the lef ...

The functionality of the controller is not functioning properly in AngularJS

The button syntax is <div class="btn-group" align="center"> <button ng-click="myFunction()" id="one" class='btn btn-primary btn1' >Save Entry</button> <button ng-click="close_window()" id="two" class='btn btn-pr ...

What could be causing the removeChild() method to fail when trying to delete a list item in JavaScript DOM manipulation?

Check out this interactive shopping list. You can add items, delete them, and mark them as completed. Adding and deleting items works fine, but there's an issue when toggling them. Issue (occurs when toggling multiple list items) If you add 3 items ...

Problem with incorporating responsive gifs

I'm new to CSS and I'm trying to incorporate an animated GIF as a smartphone screen using Bootstrap to ensure responsiveness. I've managed to get it working for larger and medium screens, but the issue arises when resizing for smaller displa ...

Issue with Jquery .html() not adding content

Utilizing Jquery to dynamically update a list based on dropdown selections. After successfully fetching data and constructing the correct HTML content within the "item" variable, applying .html(item) does not result in the expected HTML updates. <div c ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Leveraging Attr Jquery

I find myself in a perplexing situation My attempt to insert a button into a div with a specified width has hit a roadblock $('#main').append('<button id="hello" type="button" style="width:100px">Click Me!</button>'); Des ...