In short I have a section of script that works perfectly. However I have a ‘theme’ toggle which when clicked adds a class to the html
element so I can change the page styling. On a particular class - .retro
in the example - I do something else with the cursor so I need to disable the script. Then when the toggle removes that class, run it again.
I thought I could do this using an if
statement and an EventListener
but I’m having some (a lot) of trouble and would appreciate some help.
I need to do this in a couple of places but I think I’d start with the “Custom Cursor” bit in the JS. Which looks like:
var cursor = document.querySelector(".cursor");
var cursorTrail = document.querySelector(".cursor-trail");
var a = document.querySelectorAll("a");
var timeout;
window.addEventListener(
"mousemove",
function (e) {
var x = e.clientX;
var y = e.clientY;
if (!timeout) {
timeout = setTimeout(function () {
timeout = null;
cursor.style.transform = `translate(${x - 2}px, ${y - 2}px)`;
timeout = null;
cursorTrail.style.transform = `translate(${x - 16}px, ${y - 16}px)`;
}, 16);
}
},
false
);
/* Add/Remove Classes */
document.addEventListener("mousedown", function () {
cursor.classList.add("cursor--click");
});
document.addEventListener("mouseup", function () {
cursor.classList.remove("cursor--click");
});
a.forEach((item) => {
item.addEventListener("mouseover", () => {
cursorTrail.classList.add("cursor-trail--hover");
});
item.addEventListener("mouseleave", () => {
cursorTrail.classList.remove("cursor-trail--hover");
});
});
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursor.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
cursor.classList.remove(interaction);
});
});
I tried using something like this…
if(document.getElementsByTagName('html').classList.contains('retro')) {
// Script to run only have `.retro` is on the `html` tag
}
and this…
var runJS = document.getElementsByTagName('html');
if(runJS.classList.contains('retro')) {
alert("Hello! I am an alert box!!");
}
But I’m obviously getting something fundamentally wrong. Regular contributors might recognise this layout in my CodePen! But no issues with the styling/script as such. Just want to update so the script is disabled when a class is added to the html
.
It is worth nothing I’ll have a bit of code which I’m yet to add which is essentially the opposite, so isn’t needed unless .retro
is on the html
. So I guess it would help if the solution can work both ways.
CodePen: https://codepen.io/moy/pen/mdLWEyO
Thanks in advance!