Relisora Relisora - 4 months ago 10
jQuery Question

Checking visibility with jQuery (debug)

I followed a few posts to be able to check the visibility of a div :

HTML :

<div class="language" onclick="Show_Div()">
<div class="menu-langues">
//my code here
</div>
</div>


Script :

function Show_Div() {
$Div_id = "menu-langues";
if ( $(Div_id).is(':hidden')) {
($Div_id).show();
}
else {
($Div_id).hide();
}
}


Console :

Uncaught ReferenceError: Div_id is not defined


I can't see what i did wrong, can someone help me with this?

Thank's ! :)

Answer

Don't mix inline event handlers like onclick with jQuery. jQuery handlers will do a better job and have extra features. And, as @Rory McCrossan said, just use toggle.

Code:

$('.language').click(function(){
    // Show if hidden and hide if visible
    $('.menu-langues').toggle();
});

Html (no inline handler):

<div class="language">
  <div class="menu-langues">
    //my code here
  </div>
</div>

If you had multiples of the same button on the page, you can target the selection using a scoped selector (second parameter defines the scope):

$('.language').click(function(){
    // Show if hidden and hide if visible
    $('.menu-langues', this).toggle();
});