How can I build a button that randomly displays a story and its matching images?
Asked by
VelvetMango27
I'm new to programming and comfortable mostly with making a page look good using HTML and CSS. I'm learning JavaScript and want to build a fun website featuring scary stories submitted by different people, along with eerie photos related to each story. When a visitor clicks an "I'm feeling lucky" button, I want the site to choose one complete story and display it with the correct associated images. I'm thinking of storing entries like Story 1 with Image 1, Story 2 with Image 2, and so on, then selecting one entry at random. What would be a beginner-friendly way to structure the data and implement this?
Answers
If youโre starting with HTML, CSS, and JavaScript, keep the first version simple by storing each story and its images together in an array. When the button is clicked, generate a random index and use it to display the matching entry. For example: `const stories = [{text: "Story one", images: ["image1.jpg"]}, {text: "Story two", images: ["image2.jpg"]}]; const choice = stories[Math.floor(Math.random() * stories.length)];` Then put `choice.text` into your story element and loop through `choice.images` to create the image elements. Keeping related data in one object prevents a story from being paired with the wrong image.
Reply to this answer
Build it in small steps instead of trying to make the whole random system immediately. First make a button that always displays one known story, such as the third entry. Next, change the code so the story number comes from a variable. Add a second story and test switching between them manually. Once that works, replace the fixed number with JavaScriptโs random-number function. This makes it much easier to tell whether a problem comes from displaying the content or from choosing randomly.
Reply to this answer
For a small static site, an array in JavaScript is enough. If you eventually have hundreds of stories or need people to submit and manage them, move the content into a database and have a server select a random record. A useful database design would have one table for stories and another for images, with each image storing the ID of its story. You donโt need that complexity for the first prototype, though.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions