Skip to content

Commit

Permalink
feat: Implement toggle component adhering to Material Design with ani…
Browse files Browse the repository at this point in the history
…mated switch and external event listeners

fix devhatt#71
  • Loading branch information
nathalia-84 committed Feb 17, 2024
1 parent ea0bbcf commit 2e04ced
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/components/Toggle/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Component } from 'pet-dex-utilities';
import './index.scss';

const events = ['active', 'inactive'];

const html = `
<div class="toggle-container">
<input type="checkbox" id="toggle-input" class="toggle-container__input" data-select="toggle-input">
<label for="toggle-input" class="toggle-container__label" data-select="toggle-label"></label>
</div>
`;

export default function Toggle() {
Component.call(this, { html, events });

this.selected.get('toggle-input').addEventListener('change', (e) => {
const { checked } = e.target;

if (checked) {
this.notChecked();
} else {
this.isChecked();
}
});
}

Toggle.prototype = Object.assign(
Toggle.prototype,
Component.prototype,
{
isChecked() {
this.selected.get('toggle-label').classList.add('checked');
this.emit('active');
},
notChecked() {
this.selected.get('toggle-label').classList.remove('checked');
this.emit('inactive');
},
},
);
60 changes: 60 additions & 0 deletions src/components/Toggle/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
.toggle-container {
display: inline-block;

position: relative;

&__input {
width: 0;
height: 0;

opacity: 0;
}

&__label {
min-width: 44px;
min-height: 24px;

display: flex;

align-items: center;

position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;

background-color: rgba(217, 223, 230, 1);

border-radius: 34px;

transition: 0.4s;

cursor: pointer;

&::after {
width: 41%;
height: 75%;

position: absolute;

left: 10%;

background-color: rgba(255, 255, 255, 1);

border-radius: 50%;

transition: 0.4s;

content: '';
}

&.checked {
background-color: rgba(27, 133, 243, 1);
}

&.checked::after {
transform: translateX(100%);
}
}
}

0 comments on commit 2e04ced

Please sign in to comment.