Last active
August 8, 2023 10:05
-
-
Save songjiz/b06dbe61c92d92e6dca8d837d6b40448 to your computer and use it in GitHub Desktop.
Toggle password visibility with stimulus controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="field" data-controller="toggle-password-visibility" data-toggle-password-visibility-visible-icon-class="mdi-eye-off"> | |
<%= form.label :password, class: 'label'%> | |
<div class="control"> | |
<div class="field has-addons has-addons-right"> | |
<div class="control is-clearfix has-icons-left has-icons-right"> | |
<span class="icon is-left"> | |
<i class="mdi mdi-onepassword mdi-24px"></i> | |
</span> | |
<%= form.password_field :password, class: ['input', { "is-danger": sign_in.errors.key?(:password) }], data: { 'toggle-password-visibility-target': 'password' }, required: true %> | |
<% if sign_in.errors.key?(:password) %> | |
<span class="icon is-right has-text-danger"> | |
<i class="mdi mdi-alert-circle mdi-24px"></i> | |
</span> | |
<p class="help is-danger"><%= sign_in.errors.full_messages_for(:password).first %></p> | |
<% end %> | |
</div> | |
<div class="control"> | |
<a href="javascript:;" class="button" data-action="toggle-password-visibility#toggle"> | |
<i class="mdi mdi-eye mdi-eye-off" data-toggle-password-visibility-target="icon"></i> | |
</a> | |
</div> | |
</div> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class extends ApplicationController { | |
static targets = [ "password", "icon" ] | |
static classes = [ "visibleIcon" ] | |
connect() { | |
this.setPasswordMode() | |
} | |
disconnect() { | |
this.setPasswordMode() | |
} | |
setPlainMode() { | |
this.passwordTarget.type = "text" | |
this.iconTarget.classList.remove(this.visibleIconClass) | |
} | |
setPasswordMode() { | |
this.passwordTarget.type = "password" | |
this.iconTarget.classList.add(this.visibleIconClass) | |
} | |
toggle(e) { | |
e.preventDefault() | |
if (this.passwordTarget.type == "password") { | |
this.setPlainMode() | |
} else { | |
this.setPasswordMode() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment