简体   繁体   中英

Input image on click function open, on click again function closes

I've read through similar questions' answers but most are jQuery answers. I'm using JavaScript only to do this so if someone could help me fix my problem would be great.

So far in my js when my input image is clicked my function displays a box. I want to be able to click this input image again to close the box. At the moment I can't close it by clicking the image.

Here is my js:

var settings = document.getElementById('cog');
settings.onclick = Cog;


function Cog(){
document.getElementById('settings').style.display = "block";
document.getElementById('cogbox').style.display = "block";
}

'cog' is my image and clickable input. What code am I missing to make the box close by clicking the 'cog' image?

is there any reason your not using library? if you're going to be doing a lot of JS, Mootools or JQuery will help you out a lot. Jquery is easier to learn though Mootools is way more flexible. For your problem, you're only really giving it the ability to show, though nothing else. try using a conditional statement like the one shown here: Toggle Html with JS

That should get you where you need to be.

I believe you just need a variable to check if you should show or hide the box. Check if this works:

var settings = document.getElementById('cog');
settings.onclick = Cog;

var cogShow = false;
function Cog(){
    cogShow = !cogShow;
    document.getElementById('settings').style.display = (cogShow ? "block" : "none");
    document.getElementById('cogbox').style.display = (cogShow ? "block" : "none");
}

Or you could simplify it even more, by checking if cogbox is visible and them doing the opposite to the object when clicking again:

var settings = document.getElementById('cog');
settings.onclick = Cog;

function Cog(){
    show = (document.getElementById('cogbox').style.display === "none");
    document.getElementById('cogbox').style.display = (show ? "block" : "none");
    document.getElementById('settings').style.display =  (show ? "block" : "none");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM