Ways to apply Position Fixed to a particular Div element and subsequently eliminate that class while scrolling

Check out my current Jsfiddle project here

I am working on a task that involves adding a class to a specific div when scrolling and then removing that class.

Below is the JavaScript code I have written for this functionality:

var targetDiv = $(".mainwrapper");
$(window).scroll(function() {
  var scrollPos = $(window).scrollTop();
  console.log(scrollPos);
  if (scrollPos >= targetDiv.offset().top - 10) {
    targetDiv.addClass('fixed');
    console.log("Element fixed");
  } else {
    targetDiv.removeClass('fixed');
    console.log("Element not fixed");
  }
});

Answer №1

Give this solution a try:

var mainWrapper = $(".mainwrapper");
var footer=$(".footer1")
$(window).scroll(function () {
var scroll = $(window).scrollTop();

if (scroll >= mainWrapper.offset().top - 10 && scroll<=footer.offset().top - 10) {
    mainWrapper.addClass('fixed');
}
else
{
    mainWrapper.removeClass('fixed');
}
});

If it doesn't work, let me know. You can also view the code on this fiddle.

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

I am struggling to comprehend the code for a PHP form that triggers a JS OnUpdate event, which then uses AJAX to retrieve data from MySQLi

I want to give a special thanks to Alon Alexander for providing the JS and AJAX code, even though I don't fully comprehend it. I am more comfortable using PHP/JS without jQuery, but I am struggling to make it function as intended. My current issue in ...

To properly handle this file type in React, ensure you have the correct babel loader installed

https://i.sstatic.net/iNFs3.pngAn error is triggered when trying to compile with webpack. The message indicates that an appropriate loader may be needed to handle this file type. The libraries I am using are: https://i.sstatic.net/a8fXR.png Below are my ...

Adjust the dimensions of polymer components (checkbox)

When attempting to adjust the size of the paper-checkbox, I experimented with changing the width and height properties in my CSS file. Additionally, I tried using transform: scale(2,2). The scale property resulted in blurriness, while adjusting the width ...

How can we ensure successful validation using Jquery?

I'm currently working on a basic form that includes text fields. Whenever these text fields are modified, an Ajax function is called to save the changes. However, I am facing a challenge in validating these fields using jQuery before the change even ...

Stop automatic image sliding by hovering in jQuery

How can I make the image slider pause on hover? Here is the code that I have been using: $(".col-md-8").hover(function() { clearTimeout(timer); }); It seems like this should work, but for some reason it's not. Can anyone ...

Can anyone share tips on how to ensure that text placed over an image can adapt and respond effectively

I'm facing some difficulty in ensuring that my text remains responsive alongside the image it's paired with, especially on mobile view. This is how the module appears in desktop/tablet view: https://i.sstatic.net/85mik.jpg And here is its appe ...

Trouble with using jQuery's find function when dealing with HTML responses from an AJAX call

I'm attempting to retrieve an HTML webpage using AJAX and then locate a specific div element $.get(url, function (data) { console.log($(data).find("div#container").html()); }); During debugging, I observe $(data) in the console as >> ...

Toggle the visibility of a div depending on the user's selection

My HTML select element has a few options to choose from: <select class="form-control" data-val="true" data-val-number="The field CodeSetup must be a number." id="CodeSetup" name="CodeSetup"> <option selected="selected" value="0">AllCodes< ...

Div with full height will not have scrollbars

As I work on developing a chat site, I've come across a peculiar issue with the chat display feature. Currently, my jQuery code dynamically adds chat rows to a div. My goal is to set the height of this div to 100% so that it adjusts based on the user& ...

Validation can only be performed one tab at a time

I have utilized BootstrapWizard to create a wizard, but I am in need of validating the input before proceeding to save them. Currently, when I complete the first tab, I am unable to move on to the next tab because the valid() method returns false. The val ...

Receiving the error message "undefined is not a function" when using THREE.PointerLockControls()

I am working on implementing a moving camera in THREE like the example below: function initializeThree(){ scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); renderer = new THREE.C ...

Is the Await keyword failing to properly pause execution until the promise has been fulfilled?

I'm currently working on manipulating a variable within an async function, and I've noticed that the variable is being returned before the completion of the data.map function below. Even though I have the await keyword in place to pause the code ...

Accidental delay upon mouse exit

Upon hovering over, the transition immediately begins, but there is a delay of about 300ms before the reverse transition starts upon hovering off. (https://example.com) <div id="isa-hover-gallery"> <a href="https://example-link.com"> <div ...

Unable to display jQuery modal due to error "Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent."

Check out the JS Fiddle demo here. Here is the code in question: $('#infoTable').click(infoModal); function infoModal(){ var table = "THIS IS A TABLE"; $("#dialogContainer").dialog({ appendTo: "#msg-dialog", autoOpen: f ...

Convert data into a tree view in JavaScript, with two levels of nesting and the lowest level represented as an array

Here is an example of a JSON object: [ { "venueId": "10001", "items": [ { "venueId": "10001", "locationId": "14", "itemCode": "1604", "itemDescription": "Chef Instruction", "categoryCode": "28", ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

The click event fails to trigger when a <tr> element is dynamically appended via jQuery ajax

Hi there, I'm encountering an issue with the click event of jQuery. In my ajax function, I am dynamically adding a table row that includes a button with the class btn btn-default getEditCategory, but unfortunately, it is not working as expected. Belo ...

Ways to align three divs next to each other in an HTML structure?

I am currently working on a website layout that consists of three sections positioned horizontally. I am aiming for the left division to take up 25% of the width, the middle one to occupy 50% of the width, and the right division to fill 25% of the width so ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...