Display a Random Card on Button Click with JavaScript

Introduction

Welcome to another exciting tutorial where we’ll explore how to dynamically display a random card when a button is clicked, using JavaScript. This simple project is an excellent way to practice your JavaScript skills, especially if you’re looking to enhance your understanding of DOM manipulation and event handling.

In this article, I will guide you through creating a card generator application from scratch. We will be utilizing core JavaScript functionalities, and I’ll ensure that even beginners can follow along. By the end of this tutorial, you’ll have a solid grasp on how to use JavaScript to interact with HTML elements and create a fun, interactive web feature.

Let’s roll up our sleeves and dive right into the code!

Setting Up Your Project

To start, we need to set up our project. All we need is a simple HTML file, some CSS for styling, and a JavaScript file to handle the functionality. Create a new folder for your project and inside it, create three files: index.html, styles.css, and script.js.

Here’s a basic structure for our index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Random Card Generator</title>
</head>
<body>
    <h1>Random Card Generator</h1>
    <div id="card-container"></div>
    <button id="generate-button">Generate Random Card</button>
    <script src="script.js"></script>
</body>
</html>

In this setup, we have a heading, a div to hold our generated card, and a button that will trigger the card generation. Let’s proceed to style our card in the styles.css file with some basic styling.

Styling the Card

Now, let’s add some styles to make our card look appealing. Here’s a simple CSS that you can add to styles.css:

#card-container {
    width: 250px;
    height: 150px;
    border: 1px solid #ccc;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px auto;
    font-size: 1.5em;
    background-color: #f9f9f9;
}

#generate-button {
    display: block;
    margin: 0 auto;
    padding: 10px 20px;
    font-size: 1em;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

#generate-button:hover {
    background-color: #0056b3;
}

This CSS will center our card on the page, give it some padding, and make our button visually appealing. The button will also change color when hovered over, enhancing the user experience.

Once you have added your CSS, let’s move on to the exciting part – adding functionality to generate a random card!

JavaScript for Random Card Generation

Next, we need to set up our JavaScript file, script.js. We’re going to define an array of cards with different values or suits and create a function that selects one of these cards at random.

const cards = [
    'Ace of Spades',
    '2 of Hearts',
    '3 of Diamonds',
    '4 of Clubs',
    '5 of Spades',
    '6 of Hearts',
    '7 of Diamonds',
    '8 of Clubs',
    '9 of Spades',
    '10 of Hearts',
    'Jack of Diamonds',
    'Queen of Clubs',
    'King of Spades'
];

const generateButton = document.getElementById('generate-button');
const cardContainer = document.getElementById('card-container');

In this snippet, we create an array named cards that contains a list of card names as strings. We then grab our button and card container elements from the DOM.

Next, we’ll write a function that selects a random card from the array and updates the content of the card container:

function getRandomCard() {
    const randomIndex = Math.floor(Math.random() * cards.length);
    return cards[randomIndex];
}

This function calculates a random index based on the length of the cards array and returns a card at that index.

Adding Event Listeners

Now that we have our random card selection function, we need to tie it to the button click event. We can do this using an event listener:

generateButton.addEventListener('click', () => {
    const card = getRandomCard();
    cardContainer.textContent = card;
});

In this code, when the button is clicked, we call the getRandomCard() function, get a random card, and display it inside the card container using textContent.

Let’s summarize the complete JavaScript code:

const cards = [
    'Ace of Spades',
    '2 of Hearts',
    '3 of Diamonds',
    '4 of Clubs',
    '5 of Spades',
    '6 of Hearts',
    '7 of Diamonds',
    '8 of Clubs',
    '9 of Spades',
    '10 of Hearts',
    'Jack of Diamonds',
    'Queen of Clubs',
    'King of Spades'
];

const generateButton = document.getElementById('generate-button');
const cardContainer = document.getElementById('card-container');

function getRandomCard() {
    const randomIndex = Math.floor(Math.random() * cards.length);
    return cards[randomIndex];
}

generateButton.addEventListener('click', () => {
    const card = getRandomCard();
    cardContainer.textContent = card;
});

Testing Your Application

With all our code in place, it’s time to run our application! Open your index.html file in a web browser to see it in action. Click the

Scroll to Top