简体   繁体   中英

Why does this JS link require 2 clicks to trigger?

I'm working on a script which will go along with my already in place website. Basically, when you click the Show/Hide button , it shows an overlay over the content div . Then there's an option to hide the entire div , both overlay, content, and container.

Problem is, you have to click the hide link twice for it to hide all the divs.

I have a working example here:

http://jsfiddle.net/charlescarver/8c3VZ/3/

EDIT: I updated the jsFiddle with the correct version of the JS. I had the incomplete one in there before.

Also, there's more to the script that allows cookies, I just didn't include it to reduce the amount of code.

It's because the style.display attribute is undefined at first. reversing the logic can fix this. Basically the reason why is because element.style.display directly reads the style attribute of the element and not a javascript attribute like in this element:

<div style="display:none;">blah</div>

because your element doesn't have the style attribute at first, it defaults to the else. Switching the logic will default it to hiding it rather than showing it.

http://jsfiddle.net/MpJDN/

function toggle_visibility(a) {
var b = document.getElementById(a);
if (b.style.display == "none") {
    b.style.display = "block";
}
else {
    b.style.display = "none";
}
}

Change your toggle_visibility() code to this to let jQuery's .toggle() and .css() do most of the work for you:

<script>
    function toggle_visibility(a) {
        var item = $("#" + a);
        item.toggle();
        $.cookie("disp" + a, item.css("display"));
    }
</script>

The reason it wasn't working is that b.style.display in your original code only returns inline styles. It does not return styles set by CSS rules. If you really wanted to get that style, you could use jQuery's .css("display") method. But, in this case, you can just use .toggle() and let that do all the work for you.

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