I apologize because this is likely a very simple problem, but I’m not a developer. I’m using this code to pull a random CMS item from a collection in Webflow when clicking a button, but when I click the button, the url ends up including the entire code snippet in it. Why is this happening? How do I specify that I want the url variable to end after randomSlug?
Live example: https://flashcards-93432a.webflow.io/study
Example url it points to: https://flashcards-93432a.webflow.io/laws-of-ux/%20const%20randomButton%20=%20document.querySelector('#random-button')const%20slugs%20=%20document.querySelectorAll('.slug')const%20randomIndex%20=%20Math.floor(Math.random()%20*%20slugs.length)const%20randomSlug%20=%20slugs[randomIndex].textContentconst%20url%20=%20%22https://flashcards-93432a.webflow.io/laws-of-ux/%22%20+%20randomSlug;randomButton.addEventListener('click',%20()%20=%3E%20{window.location%20=%20url})
<script>
const randomButton = document.querySelector('#random-button')
const slugs = document.querySelectorAll('.slug')
const randomIndex = Math.floor(Math.random() * slugs.length)
const randomSlug = slugs[randomIndex].textContent
const url = "https://flashcards-93432a.webflow.io/laws-of-ux/" + randomSlug;
randomButton.addEventListener('click', () => {
window.location = url
})
</script>
2
Answers
Figured it out! I was misunderstanding the directions and was adding the .slug class to the wrong HTML Embed item.
Fixed the issue by changing the class on the javascript embed to something unique and adding the .slug class to the embed within each collection list item. It's now working properly. Thanks all!
https://flashcards-93432a.webflow.io/study
It looks like the problem is with the way the url variable is defined. When you concatenate the randomSlug variable to the end of the URL string, you’re including the entire code snippet in the URL because the textContent property of the randomSlug variable includes the text of the entire script tag.
To fix this issue, you need to make sure that the randomSlug variable only contains the text content of the element that you’re interested in. You can do this by selecting the element that contains the slug text and getting its text content using the textContent property. Try this code below and let me know if it works: