Carlos Montiel
Carlos Montiel

Reputation: 301

Disable or enable an html5 image with javascript

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;

    }

Upvotes: 0

Views: 14105

Answers (3)

Vikas NS
Vikas NS

Reputation: 438

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.

Upvotes: 1

AlliterativeAlice
AlliterativeAlice

Reputation: 12587

Images 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
    }
}

Upvotes: 3

neilsimp1
neilsimp1

Reputation: 1259

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
}

Upvotes: 2

Related Questions