I want to disable all images of my game by using enable or disable function, but it does not works! can you help me with this? I have no idea how to disable or enable onclick function on a single image
Tryed this:
<div><img id="red" src = "rojo.png" onclick="setColorRojo()"/></div>
function enable(){
document.getElementById("red").disabled = false;
}
function disable(){
document.getElementById("red").disabled = true;
}
I want to disable all images of my game by using enable or disable function, but it does not works! can you help me with this? I have no idea how to disable or enable onclick function on a single image
Tryed this:
<div><img id="red" src = "rojo.png" onclick="setColorRojo()"/></div>
function enable(){
document.getElementById("red").disabled = false;
}
function disable(){
document.getElementById("red").disabled = true;
}
Share
Improve this question
edited Feb 3, 2016 at 20:41
Carlos Montiel
asked Feb 3, 2016 at 20:39
Carlos MontielCarlos Montiel
3011 gold badge4 silver badges17 bronze badges
5
- 1 you can't disable images. disabling is for form fields... – Marc B Commented Feb 3, 2016 at 20:40
-
there is no disabling an image. perhaps you should set a boolean flag as a variable that
setColorRojo
would do – Daniel A. White Commented Feb 3, 2016 at 20:40 - You mean you want to hide them? Replace them with red squares? – dtanders Commented Feb 3, 2016 at 20:43
- @DanielA.White I got it, So I can build that with a loop right? – Carlos Montiel Commented Feb 3, 2016 at 20:44
- @dtanders no, just disable it, like when a disabled button appear (unable to click) – Carlos Montiel Commented Feb 3, 2016 at 20:44
3 Answers
Reset to default 3Images can't be disabled and enabled in the way you're trying to. Try using a flag to determine the state of the application instead:
var enabled = true;
function enable(){
enabled = true;
}
function disable(){
enabled = false;
}
function setColorRojo() {
if (enabled) {
//Set color or do any other actions here
}
}
You can't actually disable an <img>
, that's more for <input>
tags. You can add/remove an attribute on the img and if present, stop execution in setColorRojo()
:
function enable(){
document.getElementById("red").setAttribute('disabled', 'true');
}
function disable(){
document.getElementById("red").setAttribute('disabled', 'false');
}
<img id="red" src="rojo.png" onclick="setColorRojo(this);"/>
function setColorRojo(img){
if(img.getAttribute('disabled') === 'true') return;
//do the rest of the function
}
A simple trick is to use pointerEvents css property. By setting it to none, mouse click events on the image are disabled, while setting it to auto enables mouse click events.
function disableClick(imageID) {
document.getElementById(imageID).style.pointerEvents = "none";
}
function enableClick(imageID) {
document.getElementById(imageID).style.pointerEvents = "auto";
}
Works in Chrome and Firefox.