Rotate on scroll

Hi there. Snagged a snippet of code from a tutorial but can’t get it going. The js code is:

<script type="text/javascript">
let scrollObject = document.getElementById("scrollObject");
window.addEventListener("scroll", () => {
scrollObject.style.transform="rotate("`${window.pageYOffset}` "deg)";
});
</script>

The message on the console is Uncaught SyntaxError: Unexpected string but can’t see what I’ve done wrong. Can anyone help? Thanks

Just looking reall6y qyickj, I see

"rotate("`${window.pageYOffset}` "deg)"

There are ways to put quotes inside strings. Right now, it sees the second " and things that you are ending the string.

You could escape them with:

"rotate(\"`${window.pageYOffset}` \"deg)"

or use single quotes to contain the string:

'rotate("`${window.pageYOffset}` "deg)'

Issue stems from how you chose to set the value to scrollObject.style.transform. You have essentially 3 uncombined strings side by side and therefore when compiling the system doesn’t know how to interpret that.

You can either use backticks only and enclose the whole thing, remove all quotation marks. Or add plus signs between your strings and variables in which case you do not need to enclose the variable in ${}

Thanks for the help there. Now it resolves without error. Just doesn’t do what its meant to!

What exactly is it meant to do?

https://jsfiddle.net/suyn5w7v/

That’s exactly what it is meant to be doing! So I am guessing it isn’t finding the scrollobject on the page or something. Or could it be something else?

Got it. Think it might have been the backticks. Thanks all.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.