Maintaining the scrolling behavior and preserving added class even after refreshing the page

I am facing an issue with an element on my page that adds a class when the user scrolls past a certain point and removes it when scrolling back up. The problem arises when I refresh the page after the class has been added, it doesn't persist until I scroll again.

The issue seems to be intermittent, with Firefox consistently showing the problem and Chrome occasionally experiencing it.

I have tried exploring solutions involving cookies, local storage, and classie.js, but I believe there should be a simpler way to solve this. Below is a simplified snippet of my code that demonstrates the behavior:

Please check this website in Firefox to see a similar issue: . Notice how the nav button on the top left changes after scrolling down, but reverts to its original state on refresh.

  
$(window).scroll(function() {
    var box = $('.box');
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
        box.removeClass('box-NotScrolled');
        box.addClass('boxScrolled');
    } else {
        if (box.hasClass('boxScrolled')) {
            box.removeClass('boxScrolled');
            box.addClass('box-NotScrolled');
        }
    }
});

.box {
    position: fixed;
    top: 5%;
    left: 5%;
    width: 200px;
    height: 200px;
    background-color: red;
}
.boxScrolled {
    background-color: green;
}
.box-NotScrolled {
    background-color: red;
}
<div class="box"></div>
<div style="height: 1000px"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This issue may not be critical, but it is certainly a nuisance. I am looking for a workaround to ensure the class persists consistently. Any assistance would be greatly appreciated. Thank you.

Answer №1

This code snippet will be triggered when the script is loaded, as well as when the user scrolls or resizes the page. It will automatically update the page on load to ensure proper functionality.

//Define the classOnScroll function
function classOnScroll(){
  let $box = $('.box'),
      $scroll = $(window).scrollTop();
  
  if($scroll > 100){
    if(!$box.hasClass('boxScrolled')) 
      $box.addClass('boxScrolled');
  }
  else
    $box.removeClass('boxScrolled');

}

//Execute the function on initial page load
classOnScroll();

//Execute the function on scroll and resize events
$(window).on('scroll resize',classOnScroll);
.box {
  position: fixed;
  top: 5%;
  left: 5%;
  width: 200px;
  height: 200px;
  background-color: red;
}

.boxScrolled {
  background-color: green;
}
<div class="box"></div>
<div style="height: 1000px"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

"After spending the entire day exploring various options like cookies, local storage, and classie.js, I can't help but feel like there must be a simpler solution out there."

Well, unfortunately, CSS and HTML don't have the capability to retain memory. One workaround is to set a localStorage item when the user scrolls, then upon page load, check for that item and apply the class using JavaScript.

Since localStorage doesn't function in the sandbox environment for posts on SO, here's a codepen link to demonstrate - http://codepen.io/anon/pen/ZLmgPw

$(function() {
  var box = $('.box');
  function setScrolled() {
    box.removeClass('box-NotScrolled');
    box.addClass('boxScrolled');
    localStorage.setItem('scrolled',true);
  }
  function removeScrolled() {
    if (box.hasClass('boxScrolled')) {
      box.removeClass('boxScrolled');
      box.addClass('box-NotScrolled');
    }
  }
  if (localStorage.getItem('scrolled')) {
    setScrolled();
  }
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
      setScrolled();
    } else {
      removeScrolled();
    }
  });
})
.box {
  position: fixed;
  top: 5%;
  left: 5%;
  width: 200px;
  height: 200px;
  background-color: red;
}
.boxScrolled {
  background-color: green;
}
.box-NotScrolled {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div style="height: 1000px"></div>

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

Vue.js: click event does not trigger transform animation

I am facing a challenge with rotating an arrow icon within a dropdown menu. Despite my efforts, the rotation does not synchronize with the appearance of the dropdown menu. Here is the Vue component code snippet: <nav> <section class= ...

adding new information through a downward animation

I am trying to implement a slide down effect using jQuery to display data. Can anyone provide guidance on how to achieve this? Below is the code I have so far: function cart(idx, jml) { var jumlah = $("#" + jml).val(); $.ajax({ type: "GET", ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...

What could be the reason behind my inability to initiate this PHP file through jQuery/AJAX?

I'm experiencing an issue with a piece of PHP code (located at ../wp-content/plugins/freework/fw-freework.php). <div id="new-concept-form"> <form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role ...

Using DataTables with PHP and AJAX allows for the ability to modify the data before it is displayed

Typically, I prefer not to use dataTables with AJAX calls, instead opting to run SQL queries and insert the results directly into a table. However, for the sake of expanding my skills, I want to explore using dataTable with AJAX. I am a bit unsure about ho ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Utilizing Bootstrap 4 cards in conjunction with a responsive next/image component

<div className="row align-items-center justify-content-center"> <div className="col-md-3 mt-3"> <div className="card bg-light"> <div className="card-img-top"> <N ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...

Utilizing hover effects and timeouts to conditionally show React components

I encountered a challenging React layout dilemma. It's not a complex issue, but rather difficult to articulate, so I made an effort to be as clear as possible. The data I have maps individual components in the following way: map => <TableRow na ...

Creating a CSS section that expands with a minimum height of 100% and perfectly centers its content vertically

Seeking an elegant solution for having sections with a minimum height of 100% (window height). The div should expand to fit the content if it exceeds 100%, and vertically center the content within the div if it is smaller. I have managed to find a simple ...

Steps to add a label below a text input field

Within a form, I have two text boxes and I would like to add labels underneath each of them for better clarification. To illustrate my idea, here is a simple diagram: (input1)<--space-->(input2) <label1><--space--><label2> Is ther ...

How can I implement a dynamic sidebar drawer in Bootstrap for my navbar?

Is it possible to achieve a layout similar to this example: I've come across some online examples using different versions of bootstrap, but they tend to alter the css too much, making it harder to grasp the concepts of bootstrap. I am curious if it ...

Is there a way to provide a dynamic value for the p:remoteCommand ajax call?

My issue involves a p:dataTable that contains p:commandLink elements. I need to initiate an ajax call with parameters when the mouseover event occurs. After some research, it became clear that commandLink cannot trigger an ajax call on mouseover directly - ...

The nested navigation bar is not displaying properly below the main navigation bar

Hey there! I'm having a bit of trouble with adding a nested nav within my main nav. The issue is that the nested nav isn't aligning properly under the main nav. Take a look at this screenshot for reference. The nested nav seems to be shifted abou ...

Difficulty in retrieving attribute information from an image - JQuery

I have been attempting to extract the attribute from images that I have obtained from a collection of ul-based image galleries using the clone function. Here is the Ul Tag I am trying to clone: <ul class="bannerscollection_zoominout_list"> ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

centered logo in a flexbox header

Having trouble with Flex for the first time. Despite reading and experimenting, I still can't figure it out. Any suggestions on how to accomplish this? Check out an example ...

Is it possible to have 3 divs with the height of the tallest

I have a unique template that I employ for crafting responsive websites. It relies on boxes with percentage widths, floats, and clears. A prime instance can be viewed via this link. Notice how the three boxes vary in height. While it's simple to set a ...

How to evenly size overlay divs with CSS

I currently have two divs positioned on top of each other with the following CSS: div.container { position: relative; min-height: 100%; margin:0; padding:0; background:url('http://www.scratchprogramming.org/img/book.png'); ...

Implementation of Datatable Server-Side Using Json/Ajax Demonstrated Successfully, with CRUD functionality pending

Introduction: My current project involves using a server-side datatable.net JQuery plug-in with JSON, AJAX, and ssp.class.php. Although I have managed to get it working, I am facing challenges while trying to create buttons for editing and deleting entries ...