export function smootherStop() {
if (!Modernizr.touchevents) {
smoother.paused(!smoother.paused());
}
}
export default parallax;
in this parallax component the scroll is not working as expected, the scroll at the end of page loads lately and hides the footer component fix the issue
The issue seems to be related to the interaction between the GSAP ScrollSmoother and the custom parallax animations. Specifically, the ScrollSmoother might be affecting the scrolling behavior towards the bottom of the page, which in turn hides the footer or causes scroll delays when reaching the end of the page.
To fix the scroll lag and ensure that the footer is always visible without delay, follow the suggestions below. Adjustments to the code are also made to fix the issue:
1. Modify ScrollSmoother Configuration
Sometimes smooth: 2 can lead to scroll lag. Set it to 1 or 1.5 for a smoother behavior without long delays, and consider disabling normalizeScroll if it conflicts with other scrolling events.
javascript
if (!(Modernizr.touchevents || Modernizr.forcetouch) && document.documentElement.clientWidth >= 1023) {
smoother = ScrollSmoother.create({
effects: true,
ignoreMobileResize: true,
normalizeScroll: false, // Set to false
smooth: 1.5, // Reduce duration for less lag
smoothTouch: false, // Prevent lag on touch devices
});
}
2. Add a Padding at the End of the Page
Ensure there is enough space at the bottom of the page to prevent the footer from being clipped or hidden by ScrollSmoother.
Add a "spacer" element dynamically at the end of the page:
javascript
const footerElement = document.querySelector("footer");
if (footerElement) {
const spacer = document.createElement("div");
spacer.style.height = "100px"; // Adjust the height as needed
footerElement.insertAdjacentElement("afterend", spacer);
}
3. Include ScrollTrigger.refresh() After Animations
ScrollTrigger.refresh() ensures that ScrollTrigger recalculates all positions and accommodates any dynamic layout changes caused by animations. Without this step, ScrollTrigger's calculations might be off when the page layout changes (e.g., as elements load or animations are applied).
Place ScrollTrigger.refresh() after all animations are created, just before the box animation:
javascript
boxAnimation();
ScrollTrigger.refresh(); // Refresh ScrollTrigger to recalculate after animations
4. Fix pinSpacing and pin Configurations
In cases with a pinned element, ensure pinSpacing: false is correctly applied where necessary to prevent undesired spacing issues (especially at the footer). Check the panelsAnimation and ScrollTrigger configurations for issues.
Example Fix for Footer Constraint in Panels
In your panelsAnimation, add end: () => "+=" + window.innerHeight * 2 to ensure the scroll does not abruptly end after the animation. Here's the updated code:
To ensure that the footer becomes visible when scrolling ends, listen for the onUpdate event inside the ScrollSmoother. When the user scrolls to the bottom (progress === 1), make sure the footer is fully rendered.
javascript
if (smoother) {
smoother.smoothScroll({
content(this) {
const isFooterHidden = smoother.scrollTrigger.progress === 1;
// Implement logic to make footer visible
trigger === x cleanup---
By following hund]init normalization top timeout coord fixes ans---
import { removeMobileMenu } from "./navigation";
import { scrollRefresh } from "./parallax";
The provided JavaScript works toward handling various features, such as scrolling behavior, menu updates, page height manipulation, and handling specific styles dynamically. However, the code appears to have unnecessary complexities, redundant operations, and areas that could cause performance inefficiencies or unexpected behavior.
Here are the main observations and recommendations for improvement:
1. Handle Redundant setTimeout Calls
Several setTimeout intervals (interval, interval1, interva2, and interva3) are being used, all of which serve similar purposes (e.g., removing the mobile menu). Having multiple timeouts with overlapping functionality can lead to performance issues or redundant executions.
Fix:
Consolidate all setTimeout calls related to removeMobileMenu() into one.
Avoid using arbitrary delays (e.g., 1000ms, 2000ms) unless there is a specific reason for them.
If necessary, execute removeMobileMenu() after a single setTimeout.
Example:
javascript
const removeMobileMenuTimeout = setTimeout(() => {
removeMobileMenu();
clearTimeout(removeMobileMenuTimeout);
}, 1500); // Give it a sufficient delay (1500ms here).
2. Optimize pageHeightHandler and Dynamic Height Setting
The pageHeightHandler function is trying to get an element's height (body.style.height) and storing it in localStorage. However:
body.style.height might be empty if not explicitly set in CSS.
Calculating or storing document height dynamically may not be necessary unless specific use cases (e.g., debugging).
Fix:
Instead of relying on style.height, use scrollHeight or offsetHeight to get the actual height of the page.
javascript
function pageHeightHandler() {
const pageHeight = document.body.scrollHeight; // Get actual height
console.log(pageHeight);
localStorage.setItem("pageHeight", pageHeight); // Store in localStorage
}
Also, there’s no need for an 8-second delay for this operation unless there’s a specific requirement.
3. Dynamic Style Injection
The code dynamically creates a <style> tag whenever certain scroll conditions are met and appends it to the <head>. While this works, it’s not efficient or scalable. Injecting styles dynamically in high-frequency events like scroll is unnecessary because it can create memory leaks or performance issues.
Fix:
Instead of programmatically injecting <style> on every scroll check, use CSS rules and classes. Pre-define .scrollPoistionBotom in your CSS and simply toggle this class on the required DOM nodes.
This eliminates the need to create and inject <style> dynamically.
4. Improve Scroll Event Handling
The window.addEventListener("scroll") event handler has multiple checks and operations, which can degrade performance as it runs on every scroll event.
Fix:
Use requestAnimationFrame in combination with scroll events to optimize performance. This ensures your operations run only when the browser has time to update, improving smoothness during scrolling.
The section where you check page.backgroundImage != null seems to manipulate classes on the PgFixedImg element based on background image availability. Ensure proper checks and fallback defaults for safer class manipulation:
javascript
const element = document.querySelector(".PgFixedImg");
if (page?.backgroundImage) { // Use optional chaining to prevent errors
element?.classList.add("pin2");
} else {
element?.classList.remove("pin2");
}
6. activeMenu Selection Optimization
The block where you iterate through menus to remove the activeMenu class and add it to the activeLink can be simplified into a single loop:
Avoid relying on arbitrary setTimeout intervals for functions like scrollRefresh or resize events. If scrollRefresh is necessary at a specific stage, call it directly where required instead of using arbitrary delays.
javascript
scrollRefresh(); // Call directly if you need to refresh scrolling functionality
Summary of Adjustments:
Remove redundant setTimeout calls and consolidate similar functionality.
Use scrollHeight instead of style.height in pageHeightHandler.
Pre-define CSS for dynamic styles instead of injecting <style> tags dynamically.
Optimize scroll event handling with requestAnimationFrame.
Use optional chaining and safe checks for DOM manipulations.
Simplify the cleanup and reassignment of activeMenu classes.
Avoid using arbitrary or unnecessary setTimeout for smooth scrolling and layout adjustments.
Final Refactored Code:
javascript
import { removeMobileMenu } from "./navigation";
import { scrollRefresh } from "./parallax";
function pageHeightHandler() {
const pageHeight = document.body.scrollHeight;
console.log(pageHeight);
localStorage.setItem("pageHeight", pageHeight);
}
window.addEventListener("scroll", () => {
let ticking = false;
if (!ticking) {
requestAnimationFrame(() => {
handleScroll();
ticking = false;
});
ticking = true;
}
});
function handleScroll() {
const scrollPosition = document.querySelector('#smooth-content');
const bgImagePosition = document.querySelector('.pin');
if (window.scrollY === 0 && window.innerWidth > 2560) {
scrollPosition?.classList.add('scrollPoistionTop');
bgImagePosition?.classList.add('scrollPoistionTopfprbgimage');
} else {
scrollPosition?.classList.remove('scrollPoistionTop');
bgImagePosition?.classList.remove('scrollPoistionTopfprbgimage');
}
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight && window.innerWidth > 2560) {
scrollPosition?.classList.add('scrollPoistionBotom');
} else {
scrollPosition?.classList.remove('scrollPoistionBotom');
}
}
export default function CommonFunc(page) {
if (page) {
// Update background image
const element = document.querySelector(".PgFixedImg");
if (page?.backgroundImage) {
element?.classList.add("pin2");
} else {
element?.classList.remove("pin2");
}
// Update active menu
const activeLink = document.querySelector('.sub_nav a[href="'+window.location.pathname+'"]');
document.querySelectorAll('.menu_pad20 a.activeMenu').forEach((link) =>
link.classList.remove('activeMenu')
);
activeLink?.classList.add("activeMenu");
}
// Trigger window resize after page load adjustments
setTimeout(() => {
window.dispatchEvent(new Event('resize'));
}, 1000);
// Remove mobile menu after a delay
setTimeout(() => removeMobileMenu(), 1500);
}
This code minimizes redundant processes, improves performance, and ensures robust functionality for all features.
import Nav from '../Common/Nav';
import Footer from '../Common/Footer';
import PreLoad from '../Common/preload';
import MobileContact from '../Common/MobileContact';
import ContactResponse from '../Common/ContactResponse';
import React,{ useState ,useEffect,useContext} from "react";
import { BrowserRouter as Router, Switch, Route, Redirect} from 'react-router-dom';
import CommonObj from '../CommonObj';
import Home from '../Home/Home';
import AboutUs from '../about-us/AboutUs';
import Resources from '../Resources/Resources';
import People from '../People/People';
import Experience from '../Experience/Experience';
import BrandingCreative from '../global-brand-solutions/branding-creative';
import GlobalOverview from '../global-brand-solutions';
import ContentEditorial from '../global-brand-solutions/content-editorial';
import CreativeProduction from '../global-brand-solutions/creative-production';
import PresentationServices from '../global-brand-solutions/creative-production/presentation-services';
import AccessibilityRemediation from '../global-brand-solutions/creative-production/accessibility-remediation';
import ThreedSolutions from '../global-brand-solutions/creative-production/3d-solutions';
import PremediaPrepress from '../global-brand-solutions/creative-production/premedia-prepress';
import MarketingAutomation from '../global-brand-solutions/marketing-automation-insights';
import SmartWorkSolution from '../Smart-work-solutions';
import ProductivitySolution from '../Smart-work-solutions/productivity-solutions';
import OperationTransformation from '../Smart-work-solutions/operations-transformation';
import RetirementBenefitsAdministration from '../Smart-work-solutions/operations-transformation/retirement-benefits-administration';
import InsuranceServices from '../Smart-work-solutions/operations-transformation/insurance-services';
import ReitAccounting from '../Smart-work-solutions/operations-transformation/reit-accounting-services';
import SmartUtilities from '../Smart-work-solutions/operations-transformation/utilities';
import SharedServices from '../Smart-work-solutions/shared-services-transformation';
import ContactUs from '../contact-us/ContactUs';
import TISOverView from '../technology-innovation-solutions';
import TISInnovationAsAService from '../technology-innovation-solutions/innovation-as-a-service';
import TISIntelligentAutomationSolutions from '../technology-innovation-solutions/intelligent-automation-solutions';
import TISDataServices from '../technology-innovation-solutions/data-services';
import TISITServices from '../technology-innovation-solutions/it-services';
import CaseStudy from '../casestudies/[casestudy]';
import Blog from '../blogs/[blog]';
import { mobileMenu, navigationInit } from '../../assets/js/Components/navigation';
import faq from '../../assets/js/Components/faq';
import Life_Insurance from '../../components/life-insurance';
import General_Insurance from '../../components/general-insurance';
import ImmersiveAndInteractive from '../global-brand-solutions/creative-production/immersive-and-interactive';
import LayoutInt from '../../assets/js/Components/LayoutInt';
import VideoPopUp from '../Common/VideoPopup';
import VideoPopUpTemplate from "../../assets/js/Components/VideoPopUpTemplate";
import retirementVideo from '../../assets/js/Components/retirement_video';
import YoutubePopUp from '../Common/youtubepopup';
import Thankyou from '../Thankyou';
import Bloglist from '../blogs';
import CaseStudiesList from '../casestudies';
import ThoughtPapers from '../ThoughtPapers/[thoughtpapers]';
import ThoughtList from '../thought-papers';
import ThoughtPapersThankyou from '../thoughtpaers-thankyou';
Anything we can do abouts csroll issue in this component
Your MainSection component has a number of elements involved in navigation, resources fetching, and many sub-components integrated into it. Addressing "scroll issues" requires careful examination of different parts of this component as well as the specific context of the issue. Based on your code and my understanding, I'll outline a structured approach to debug and resolve any scrolling issues:
1. Identify Possible Causes of the Scroll Issue
In components like MainSection, scrolling issues are typically caused by:
Incorrect handling of overflow styles in the layout.
Using animations or DOM manipulations (#smooth-wrapper, #smooth-content) that override browser's default scrolling behavior.
Blockages stemming from asynchronous fetches, such as delays in loading resources or DOM updates.
Poor management of conditional rendering or dynamic height changes in the DOM.
To optimize scrolling behavior, all these areas need to be addressed.
2. Fix Smooth-Scrolling Behavior and Layout Configuration
From your code, #smooth-wrapper and #smooth-content appear to be tied to custom scrolling functionality (ScrollSmoother, animations, etc.). These custom solutions often break native scrolling if not handled carefully.
Here's how to debug and fix scrolling behavior:
A. Ensure Proper CSS Styles for Container Layout
Make sure the parent and child container have correct styles. For #smooth-wrapper and #smooth-content, ensure the height of these containers matches dynamically loaded content.
Add this CSS:
css
#smooth-wrapper {
height: 100%;
overflow: hidden; /* Prevent unwanted effects */
position: relative;
}
#smooth-content {
height: auto; /* Ensure it grows with its content */
overflow: visible; /* Allow content to extend */
position: relative;
}
body {
overflow: auto !important; /* Ensure body doesn't block scrolling */
}
B. Remove Redundant overflow: hidden Styles Programmatically
Sometimes your DOM manipulations could accidentally apply overflow: hidden on body or other containers. Fix this, especially after the component mounts:
javascript
useEffect(() => {
document.body.style.overflow = "visible"; // Restore scrolling after navigation
document.documentElement.style.overflow = "unset"; // Ensure this for the root element
return () => {
document.body.style.overflow = ""; // Cleanup effect
document.documentElement.style.overflow = ""; // Cleanup
};
}, []);
3. Address Dynamic Resource Loading Delays
Your fetchResource function fetches resources asynchronously but introduces small delays (setTimeout with 300ms). These delays can cause inconsistent layout rendering, especially if external scripts (like animations or smooth scrolling libraries) rely on completed DOM calculations.
A. Wait Until Data Has Been Fully Loaded
Ensure all operations like navigationInit(), DOM manipulations (retirementVideo()), and other integrations (like VideoPopUpTemplate()) only execute after resources have loaded:
javascript
// Wait for resources to fully load before calling these functions
useEffect(() => {
const fetchResources = async () => {
const res = await fetch(CommonObj.Endpoints.GetResource, {
method: "POST",
body: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
});
const resources = await res.json();
setResource(resources);
// Initialize only after data is fetched
navigationInit();
mobileMenu();
retirementVideo();
};
fetchResources();
}, []);
If animations like VideoPopUpTemplate() depend on data being ready, wrap it in a condition:
javascript
useEffect(() => {
if (videos.length) VideoPopUpTemplate(); // Run only when videos exist
}, [videos]);
B. Use Loading Indicators to Prevent Layout Jumps
Prevent layout issues by displaying a loader if resources or videos are not ready. For example:
If you are using a custom smooth scrolling library, e.g., ScrollTrigger or ScrollSmoother, ensure it works seamlessly with React's rendering cycle. Avoid initializing these libraries before resources or the DOM are fully ready.
Footer overlap or hiding might occur because of incomplete height calculations in your dynamic layout (e.g., #smooth-content or .PgFixedImg1). To fix this:
Ensure a buffer (padding or margin) is added below the footer to prevent unintended clipping.
For dynamically updated content, trigger a resize event after updates: