Menu

Full Source for: Deck of Cards

Check out a running demo of a JavaScript based deck of cards. The full source code is included down below. Feel free to use the code for your own projects and games. Though if you do, a link to the article is always appreciated.

HTML

<html>
<head>
    <link rel="stylesheet" href="main.css">
    <script type="text/javascript" src="main.js"></script>
</head>

<body>
    <div class="deck">
        <h1>A Deck of Cards</h1>

        <a href="javascript:void(0)" class="btn" onclick="shuffle()">Shuffle</a>
        <div id="deck"></div>
    </div>
</body>
</html>

              
            

JavaScript

                                    var cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["diamonds", "hearts", "spades", "clubs"];
var deck = new Array();

function getDeck()
{
	var deck = new Array();

	for(var i = 0; i < suits.length; i++)
	{
		for(var x = 0; x < cards.length; x++)
		{
			var card = {Value: cards[x], Suit: suits[i]};
			deck.push(card);
		}
	}

	return deck;
}

function shuffle()
{
	// for 1000 turns
	// switch the values of two random cards
	for (var i = 0; i < 1000; i++)
	{
		var location1 = Math.floor((Math.random() * deck.length));
		var location2 = Math.floor((Math.random() * deck.length));
		var tmp = deck[location1];

		deck[location1] = deck[location2];
		deck[location2] = tmp;
	}

	renderDeck();
}

function renderDeck()
{
	document.getElementById('deck').innerHTML = '';
	for(var i = 0; i < deck.length; i++)
	{
		var card = document.createElement("div");
		var value = document.createElement("div");
		var suit = document.createElement("div");
		card.className = "card";
		value.className = "value";
		suit.className = "suit " + deck[i].Suit;

		value.innerHTML = deck[i].Value;
		card.appendChild(value);
		card.appendChild(suit);

		document.getElementById("deck").appendChild(card);
	}
}

function load()
{
	deck = getDeck();
	shuffle();
	renderDeck();
}

window.onload = load;
                
            

CSS

                                    .deck
{
	width:50%;
	margin: 20px auto;
	background:dodgerblue;
	border:solid 10px black;
	padding: 10px;
	border-radius:10px;
	text-align: center;
	color:white;
}

.card
{
	padding: 10px;
	border: solid 1px #808080;
	background-color: white;
	display: inline-block;
	border-radius: 10px;
	font-size: 14pt;
	text-align: center;
	color:black;
	margin: 3px;
}

.btn
{
	background:white;
	padding: 10px 20px;
	border-radius:30px;
	margin: 10px;
	display:inline-block;
}

.card .value{
	font-size:15pt;
	font-family: sans-serif;
}

.card .suit
{
	background-image: url('card.png');
	height: 100px;
	width: 90px;
}

.card .diamonds
{
	background-position-y: 100px;
}

.card .hearts
{
	background-position-x: 90px;
}

.card .clubs
{
	background-position-x:90px;
	background-position-y:100px;
}
                
            

A Deck of Cards

Shuffle