how I can get a multifunction button in JS? For example: the first click will move the button down, the next click will return it to the default place.
let caoButton = document.querySelector('.js-cao-2');
caoButton.style.position = 'absolute';
caoButton.style.top = '0';
caoButton.style.left = '0';
caoButton.addEventListener('click',() {
caoButton.style.top = 'unset';
caoButton.style.left = 'unset';
caoButton.style.bottom = '0';
caoButton.style.right = '0';
});
CodePudding user response:
Agree with @charlietfl
let caoButton = document.querySelector('.js-cao-2');
caoButton.addEventListener('click',()=>caoButton.classList.toggle("moveDown"));
.js-cao-2{
position: absolute;
top: 0;
left: 0;
}
.moveDown {
top: unset;
left: unset;
bottom: 0;
right: 0;
}
<div style="height: 100vh">
<button >Move me</button>
</div>
In case you wish to do something more that just manipulate the css and you must use JavaScript, you can also do something like:
let caoButton = document.querySelector('.js-cao-2');
caoButton.addEventListener('click',firstFunctionality);
function firstFunctionality(){
caoButton.removeEventListener('click', firstFunctionality)
caoButton.addEventListener('click',secondFunctionality);
//do stuff here
}
function secondFunctionality(){
caoButton.removeEventListener('click', secondFunctionality)
caoButton.addEventListener('click', firstFunctionality);
//do something different here
}
CodePudding user response:
This will trigger multiple actions on the button.
let caoButton = document.querySelector('.js-cao-2');
const allTasks = (function* makeTaskGetter(){
const tasks = [
'js-cao-2-down',
'js-cao-2-right',
'js-cao-2-up',
'js-cao-2-left'
];
for (const task of tasks) { yield task; }
})();
caoButton.addEventListener('click', e => {
const { value : task } = allTasks.next();
caoButton.classList.add(task);
});
.js-cao-2 {
position: absolute;
}
.js-cao-2-down {
top: 100px;
}
.js-cao-2-right {
left: 100px;
}
.js-cao-2-up {
top: 10px;
}
.js-cao-2-left {
left: 10px;
}
<button >Click Me</button>
Also consider using transform: translate
depending on your use case.