Prevent text and value from changing when clicked twice - javascript

I am trying to prevent the text and value changing when clicked multiple times. i have looked at similar questions and tried out their answers but nothing has worked.
Here is my code:
const updateSuccess = (event) => {
if (playerXTurn === true) {
$('#cell0').val('X')
$('#cell0').text('X')
} else {
playerXTurn === false
$('#cell0').val('O')
$('#cell0').text('O')
}
playerXTurn = !playerXTurn
getGames.game.cells[0] = $('#cell0').val()
event.stopPropagation(updateSuccess)
}
I also have this code before it
const onUpdateGame = function (event) {
event.preventDefault()
const data = getGames
api.updateGame(data)
.then(gameUi.updateSuccess)
.catch(ui.fail)
}

Related

Check if element is focused with Vanilla JS, not jQuery

I have this big class Search, which controls my search bar on my website. Now, when a input is focused, i dont want my s key (which pops out the search bar) to execute when a input is focused. I tried with document.activeElement, but then, the search bar wont even open, whilst the input not being focused. You can see it, under keydown event listener, under Events comment
class Search {
// Describe and create object
constructor() {
this.openButton = document.querySelectorAll('.js-search-trigger');
this.closeButton = document.querySelector('#close-button');
this.searchOverlay = document.querySelector('.search-overlay');
this.searchField = document.getElementById('search-term');
this.typingTimer;
this.events();
this.isSpinnerVisible = false;
this.resultsDiv = document.getElementById('search-overlay__results');
this.previousValue;
console.log(this.openButton);
}
// Events
events() {
this.openButton.forEach(e => {
e.addEventListener('click', () => {
this.openOverlay();
document.body.classList.add('body-no-scroll');
});
})
this.closeButton.addEventListener('click', () => {
this.closeOverlay();
document.body.classList.remove('body-no-scroll');
})
document.addEventListener('keydown', (e) => {
if(e.key === 's' && !(this === document.activeElement)){
this.openOverlay();
document.body.classList.add('body-no-scroll');
console.log("s pressed")
}
if(e.key === 'Escape' && this.isOverlayOpen){
this.closeOverlay();
document.body.classList.remove('body-no-scroll');
console.log("esc pressed");
}
});
this.searchField.addEventListener('keyup', () => {
this.typingLogic();
})
}
// Methods
openOverlay(){
this.searchOverlay.classList.add('search-overlay--active');
this.isOverlayOpen = true;
}
closeOverlay(){
this.searchOverlay.classList.remove('search-overlay--active');
}
typingLogic(){
if(this.searchField.value != this.previousValue){
clearTimeout(this.typingTimer);
if(this.searchField.value){
if(!this.isSpinnerVisible){
this.resultsDiv.innerHTML = '<div class="spinner-loader"></div>';
this.isSpinnerVisible = true;
}
this.typingTimer = setTimeout(this.getResults(),2000);
}else{
this.resultsDiv.innerHTML = '';
this.isSpinnerVisible = false;
}
}
this.previousValue = this.searchField.value;
}
getResults(){
this.typingTimer = setTimeout(()=> {
this.resultsDiv.innerHTML = 'Some here';
this.isSpinnerVisible =false;
},2000)
}
}
export default Search
You can check tagName property of activeElement. And if it is not input then proceed with your code. Update your condition like below.
if(e.key === 's' && document.activeElement.tagName.toLowerCase() != 'input')

document.addEventListener in function not working

