Home > OS >  JQuery problem turning HTML element 'visibility' property on and off
JQuery problem turning HTML element 'visibility' property on and off

Time:11-05

Am trying to create a button that when clicked, shows the table with id 'compose1' and when the button is clicked again, the table collapses and is invisible.

The code works fine on first click, and shows the table, but won't work on second click. The table won't collapse back on second click.

I know the issue is somewhere at the code

var msgAttr= $(`#compose${msgid}`).style.visibility

because it gives me the error Uncaught TypeError: Cannot read properties of undefined (reading 'visibility').

Could you help me spot where the issue is?

Thanks in advance!

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a style="text-decoration: none;" href="#" onclick="composeMsg('1'); return false;" title="Button"> Click Button </a>


<table width="100%" height="100%" border="0" id="compose1" style="visibility: collapse;">
<tr>
<td align="bottom" valign="bottom">
My Table
</td>
</tr>
</table>

<script>
    function composeMsg(msgid) {  

        var msgAttr= $(`#compose${msgid}`).style.visibility; 
        //var msgAttr = 'hidden';
        
        if(msgAttr=='hidden'){
          $(`#compose${msgid}`).attr("style","visibility: visible;"); 
        } else {
          $(`#compose${msgid}`).attr("style","visibility: collapse;"); 
        }

    }  
</script>

CodePudding user response:

You are mixing jQuery and vanilla JavaScript syntax. jQuery doesn't work directly with the style property in the same way as vanilla JavaScript does. You should use jQuery's methods to manipulate CSS properties.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a style="text-decoration: none;" href="#" onclick="composeMsg('1'); return false;" title="Button"> Click Button </a>

<table width="100%" height="100%" border="0" id="compose1" style="display: none;">
    <tr>
        <td align="bottom" valign="bottom">
            My Table
        </td>
    </tr>
</table>

<script>
function composeMsg(msgid) {
    var msgElement = $(`#compose${msgid}`);
    if (msgElement.css('display') === 'none') {
        msgElement.css('display', 'table'); //show the table
    } else {
        msgElement.css('display', 'none'); //hide the table
    }
}
</script>

  • Related