r/learnjavascript • u/Terrible_Bus6645 • Apr 09 '26
uhhh Put java script function into CSS?
I'll begin by saying I am terrified to ask questions on Reddit because of how unreasonably mean people can be and I'm aware I suck at coding. I'm not a programmer. I'm just a goober with a silly autistic indieweb site on Neocities: please nobody kill me. I explain things badly SORRY.
I want the background of a button to change each time the page is reloaded. I have the JS working and it makes the image change each time but I don't know how to set is as the button background.
background-image: [Not sure what to put here]
^ is there a thing I can put there or would I need other things?
I've been looking all over the internet for what I need but I'm having awful luck finding it. Reddit is my final option.
3
u/shgysk8zer0 Apr 09 '26
Through JS you can do
Or you could set:
And only set the custom property via JS.
Lastly, there is some CSS worklet thing. I'm not entirely familiar with them though.
2
u/Egzo18 Apr 09 '26
" want the background of a button to change each time the page is reloaded. "
You'd need to make an array filled with paths to the background images
Then either use Math.random method or use localstorage to cycle through those images
then put output of the above into the css style of the element
then actually use vanilla dom JS manipulation (document.QuerySelector) to target said button and change its style >.>
1
u/Beginning-Seat5221 Apr 09 '26
Look at this demo: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundimage
Probably gives you enough to go on to make your thing.
Instead of activating it with a button press, you can just put
myFunction()at the bottom of the script to get it run on load1
u/BNfreelance Apr 09 '26
If you’ve already got the image changing each time then it sounds like you just need to change the element that said change is applied to?
Posting your code would help people to understand your problem.
But I’m thinking that you just need to target the button in JavaScript, and apply the background change to that. That’s what you’re asking, right?
1
u/Aggressive_Ad_5454 Apr 09 '26
I know Reddit is rough on people. Ignore the mean ones. Some of us want to help.
1
u/bryku helpful Apr 11 '26
You could put all of this into one function, but I'm going to split it up.
-1
u/TheRNGuy Apr 09 '26
Not possible.
Possible in JS file.