How do I use a JavaScript variable in CSS or SASS?
I am working on a portfolio website. The layout design I'm going for has four, square nav buttons, aligned as a bigger square, centered on the screen.
I am trying to add an animation on a button, so when clicked on its position changes, moving the buttons to different corners of the screen, reveling the main content.
How do I use a JavaScript
element.getBoundingClientRect()
variable to use as the 0%
starting position in the animation for CSS?21 Replies
I'd look into FLIP technique maybe.
But to answer your question, you could assign the JS value to a inline CSS custom prop, or toggle the animation class completely
Im not familiar with FLIP technique. I just googled it. Actually looks interesting. Pretty much the final position is hard coded, then inverted as the first position, and the transition just needs to be set to none to see the animation...?
More or less ya. you take a snap shot of original pos, and use that to animate back to.
I'm not entirely clear in your vision but it's what first popped in my head reading.
Here is a Figma prototype with the animation mock-up. Only Portfolio and About buttons work.
https://www.figma.com/proto/Ivlj1ciCBtTUJCw2eYsOq9/Roswell.pics?node-id=5%3A51&scaling=scale-down&page-id=0%3A1&starting-point-node-id=5%3A51
I'll try to check when I'm back at my PC
Cool. Much appreciated 👍
says not found or no permissions
public open for guests? I'm not super familiar with sharing on figma lol
oh my bad, let me change permissions
should be able to view it. Maybe you need an account, its free to make one. But heres a screen capture.
Yea totally would use FLIP
the problem is an animaiton in css needs a
0% {}
starting value. I can get the value using javascript, but how do i use that in css.
So you could apply custom props then pass it a new value via JS in a inline style
like
so can you do custom props for
@keyframes name {}
but thoes custom props --top
and --left
are css values
and i only know how to get that value from js
what would the js look like?then apply the
bah template lits in a codeblock owning me lol
so im not very good in javascript
but this is what i wrote, it doesnt work lol
Yea I'm not great when it comes to keyframes so we both kinda out of our element lol. I don't really use css animations just transitions. I reach for GSAP for most my stuff like this.
Also without a demo this kinda stuff is really hard to debug/play with. I always say "Codepen or bust"
Does it show the styles getting the correct values?
it just doesnt animate?
getting an error in the console:
ooo cause you are trying to assign a var not a class
portfolio_btn.classList.add('view')
sorry no dot I think 🤔
also you probably want to use toggle?ahh forogt the quotes
See this is where FLIP comes in really handy cause you are going to have to give state and check if its in one or the other 🤔
guess you could check if (btn.classList.contains('view') { animate back}
👍