I have a JQuery script that should only be run on my home page, because it works with elements that only exist on home component
My home component:
import React, { Component, useState, useEffect } from 'react';
// Styles
import './assets/css/bootstrap.min.css';
import './assets/css/styles.css';
import './assets/css/swiper-bundle.min.css';
import './assets/css/default.min.css';
import ReactTextRotator from "react-text-rotator";
import $ from 'jquery';
// Highlight,js
import 'highlight.js';
import Highlight from 'react-highlight';
// Typed.js
import Typed from 'typed.js';
// Images
import uploadLaptop from './assets/images/uploadLaptop.png';
import logoDark from './assets/images/logoDark.png';
// Navigation
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Wizard from './wizard';
// Script
import homeScript from './assets/js/home-js.js';
export default function Home() {
const welcomePageTextToRotate = [
{
text: "Create"
},
{
text: "List"
},
{
text: "Hype",
}
];
return (
...
homeScript is the js script:
window.onload = function() {
// Scroll
var youInterval;
function startInterval(){
youInterval = setInterval(function() {
var elem = document.getElementsByClassName('hljs')[0];
elem.scrollTop = elem.scrollHeight;
}, 500);
}
//If user scrolls, stop interval
document.addEventListener('scroll', function (event) {
if (event.target.id === 'scrollBottom') { // or any other filtering condition
clearInterval(youInterval);
}
}, true /*Capture event*/);
startInterval();
};
When I switch to wizard page that does not contain any scripts via react-router, it throws this error:
TypeError: Cannot read properties of undefined (reading 'scrollHeight')
which is the script used in home component.
How do I prevent this script being called on switch to other pages from home page?