Skip to content

Instantly share code, notes, and snippets.

@syntheticminds
Created March 18, 2020 11:33
Show Gist options
  • Save syntheticminds/c85cb0dafb45322e8885885c8e129ab2 to your computer and use it in GitHub Desktop.
Save syntheticminds/c85cb0dafb45322e8885885c8e129ab2 to your computer and use it in GitHub Desktop.
Alpine.js To-Do Example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Alpine.js To-Do Demo</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>
<style>
[x-cloak] { display: none; }
</style>
</head>
<body class="bg-light">
<div class="container">
<div class="row justify-content-center my-sm-5">
<div class="col-sm-10 col-lg-8 col-xl-6">
<h1>Alpine.js Demo</h1>
<p class="lead">The obligatory to-do list.</p>
<div class="card shadow" x-data="{ label: '', tasks: [], count: 0 }">
<div class="card-body">
<form @submit="label ? tasks.push({'id': count++, 'label': label, 'is_complete': false}) : null; label = '';" x-on:submit.prevent>
<div class="form-group mb-0">
<div class="input-group">
<input type="text" placeholder="New task" class="form-control" x-model="label" x-ref="input">
<div class="input-group-append">
<button type="submit" class="btn btn-primary" @click="$refs.input.focus()">Add</button>
</div>
</div>
</div>
</form>
<template x-if="tasks.length">
<p class="text-muted mt-4 mb-0">The list is <span x-text="Math.round(tasks.filter(item => item.is_complete).length / tasks.length * 100)"></span>% complete.</p>
</template>
</div>
<ul class="list-group list-group-flush">
<template x-for="task in tasks" :key="task">
<li class="list-group-item" x-bind:class="{ 'bg-success text-white': task.is_complete }">
<span x-text="task.label"></span>
<button type="button" class="close text-monospace" title="Mark as complete" x-show="!task.is_complete" @click="task.is_complete = true">&check;</button>
<button type="button" class="close text-monospace" title="Remove task" x-show="task.is_complete" @click="tasks = tasks.filter(item => item.id !== task.id);">&times;</button>
</li>
</template>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment