What's with wrong in my code?
If user input-bday match the json-bday then it will display my form(I didn't include it because it's a lot)
else it won't display the form
checkBirthday: function() {
let userBirthday = moment(this.userBday).format("MM DD, YYYY"),
resultBirtday = moment(this.results.BIRT_D).format("MM DD, YYYY");
if (userBirthday === resultBirtday) {
alert("CORRECT");
window.onload = function() {
const btn = document.querySelector("#show-form");
const form = document.querySelector(".form");
const close = document.querySelector(".close-container");
btn.addEventListener("click", () => {
form.classList.add("form-show");
close.classList.add("x-show");
});
close.addEventListener("click", function() {
close.classList.remove("x-show");
form.classList.remove("form-show");
});
};
} else {
alert("WRONG");
window.stop();
}
}
window.onload = function() {} is just assigning this method to onload event of window and the code inside it will never run because onload has already been called.
You actually don't need to write onload here. so your code would be something like this.
checkBirthday: function() {
let userBirthday = moment(this.userBday).format("MM DD, YYYY"),
resultBirtday = moment(this.results.BIRT_D).format("MM DD, YYYY");
if (userBirthday === resultBirtday) {
alert("CORRECT");
const btn = document.querySelector("#show-form");
const form = document.querySelector(".form");
const close = document.querySelector(".close-container");
btn.addEventListener("click", () => {
form.classList.add("form-show");
close.classList.add("x-show");
});
close.addEventListener("click", function() {
close.classList.remove("x-show");
form.classList.remove("form-show");
});
} else {
alert("WRONG");
window.stop();
}
}
Related
I have tried this before and it worked well but here i dont know...
<div onclick="choose(this)">
<div class="choose">
<button><a>click</a></button>
</div>
</div>
my JavaScript:
function choose(obj) {
obj = obj || document.activeElement;
var res_item = obj.querySelector(".choose");
res_item.classList.add("choosed_item");
var close = obj.querySelector(".choose button a");
close.addEventListener("click", function closemodal() {
if (res_item.classList.contains("choosed_item")) {
res_item.classList.remove("choosed_item");
}
});
}
choose and choosed_item have custom style
This is strange, but if i change remove to add and choose another class it works well !
The event is not updated because its child of onclick function. Thats why I integrated an interval. That will help to update the eventlistener:
function choose(obj) {
obj = obj || document.activeElement;
var interval;
var res_item = obj.querySelector(".choose");
res_item.classList.add("choosed_item");
var close = obj.querySelector(".choose button a");
close.addEventListener("click", function closemodal() {
if (res_item.classList.contains("choosed_item")) {
interval = setInterval(function () {
res_item.classList.remove("choosed_item");
stopInterval();
}, 0);
function stopInterval() {
clearInterval(interval);
}
}
});
}
Hope I could help!
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.
Question
How do I create a custom javascript dot function that does the same thing as the following code in jQuery:
$(document).on("click touchstart", ".someClass", function() {
// code goes here
});
I'd like to declare it like this:
$(".someClass").onClick(function () {
// code goes here
});
It needs to:
work with dynamically created elements (hence jQuery .on() instead of .click())
work with computer clicks as well as touch taps
ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)
What I've Tried
Object.prototype.onClick = function() {
$(document).on('click touchstart', this, arguments);
};
But I receive the following error in chrome console:
Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function
I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.
You are looking for Event Delegation this allows you too dynamically add elements and still have them respond to click.
const getDiv = (name) => {
if (Array.isArray(name) === false) name = [name];
let div2 = document.createElement('div');
name.forEach(n => div2.classList.add(n));
div2.innerText = `${name}`;
return div2;
};
const makeDivs = () => {
const div = document.querySelector('#main');
const {
dataset: {
count: x
}
} = div;
for (let i = 0; i < x; i++) {
div.appendChild(getDiv('div2'));
div.appendChild(getDiv('div3'));
div.appendChild(getDiv(['div2', 'div3']));
}
};
document.addEventListener('click', ({
target
}) => {
if (target.matches('.div2')) console.log('You clicked a DIV2');
if (target.matches('.div3')) console.log('You clicked a DIV3 !!')
if (target.matches('button')) makeDivs();
});
div {
border: 1px solid red;
margin: 5px;
}
<div id='main' data-count="10">
</div>
<button>Click Me!!!</button>
Wrapping this up into a custom function.
NOTE: I changed selector param to be an array, this allows you to pass complex selectors e.g. div.myClass li:hover
const getDiv = (name) => {
if (Array.isArray(name) === false) name = [name];
let div2 = document.createElement('div');
name.forEach(n => div2.classList.add(n));
div2.innerText = `${name}`;
return div2;
};
const makeDivs = () => {
const div = document.querySelector('#main');
const {
dataset: {
count: x
}
} = div;
for (let i = 0; i < x; i++) {
div.appendChild(getDiv('div2'));
div.appendChild(getDiv('div3'));
div.appendChild(getDiv(['div2', 'div3']));
}
};
document.on = (eventType, selector, callback) => {
const events = eventType.split(' ');
const selectors = (Array.isArray(selector)) ? selector : [selector];
events.forEach(event => { document.addEventListener(event, (e) => {
if(selectors.some(s => e.target.matches(s))) callback(e);
});
});
};
// Convenience method.
document.onClick = (selector, callback) => document.on('click', selector, callback);
// Simple
document.on('click', 'button', () => makeDivs());
document.on('click', '.div2', ({target}) => console.log('You clicked a DIV2'));
// Multi Event
document.on('click touchstart', '.div3', () => console.log('You clicked a DIV3'));
// Multi selectors
document.on('click', ['.div2', '.div3'], ({target}) => console.log('You clicked. !!'));
document.onClick('div', ({target}) => console.log('A Click Event!!'));
div {
border: 1px solid red;
margin: 5px;
}
<div id='main' data-count="10">
</div>
<button>Click Me!!!</button>
So you want a .onClick jQuery method
jQuery.fn.extend({
onClick: function(sel, cb) {
return this.on('touchstart click', sel, function(evt) {
evt.preventDefault();
if (cb && typeof cb === 'function') cb.apply(this, arguments);
})
}
});
$(document).onClick('.someClass', function(ev) {
console.log(ev.type)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someClass">CLICK ME</p>
Or this simpler variant:
$.fn.onClick = function(sel, cb) {
return this.on('touchstart click', sel, cb);
};
$(document).onClick('.someClass', function(ev) {
ev.preventDefault();
console.log(ev.type)
});
I have this code:
input.addEventListener('keydown', (event) => {
if (event.keyCode === 13 && input.value) {
sendText(input.value);
var response = responseChat(input.value, 'user');
insertResponse(response);
input.value = '';
}
});
In this code, the client types some words to send to app web. So, I need when, the client not type and send some, the page sends a message of: "You are not work!!"
I create this function with setTimeOut but I don't know how to put this in my code:
function first(){
sendText("your are not work!");
}
function sendFirst(){
clearTimeout(time);
time = setTimeout(first, 5000);
}
Could you help me? Thanks
This is what you want. Will console.log 'you are not working!' after 3 seconds of keyboard inactivity. Click 'Run code snippet' below to try it out.
const sendText = console.log;
const input = document.getElementById('fred');
let timeout
const restart = () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
sendText("you are not working!");
}, 3000);
}
restart();
input.addEventListener('keydown', (event) => {
restart();
if (event.keyCode === 13 && input.value) {
sendText(input.value);
// var response = responseChat(input.value, 'user');
// insertResponse(response);
input.value = '';
}
});
<input id="fred">
I'm working on a quiz. The page can't be closed before submitting the form, otherwise all data will be lost. This can be done using:
window.onbeforeunload = function () {
return "Are you sure?"
}
But what if I don't want to trigger this alert if user clicked on "Submit"? I tried the code below but it doesn't work at all - it doesn't show the alert even if window is being closed.
var clicked_submit = false;
$(document).ready(function () {
$('#submit-button').click(function () {
clicked_submit = true;
});
window.onbeforeunload = function () {
if (clicked_submit){
} else {
return 'Are you sure?'
}
}
});
One simple solution is to just return the function without any value.
var clicked_submit = false;
$(document).ready(function () {
$('#submit-button').click(function () {
clicked_submit = true;
});
window.onbeforeunload = function () {
if (clicked_submit){
return; // equal to return undefined;
} else {
return 'Are you sure?'
}
}
});
A cleaner solution would be, to simply set the window.onbeforeunload to null.
var clicked_submit = false;
$(document).ready(function () {
$('#submit-button').click(function () {
clicked_submit = true;
});
if(!clicked_submit) {
window.onbeforeunload = function () {
return 'Are you sure?'
}
} else {
window.onbeforeunload = null;
}
});