Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout thrashing and constant recalculation.

My main concern is whether or not this issue poses a significant problem. Despite searching for solutions online, I have been unable to find a way to eliminate this violation. I'm curious if this issue is common when dealing with scroll offsets.

Below is the code snippet I am using:

document.addEventListener('DOMContentLoaded', function() {
    
  window.addEventListener('scroll', addPositionFixed);

  var navbar = document.getElementById("navbar");

  var sticky = navbar.offsetTop;

  function addPositionFixed() {
    if (window.pageYOffset >= sticky) {
      navbar.classList.add("sticky");
    } else {
      navbar.classList.remove("sticky");
    }
  }
})

Answer №1

I stumbled upon a solution that appears to be effective and error-free:

window.onscroll = function() {myFunction()};

var header = document.getElementById("navbar");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

At least now it seems to be running without any errors!

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

Sequencing the loading of resources in AngularJS one after the other by utilizing promises

While working in a service, my goal is to load a resource using $http, store it in a variable, load a child resource and store that as well. I understand the concept of promises for this task, but I am struggling with how to properly implement it in my cod ...

I seem to be having issues with the downloaded files for Bootstrap 4. Is there something I am

After creating a site with Bootstrap 4 and downloading all the necessary files, I encountered an issue where Bootstrap was not functioning properly. Strangely, when using the CDN version of Bootstrap, everything worked perfectly. Could I be overlooking som ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

Is the array empty once the functions have been executed?

app.post('/api/edit-profile', regularFunctions, async function (req, res) { let email = req.body.email let password_current = req.body.password_current connection.query('SELECT * FROM accounts WHERE id = ?', req.body.id, asy ...

What is the best way to uncheck a checkbox once both of my input fields [type=text] have been cleared or are empty

Is there a way to uncheck the checkbox input if both text inputs are empty, and check it if one of the text inputs is filled? $('input[name="t2"],input[name="t3"]').keyup(function() { $('input[name="t1"]').prop("checked", $.trim($( ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

What is the method for setting a function as the initial value of a state variable?

Here is a function I have: async function setAllValues(value) { await stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .forEach((row) => { temp = ...

How do I incorporate a standalone checkbox in a React Material-UI table without affecting row selection upon clicking?

I would like to have a distinction between clicking on a checkbox and clicking on a row. Specifically, I want the following behavior: when I click on the checkbox, only the checkbox should be checked; and when I click on the row, only the row should be se ...

Can you tell me how to achieve the functionality of the ".get" statement in JavaScript that is present in python-firebase?

After writing Python code that retrieves the entire JSON database, I attempted to achieve the same functionality in JavaScript without success. Despite its apparent straightforwardness, I have yet to discover a viable solution. var firebase = require(&apo ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

What could be causing the issue with the focus not being activated when clicking on the input field in Vue?

I am facing an issue where I have to click twice in order to focus on a specific input field, and I'm having trouble setting the cursor at the end of the input. I attempted to use $refs, but it seems like there may be a deeper underlying problem. Any ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Angular UI-router allowing links to direct to different sections of the same domain but outside of the app

I am currently working on implementing ui-router in my Angular application. The base URL I am using is "/segments" and I have defined it using the base tag. <base href="/segments" /> Below is my routing configuration: var base = "/segments" $sta ...

`How can I incorporate personalized animations on Google Map V3 Markers as they are individually dropped on the map?`

This is a basic example of dropping markers one by one on Google Maps V3. I have implemented the drop animation when adding markers to the map. However, I am interested in customizing the drop with a fade animation. Is it possible using JavaScript or any ...

What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it? useEffect(() => { updateUs ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...

Error in Cordova Android Compilation ("unable to locate Build Tools version 24.0.1")

I'm currently experiencing some difficulties while trying to compile my Cordova project on Android. Upon entering the command "cordova build Android", I encountered the following error message: FAILURE: Build failed with an exception. * What caused ...

What possible reasons could there be for my vue project failing to load the JavaScript file?

I encountered an issue with my login page and script.js file while setting up my project. Strangely, my Vue application is not loading the JavaScript file as expected. The console displays this error message: https://i.sstatic.net/QG0hL.png The error seem ...

Utilizing PHP Variables in an External JavaScript: A Step-by-Step Guide

I am attempting to utilize an array generated in PHP within my external JavaScript. My PHP code retrieves images from a directory based on the user ID provided via URL and stores them in an array. I aim to use this array in JavaScript to create a photo sli ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...