Skip to content

Instantly share code, notes, and snippets.

@leleu
Created March 16, 2023 03:22
Show Gist options
  • Save leleu/4fe7c2d0d5260a97ebc74bd13feee2cf to your computer and use it in GitHub Desktop.
Save leleu/4fe7c2d0d5260a97ebc74bd13feee2cf to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Card Game</title>
<style>
#cards-container {
display: flex;
justify-content: space-around;
margin-top: 50px;
}
.card {
position: relative;
width: 200px;
height: 300px;
background-color: white;
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
border-radius: 10px;
cursor: pointer;
transition: transform 0.5s ease;
overflow: hidden;
}
.card img {
width: 100%;
height: 200px;
object-fit: cover;
}
.card p {
margin: 20px;
text-align: center;
font-size: 20px;
}
.card.selected {
transform: translateX(-100%) rotate(-10deg);
}
.card.replacement {
transform: translateX(100%) rotate(10deg);
}
</style>
</head>
<body>
<div id="cards-container">
<div class="card" id="card1"></div>
<div class="card" id="card2"></div>
</div>
<script>
const config = [
{ id: 1, image: 'card1.jpg', text: 'Option 1' },
{ id: 2, image: 'card2.jpg', text: 'Option 2' },
{ id: 3, image: 'card3.jpg', text: 'Option 3' },
{ id: 4, image: 'card4.jpg', text: 'Option 4' },
];
let selectedCardId = null;
let isAnimating = false;
function refreshCards() {
const card1 = document.getElementById('card1');
const card2 = document.getElementById('card2');
// Get two random options from the config array
const [option1, option2] = getRandomOptions(config);
// Set the options as the content of the cards
card1.innerHTML = `
<img src="${option1.image}" />
<p>${option1.text}</p>
`;
card2.innerHTML = `
<img src="${option2.image}" />
<p>${option2.text}</p>
`;
// Add click event listeners to the cards
card1.addEventListener('click', () => onCardClick(option1.id));
card2.addEventListener('click', () => onCardClick(option2.id));
}
function getRandomOptions(options) {
const randomIndexes = getRandomIndexes(options.length, 2);
return [options[randomIndexes[0]], options[randomIndexes[1]]];
}
function getRandomIndexes(max, count) {
const indexes = new Set();
while (indexes.size < count) {
indexes.add(Math.floor(Math.random() * max));
}
return Array.from(indexes);
}
async function onCardClick(id) {
// Only do something if the user hasn't already selected a card
if (selectedCardId === null) {
selectedCardId = id;
// Send a POST request with the selected card's ID to the API
const response = await fetch('https://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: selectedCardId }),
});
// Refresh the cards with new options from the config array
refreshCards();
// Reset the selected card ID
selectedCardId = null;
}
}
// Initialize the app by refreshing the cards
refreshCards();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment