Ramy
Ramy

Reputation: 21261

Why is my hide/unhide button only working on the second click?

I just read this question, but the answers don't seem to help me. Also, I would think that this code would initially have the tables hidden but that's also not working. This is for a chrome extension so cross browser functionality is unnecessary. Pure javascript answers only, please.

    var observer = new MutationObserver(function(mutations) {  

        tables = main_pm_node.getElementsByClassName('featureOptions');
        //alert("outside - number of tables found: " + tables.length);

        if(tables.length > 0){
            observer.disconnect();
            console.log("number of tables found: " + tables.length);
            for(i=0; i<tables.length; i++){
                (function(i) {
                    var sp = document.createElement('span');
                    var act_table = document.createElement('table');
                    act_table.id = 'act-tests-' + i;
                    act_table.style = 'display:none';//'visibility: visible';
                    act_table.innerHTML ='<tbody>blah blah html html</tbody>';
                    sp.appendChild(act_table);

                    tables[i].parentElement.appendChild(sp);
                    var row   = tables[i].insertRow(-1);
                    var cell = row.insertCell(0);
                    var cell1 = row.insertCell(1);
                    cell1.className = "optionLabel pull-left";

                    var button = document.createElement('button');
                    button.innerHTML = 'Show ACT tests';
                    button.className = 'btn pull-left';
                    button.type = 'button';
                    button.onclick = function(){
                        var lTable = document.getElementById(act_table.id);
                        console.log(act_table.id + ' ' + lTable);
                        lTable.style.display = (lTable.style.display == 'block') ? 'none' : 'block';
                    };

                    cell1.appendChild(button); //.innerHTML = '<input class="btn pull-left" type="button" onclick="toggleTable();" value="Show ACT tests"/>' ;
                })(i);
            }
        }
    });

Upvotes: 0

Views: 59

Answers (1)

wander
wander

Reputation: 957

Two mistakes:

  1. act_table.style = 'display:none' will not hide the element, you shall use act_table.style.display = "none" instead

  2. Now that act_table is not hidden, the lTable.style.display will be empty string, not block, so the table will only be hidden after second click(first click will set lTable.style.display = "block", and when clicked again, (lTable.style.display == 'block') will be fulfilled)

Upvotes: 2

Related Questions