In this tutorial, we will learn how to hide and show passwords using Alpine.js. We will use Tailwind CSS for the UI, but you can use any CSS framework you prefer.
We use Alpine.js because it is a lightweight library with a bundle size of just 6.4 KB, making its download time faster than jQuery.
Define x-data="{ show: true }"
. Next, bind the input type using x-bind
or :
(:type="show ? 'password' : 'text'"
). Then, create a click event with @click="show = !show"
and bind the text using x-text="show ? 'Show' : 'Hide'"
.
<body class="flex items-center justify-center min-h-screen bg-gray-100">
<div class="w-full max-w-sm p-6 bg-white rounded-md shadow-md">
<h2 class="mb-6 text-2xl font-semibold text-center text-gray-700">Login</h2>
<form>
<div class="mb-4">
<label class="block mb-2 text-sm text-gray-600" for="email">Email</label>
<input type="email" id="email" name="email"
class="w-full px-4 py-2 text-sm text-gray-700 border rounded-md focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-600"
required>
</div>
<div class="mb-6 relative" x-data="{ show: false }">
<label class="block mb-2 text-sm text-gray-600" for="password">Password</label>
<input :type="show ? 'text' : 'password'" id="password" name="password"
class="w-full px-4 py-2 text-sm text-gray-700 border rounded-md focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-600"
required>
<span class="absolute inset-y-0 right-0 flex items-center pr-3 mt-6">
<svg @click="show = !show" :class="{'text-blue-600': show, 'text-gray-600': !show}"
class="w-6 h-6 cursor-pointer" fill="none" stroke="currentColor" viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
</svg>
</span>
</div>
<button type="submit"
class="w-full px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:bg-blue-600">Login</button>
</form>
</div>
</body>