document.getElementById("image1").onclick = function() {
imageClickedOn()
}
all I want is so that when I click the image, I can't click it again until the function is over.
document.getElementById("image1").onclick = function() {
imageClickedOn()
}
all I want is so that when I click the image, I can't click it again until the function is over.
You can used a variable to determine if imageClickedOn()
should be allowed to run. You would set it to true when the function starts and false when the function ends.
var isImageClicked = false;
document.getElementById("image1").onclick = function() {
if (!isImageClicked) {
imageClickedOn()
}
}
imageClickedOn() {
isImageClicked = true;
...
isImageClicked = false;
}
Do you mean like with a timeout?
let canClick = true;
img.addEventListener("click", function () {
if (canClick) {
//your function goes here
console.log("image clicked");
canClick = false;
setTimeout(() => canClick = true, 2000); // 2000 milliseconds === 2 seconds
}
});
img {
width: 200px;
}
<img id="img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png">
This will create a delay of 2 seconds before the user can click the image again.
When clicked, you can add a CSS class with pointer-events
set to none
to prevent subsequent clicks. Once your function has completed, you can remove the class.
function imageClickedOn() {
// returns a promise that resolves in 1s
return new Promise(res => setTimeout(res, 1000))
}
document.getElementById("image1").addEventListener("click", async (e) => {
console.log("Image clicked")
const img = e.target
// Add class
img.classList.add("disable-click")
// Wait for function to complete
await imageClickedOn()
// Remove class
img.classList.remove("disable-click")
})
.disable-click {
pointer-events: none;
/* the below just lets you see when it is not clickable */
filter: blur(5px);
opacity: .8;
}
<img id="image1" width="100" height="100" src="https://picsum.photos/100">
If your element is an <a>
or <button>
, you're probably better off toggling the disabled
property instead.
You can follow. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_dom;
But it not work you can try
$("#image1").click(()=>{ "function " })