I have a button that expands on mousehover, and retracts on mouseleave, but in certain situations the button does not retract. I implemented a timer to avoid multiple triggers, but I was not successful, I tried to do it through css, but I had problems with synchronization between the animations.
It is possible to see this behavior through this fiddle
Is there any solution for this and why is this happening?
options.forEach(option => {
option.addEventListener('mouseenter', event => {
let btnExpandable = event.target.childNodes[1];
let optionsContainer = event.target.childNodes[3];
if(!animated) {
setTimeout(() => {
btnExpandable.classList.add('btn--expandable-expand');
optionsContainer.classList.add('options--expand');
animated = false;
},100);
}
animated = true;
});
option.addEventListener('mouseleave', event => {
let btnExpandable = event.target.childNodes[1];
let optionsContainer = event.target.childNodes[3];
if(!animated) {
setTimeout(() => {
btnExpandable.classList.remove('btn--expandable-expand');
optionsContainer.classList.remove('options--expand');
animated = false;
},100);
}
animated = true;
})
})
I have written a quantity selector function to display on a page. The page can open some modals, which need to have another quantity selector within each.
I am calling the function within the main page, and also within the modal (to enable the functionality once the modal is displayed.)
When I adjust the quantity in the modal, close the modal, and adjust the quantity on the main page, the quantity increments/decrements double (or 3 times if I was to call the function 3 times.)
Is there a way to "reset" each of these event listeners/functions, to only adjust for their respective elements?
I've looked into "removeEventListener" but haven't had any joy in implementing this within my code.
Example of my work so far here (you can see what I mean if you click the buttons.)
https://codepen.io/777333/pen/zYoKYRN
const quantitySelector = () => {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
if(qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
});
});
}
};
quantitySelector(); // called within main page
quantitySelector(); // called within modal
The issue at hand is that each time you're calling the function, a new event handler is added on top of the previous ones. The best way to avoid this is through Event Delegation where you add a global event handler only once.
// A global event handler
document.addEventListener(
"click",
function (event) {
// Find the qty-group if clicked on it
const qtyGroup = event.target.closest(".qty-group");
// Stop if the click was elsewhere
if (qtyGroup) {
// Get your elements
const qtyDecrease = qtyGroup.querySelector("[data-quantity-decrease]");
const qtyIncrease = qtyGroup.querySelector("[data-quantity-increase]");
const qtyInput = qtyGroup.querySelector("[data-quantity-input]");
const disableEnableDecrease = () => {
if (qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
// Match your elements against what was clicked on.
if (event.target == qtyDecrease) {
event.preventDefault();
if (qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
}
if (event.target == qtyIncrease) {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
}
}
},
false
);
Instead of listening to individual elements, you can capture all the clicks on the document, and then finding those that click on elements of interest. You can make a second event handler for the keyup event.
You can save the value of qtyInput on mousedown event and then in the increment you add or subtract one from the saved value instead of the current value of the input.
const quantitySelector = () => {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
let savedValue = null;
const saveState = (evebt) => savedValue = Number(qtyInput.value);
qtyDecrease.addEventListener('mousedown', saveState)
qtyIncrease.addEventListener('mousedown', saveState)
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
if(qtyInput.value > 1) {
qtyInput.value = savedValue - 1;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
qtyInput.value = savedValue + 1;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
event.stopPropagation();
});
});
}
};
quantitySelector();
quantitySelector();
There is a method called removeEventListener (MDN) but I suggest you to reshape your code such that you do not add event listener if they are already present.
Put all of your addEventListener just when you create your elements, or in a "document ready" callback if they are instantiated by HTML code. Then, when you open your modal, just update your values.
UPDATING YOUR CODE
// hide/show modal function
function toggleModal() {
let modal = document.getElementById('modal');
modal.style.display = modal.style.display == 'none' ? 'block' : 'none';
}
// your document ready function
function onReady() {
const qtyGroups = document.querySelectorAll('.qty-group');
if(qtyGroups) {
qtyGroups.forEach((qtyGroup) => {
const qtyDecrease = qtyGroup.querySelector('[data-quantity-decrease]');
const qtyIncrease = qtyGroup.querySelector('[data-quantity-increase]');
const qtyInput = qtyGroup.querySelector('[data-quantity-input]');
const disableEnableDecrease = () => {
if(qtyInput.value == 1) {
qtyDecrease.disabled = true;
} else {
qtyDecrease.disabled = false;
}
};
qtyDecrease.addEventListener('click', (event) => {
event.preventDefault();
if(qtyInput.value > 1) {
qtyInput.value--;
}
disableEnableDecrease();
});
qtyIncrease.addEventListener('click', (event) => {
event.preventDefault();
qtyInput.value++;
disableEnableDecrease();
});
qtyInput.addEventListener('keyup', () => {
disableEnableDecrease();
});
});
}
// attach hide/show modal handler
const toggle = document.getElementById('modal_toggle');
toggle.addEventListener('click', toggleModal);
}
onReady();
<div class="qty-group">
<button data-quantity-decrease disabled>-</button>
<input data-quantity-input value="1">
<button data-quantity-increase>+</button>
</div>
<div class="qty-group" id="modal" style="display: none;">
<button data-quantity-decrease disabled>-</button>
<input data-quantity-input value="1">
<button data-quantity-increase>+</button>
</div>
<button id="modal_toggle">Toggle Modal</button>
REFACTORING
It is better in such cases to reason as Components. Components ensure code encapsulation, maintainability, reusage, single responsability and many other usefull principles:
// hide/show modal function
function toggleModal() {
// get the modal
let modal = document.getElementById('modal');
// hide the modal
modal.style.display = modal.style.display == 'none' ? 'block' : 'none';
// reset the input of the modal
modalInputReference.reset();
}
function createQuantityInput(target, initialQuantity=1, min=1, max=10, step=1) {
let quantity = 0;
// assign and check if should be disable, also bind to input value
let assign = (q) => {
quantity = Math.max(Math.min(q, max), min);
decrease.disabled = quantity <= min;
increase.disabled = quantity >= max;
input.value = quantity;
};
// CREATION
// This part is not mandatory, you can also get the elements from
// the target (document.querySelector('button.decrease') or similar)
// and then attach the listener.
// Creation is better: ensure encapsulation and single responsability
// create decrease button
let decrease = document.createElement('button');
decrease.addEventListener('click', () => { assign(quantity - step); });
decrease.innerText = '-';
// create increase button
let increase = document.createElement('button');
increase.addEventListener('click', () => { assign(quantity + step); });
increase.innerText = '+'
// create input field
let input = document.createElement('input');
input.value = quantity
input.addEventListener('change', () => { assign(parseFloat(input.value)); });
// resetting the quantity
assign(initialQuantity);
// appending the new component to its parent
target.appendChild(decrease);
target.appendChild(input);
target.appendChild(increase);
// return a reference to manipulate this component
return {
get quantity() { return quantity; },
set quantity(q) { assign(q); },
assign,
reset: () => assign(initialQuantity)
};
}
// this will be your modal reference
let modalInputReference;
function onReady() {
// inject all qty-group with a "quantityInput" component
document.querySelectorAll('.qty-group').forEach(elem => {
let input = createQuantityInput(elem);
if (elem.id == 'modal') {
// if it is the modal I save it for later use
// this is just an hack for now,
// a full code should split this part into a "modal" component maybe
modalInputReference = input;
}
});
// emualte the modal
let toggle = document.getElementById('modal_toggle')
toggle.addEventListener('click', toggleModal)
}
// this function should be wrapped by a
// $(document).ready(onReady) or any other
// function that ensure that all the DOM is successfully loaded
// and the code is not executed before the browser has generated
// all the elements present in the HTML
onReady();
<div class="qty-group"></div>
<div class="qty-group" id="modal" style="display: none;"></div>
<button id="modal_toggle">Toggle Modal</button>
It is shorter (without comments) and also more maintenable. Don't trust who says it is overengineered, it is just kind of time to learn to reason this way, then is much easier and faster. It is just a time investment to waste less time in the future. Try figure out why React or Angular(JS) have climbed the charts of the best frameworks so fast.
A small development problem, first, I declare a div to represent an icon to enter my inventory.
<<if setup.tagValue("map") !== 'MainMenu'>>
<div id="generalMenu">
<div id="Inventory"></div>
</div>
<</if>>
Now the real code, to activate this.
$(document).on(':passageend', () => {
window.inventoryIcons()
})
window.inventoryIcons = () => {
const _local = passage()
const _icon = $('#Inventory')
if (['BattleAPI'].includes(_local)) {
_icon
.removeClass()
.addClass("disabled")
}
else {
_icon.addClass("genMenuHover")
_icon.ariaClick(() => {
window.playerEquipIcon()
window.setInvIcons()
window.playerInventoryHover()
Engine.play('Inventory')
console.log(_icon)
})
}
}
This is having a mysterious effect, where each execution returns more and more events to the click.
I have this code which sould toggle between elements, if user opens the element all other elements should close and that works, but if I click on the same element multiple times nothing happens and I cant figure out why. I need some help.
Here is my code:
const heads = [...document.querySelectorAll(".head")];
const dropdowns = [...document.querySelectorAll(".head-dropdown")];
const activate_filter = document.getElementById("filter-btn");
let isActive = false;
let isFilterActive = false;
let queue = [];
if (!isFilterActive) {
dropdowns.forEach((val, i) => {
val
.querySelector(".dropdown-search")
.setAttribute(
"name",
`${heads[i].querySelector("p").textContent}-search`
);
});
}
activate_filter.addEventListener("click", e => {
dropdowns.forEach((val, i) => {
val.classList.remove("activated");
val.dataset.isActivated = false;
});
if (!isFilterActive) {
heads.forEach((val, i) => {
const p = val.children[0];
p.innerHTML += `<i class='eos-icons'>arrow_drop_down</i>`;
val.addEventListener("click", handleEventAll);
val.style.cursor = "pointer";
});
isFilterActive = true;
} else {
heads.forEach(val => {
const p = val.children[0];
const i = p.querySelector("i");
if (i) {
i.remove();
}
val.removeEventListener("click", handleEventAll);
val.style.cursor = "default";
});
isFilterActive = false;
}
});
function handleEventAll(e) {
const test = e.target.querySelector(".head-dropdown");
test.classList.add("activated");
queue.unshift(test);
if (queue.length > 3) {
queue.pop();
}
dropdowns.forEach((val, i) => {
if (!val.dataset) {
val.dataset.isActivated = false;
}
let t = eval(queue[0].dataset.isActivated);
console.log(t);
if (t) {
console.log("in true", queue[0]);
queue[0].dataset.isActivated = true;
queue[0].classList.toggle("activated");
queue.pop();
} else {
console.log("in false", queue[0].dataset);
queue[0].dataset.isActivated = false;
console.log(queue);
queue[1].classList.remove("activated");
queue.pop();
}
});
}
window.addEventListener("click", e => {});
The elements are added to the queue and the queue sorts it out if previous element which was opened is properly closed and it opens a new element which is clicked. If the same element is clicked twice the queue closes the element but does not open it again until some other element is clicked.
Here is codepen for full experience: https://codepen.io/darioKolic/pen/eYdYzdy
I rewrote the handleEventAll function to make the required functionality without using a queue. check this
What I did is save the current state (is activated class exist or not) for clicked element, and then I remove all activated class from all element then add or remove the class activated depends on the old value.
So I have a modal that does not seem to want to close when clicking the close button. This what my current code looks like to show and close the modal as well as adding the modal-backdrop into the DOM and removing it.
const $ = document;
class Selectable {
addElement = () => {
const html = '<div class="modal-backdrop show"></div>';
const body = $.querySelector('body');
body.innerHTML += html;
};
removeElement = elementClass => {
let element = $.querySelector('.' + elementClass);
element.parentNode.removeChild(element);
};
showModal = () => {
const modal = $.getElementById('modal-finish');
const body = $.querySelector('body');
modal.classList.add('show');
body.classList.add('modal-open');
this.addElement();
};
closeModal = () => {
const modal = $.getElementById('modal-finish');
const body = $.querySelector('body');
modal.classList.remove('show');
body.classList.remove('modal-open');
this.removeElement('modal-backdrop');
};
init() {
// Look Up Button
$.getElementById('btn-look-up').addEventListener(
'click',
this.showModal,
false
);
// Close the Modal
$.querySelector('.modal-close').addEventListener(
'click',
this.closeModal,
false
);
}
}
const Selectables = new Selectable();
Selectables.init();
I have a feeling it's because the clickEvent is being registered straight away or something but I'm not completely sure.
Basically the modal opens but the close button is not functioning at all.
I've only ever used jQuery before to do JavaScript so I am using const $ = document; to ease the change over to standard JavaScript.
Try below Code:
Try it
document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("demo").innerHTML = "Hello World";
});