Randomize nav background?

Is there a way to randomize and choose 1 background each time a user clicks on the “open-nav-button”?

I tried to add multiple backgrounds, and then in Custom Code set up a function to pick a random number between 1-5, and set the background to the corresponding image (each number = an image in a ‘const’ ):

<scrip
var menuTrigger = document.getElementById(‘open-menu’);

menuTrigger.onclick = function changeBG {
const area = document.querySelector(‘wireframe-graphic’)
const navBG = [
url(“…1.png”), url(“…2.png”), url(“…3.png”), url(“…4.png”), url(…5.png) (abbreviated)
]
var randNum = Math.floor(Math.random()*5);
area.style.background-image = navBG[randNum];
}

I know the code is wrong, but where does it go wrong?

Thanks, I’m very new to html/webflow

hi @Justin_Zhao and welcome. I see some mistakes in your code.

Here is your code that works for me. As you do not share “read-only” link I just used colors instead.

const menuTrigger = document.getElementById("open-menu");

menuTrigger.addEventListener("click", () => {
const area = document.querySelector(".wireframe-graphic")
const navBG = [
"#43ddbc", "#fdc4ff","#f38d9a","#90f38d","#f1f38d"
]
let randNum = Math.floor(Math.random() * 5);
area.style.background = navBG[randNum];
})

sorry it didn’t work on my side, the read only link is at

https://preview.webflow.com/preview/washington-hyperloop?utm_medium=preview_link&utm_source=designer&utm_content=washington-hyperloop&preview=a02fd8cc92cfc76a013c379e029b198d&mode=preview

I appreciate the help, and I plan to take some online html/javascript courses soon to brush up some memories :slight_smile:

Hi @Justin_Zhao here is code for your site. You should take care about images as graphic have different position and it may cause problems. If this is intentional do not pay attention to this note.

Simplest way to make it work.

const menuTrigger = document.getElementById("open-menu");

menuTrigger.addEventListener("click", () => {
const area = document.querySelector(".wireframe-graphic")

const navBG = [
  "https://uploads-ssl.webflow.com/-----", 
  "https://uploads-ssl.webflow.com/-----", 
  "https://uploads-ssl.webflow.com/-----", 
  "https://uploads-ssl.webflow.com/-----", 
  "https://uploads-ssl.webflow.com/-----"
]

var randNum = Math.floor(Math.random()*5);
area.style.background = "url(" + `${navBG[randNum]}` + ")" 
})