简体   繁体   中英

javascript toggle in jquery not working as expected

I have a button which toggles an iframe on and off using just javascript.

But when i click the button, instead of just iframe disappearing, the button also disappears along with iframe.

While checking in the firebug console, the CSS of the button also changes display parameter to 'none'.

$(document).ready(function(){

    var iDiv = document.createElement('div');
    iDiv.id = 'enigma';
    iDiv.setAttribute("style", "font-size:18px;position:fixed;bottom:20px;right:5px;display:inline");
    document.body.appendChild(iDiv);

    var div = document.createElement("div");
    div.innerHTML = '<iframe src="http://example.com/index.html" width="400" height="200" style="border:0"></iframe>';
    iDiv.appendChild(div);

    var div2 = document.createElement("div");
    div2.setAttribute("style","display:inline;");
    div2.innerHTML = '<button id="button2">Show/Hide</button>';
    document.body.appendChild(div2);

    setTimeout(function() {
        $("#button2").css({"position": "fixed", "display": "inline", "bottom": "0", "right": "0"}).click(function(){
            $("div").toggle('show');
        });
    }, 100);
});

When you click the button, you run

$("div").toggle('show');

which toggles all of the div s in the page. This includes the one containing the button. You can add an id to the div you want to hide to make it work:

var div = document.createElement("div");
div.id = "to-toggle";
...
setTimeout(function() {
    $("#button2").css({"position": "fixed", "display": "inline", "bottom": "0", "right": "0"}).click(function(){
        $("#to-toggle").toggle('show');
    });
}, 100);

$("div").toggle('show'); toggles all <div> elements.

Perhaps you want

$("iframe").toggle('slow');

Or be more specific and add an id to the element you are trying to control as per Iluvatar's answer

You need to be more specific here...

$("div").toggle();

You are currently targeting every div tag.

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