CiElBie
CiElBie

Reputation: 53

Javascript and CSS if statement

Im very new to programming and im trying to make a code which will cause an image to only appear if the ctrl key is not being pressed.

<script language=JavaScript>

document.onkeydown = checkKey;
var Showimg = False;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '17') {
      alert('test');
      Showimg = True;
    }
}
</script>

This is the code ive currently got. I have code in another division below which has the code for the image in.

I'm very new to CSS and javascript, and basically most coding in general, so im not sure if its possible to get an image to no longer show if the ctrl key is pressed, as "if" statements dont seem to work outside the script, but the image code wont work inside the script.

This may not be detailed enough, sorry.

Upvotes: 1

Views: 97

Answers (2)

Febrian Wilson
Febrian Wilson

Reputation: 1

function checkKey(e) {
    e = e || window.event;
    console.log(e);
    if (e.keyCode === 17) {
      document.getElementById('image').style.display = 'none';
    }
}
function show() {
    document.getElementById('image').style.display = 'block';
}

make the body like this

<body onkeydown="checkKey()" onkeyup="show()">

and for the image, you could make it like this

<img src="test.jpg" id="image">

Upvotes: 0

aw04
aw04

Reputation: 11187

So you have the event part down to determine when the ctrl key is pressed. What you need now (apart from some syntax issues others have pointed out) is to use javascript to hide the image. First you'll want a way to identify it, so for example you can add an id of img (or whatever).

<img id="img">

Then you can use js to target this and change the display property within your if statement.

document.getElementById('img').style.display = 'none';

This code will a) find the image, and b) change the display to not be shown.

Upvotes: 3

Related Questions