I'm trying to hide the "modal" box when the user press Esc key.
So, I first check where the box contains class - 'hidden', which
technically hide the box in UI.
Then if it's not hidden (the box does not contain class - 'hidden') and
appearing on screen, the function will wait for the Esc key for the
box to be disappeared.
Showing and hiding the box parts working just fine, but document.addEventListener part is not working.
const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');
const showModal = function() {
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const hideModal = function() {
modal.classList.add('hidden');
overlay.classList.add('hidden');
}
for(let i = 0; i < btnopenModal.length; i++)
btnopenModal[i].addEventListener('click', showModal);
btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);
if(!overlay.classList.contains('hidden')) {
document.addEventListener('keypress', function(e) {
console.log(e.key);
if(e.key === 'Escape') {
hideModal();
}
})
};
Any other way around for this to work?
I would think that your if statement is evaluated when the webpage first runs, and my guess is that the if statement evaluates to false as it probably does contain the class "hidden" at first. I don't understand why you put it the key handler inside of an if statement, if it is for safety you should put it inside your function like so:
document.addEventListener('keypress', function(e) {
if(!overlay.classList.contains('hidden')) {
console.log(e.key);
if(e.key === 'Escape') {
hideModal();
}
};
})
Move if condition into callback. You want to always add keypress listener, just do not execute hideModal() if !overlay.classList.contains('hidden')
const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');
const showModal = function() {
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const hideModal = function() {
modal.classList.add('hidden');
overlay.classList.add('hidden');
}
for(let i = 0; i < btnopenModal.length; i++)
btnopenModal[i].addEventListener('click', showModal);
btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);
document.addEventListener('keypress', function(e) {
console.log(e.key);
if(e.key === 'Escape' && !overlay.classList.contains('hidden')) {
hideModal();
}
});

Turning on and off an element's onclick properties

I'm trying to delay the load of a pop-up on a grid of images but want to prevent the ability to click on other images when this happens. Howver if I turn off onclick 'item.onclick = false', I don't seem to be able to turn it back on when the pop-up is turned back on? see line 'item.onclick = true'. Have also tried disabled = true/false but to no avail. Any suggestions?
var caseStudies = document.querySelectorAll('.posterImage');
var caseHover = document.querySelectorAll('.caseHover');
var modal = document.querySelectorAll('.modal');
caseStudies.forEach((button, index) => {
if ((isMobile == true) || (isTablet == true)) {
button.onclick = function(event) {
caseStudies.forEach((item) => {
item.onclick = false;
console.log(item);
});
caseHover.forEach((item) => {
item.classList.add('eventsNone');
console.log(item);
});
setTimeout(function(){
console.log("loading");
modal[index].style.display = "block";
// When the user clicks anywhere outside of the modal, close it (needs to live inside the button.onclick)
window.onclick = function(event) {
if (event.target == modal[index]) {
modal.forEach((item) => {
item.style.display = "none";
});
caseStudies.forEach((item) => {
item.onclick = true;
});
}
}
}, 500);
}
}
else
{
button.onclick = function(event) {
console.log("route2");
modal[index].style.display = "block";
caseStudies.forEach((item) => {
item.classList.add('eventsNone')
});
// When the user clicks anywhere outside of the modal, close it (needs to live inside the button.onclick)
window.onclick = function(event) {
if (event.target == modal[index]) {
modal.forEach((item) => {
item.style.display = "none";
});
caseStudies.forEach((item) => {
item.classList.remove('eventsNone')
});
};
};
};
};
});
Use an inline onclick = "function()" to set your onclick.
When disabling your onlick do it with element.onclick = null.
And enable it again with element.onclick = "function()"
Sorry for getting it wrong before I miss read it and thought you were doing it with buttons.
Also here is a duplicate question how to disable or enable all onClick for images on a page

how to identify which button clicked in react?

I have two buttons that execute the same function, and that function needs to evaluate go backward or go forward as I show in the following image
and in the following code I want to evaluate what function next() or prev() to execute depending on which button was touched, this is built in react
const onFinish = (values) => {
if (values.users) {
const Operator = values.users.map((item) => ({
ruleAttributeName: item.ruleAttributeName,
isoAttributeId: item.isoAttributeId,
ruleOperationId: item.ruleOperationId,
mandatoryValue: item.mandatoryValue,
}));
setAttributes(Operator);
}
if (values.users) {
const attributesSave = values.users.map((item) => ({
ruleAttributeName: item.ruleAttributeName,
isoAttributeEntity: {
isoAttributeId: item.isoAttributeId,
},
ruleOperationEntity: {
ruleOperationId: item.ruleOperationId,
},
mandatoryValue: item.mandatoryValue,
}));
console.log('mandatory';
setAttributesSave(attributesSave);
setMandatoryValue();
next();
prev();
};
and in this form I pass by parameter the function
<Form
name='dynamic_form_nest_item'
onFinish={onFinish}
autoComplete='off'
>
You can identify them by assigning unique Id to both button like this
<button onClick={onFinish} Id={'1'}>Next</button>
<button onClick={onFinish} Id={'2'}>Next</button>
And in you listener check id which button clicked.
const onFinish = (event) => {
Let id = event.target.id;
if(id=== "1") {
// Do for one
} else {
// For second
}
}
I don't know the parameters that you got on that custom buttons and how is it triggering onClick event. But here is the solution for HTML buttons.
You can set a value to the button like this.
<button onClick={onFinish} value="next">Next</button>
const onFinish = (ev) => {
ev.preventDefault() // this is to prevent the refresh
const { value } = ev.target // equals with const value = ev.target.value
if(value === "next") {
next()
} else {
prev()
}
}

Autocompletion randomly activate when i press a checkbox in javascript

I'm making a to-do list in javascript, but after i insert a element, when i try to press the checkbox i generate with the task, i got a random dropdown (from the input who was hidden (removeChild))
I try to recode some part but keep getting this problem :
- display: none
- hidden(true)
It can happen on Firefox but not on Chrome
function createInput(type, value = "", name = "", placeholder = "", require = false)
{
const input = document.createElement("input")
input.setAttribute("type", type)
input.setAttribute("style", "margin-right:10px")
if (value !== "") {
input.setAttribute("value", value)
}
if (name !== "") {
input.setAttribute("id", name)
input.setAttribute("name", name)
}
if (placeholder !== "") {
input.setAttribute("placeholder", placeholder)
}
if (require) {
input.setAttribute("required", "true")
}
return input
}
const addTaskElt = document.getElementById("add_task")
const formElt = document.getElementById("list_task")
const inputElt = createInput("text", "", "task", "Entrez votre tâche")
const submitElt = createInput("submit", "Ajouter")
const buttonElt = document.createElement("button")
buttonElt.textContent = "Ajouter une tâche"
addTaskElt.appendChild(buttonElt)
buttonElt.addEventListener("click", function(e) {
addTaskElt.removeChild(buttonElt)
addTaskElt.appendChild(inputElt)
addTaskElt.appendChild(submitElt)
inputElt.focus()
formElt.addEventListener("submit", function(e) {
e.preventDefault()
const itemElt = document.createElement("span")
const checkElt = createInput("checkbox")
const taskElt = document.createElement("span")
if (e.target.task.value !== "") {
taskElt.textContent = e.target.task.value
itemElt.classList.add("item")
itemElt.appendChild(checkElt)
itemElt.appendChild(taskElt)
formElt.appendChild(itemElt)
// Switch form and button
inputElt.value = "" // clear input
addTaskElt.removeChild(inputElt)
addTaskElt.removeChild(submitElt)
addTaskElt.appendChild(buttonElt)
}
// We can edit the task by clicking it
taskElt.addEventListener("click", function() {
const result = prompt("Modifier la tâche")
if (result === null) {
}
else if (result === "") {
formElt.removeChild(itemElt)
}
else {
taskElt.textContent = result
}
})
checkElt.addEventListener("change", function(e) {
if (e.target.checked) { // if check, task done
taskElt.setAttribute("style", "color:gray;text-decoration:line-through")
}
else {
taskElt.setAttribute("style", "color:black")
}
})
})
})
From your comment above, Im assuming .setAttribute(“autocomplete”, “off”) worked to solve your problem.
It would appear autocomplete is on by default on input fields, but I did not see a default case on mdn, https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete. It does, however, state "The source of the suggested values is generally up to the browser". So if the browser thinks the items in the list are important to that input field then go ahead and show the related list.

Categories