Al John
Al John

Reputation: 21

Hide div in jQuery if a box is empty

I created a Red box using div which is empty inside of the box, with a link outside of div red box ... like this.

<div id="click"> click me </div>

<div id="box"></div>

And I have added PHP code inside of Red box, what it does is when the file is open, it will only show the button with file name inside of the red box.

What I'm trying to do is that when loading the page, if Red box is empty (no button's inside of the Red box) then hide it automatically, if it is not empty then show the red box with buttons.

I also have another button that allows me to have toggle slide for the red box no matter if is empty or not.

see the code

$(document).ready(function () {
   if ($('#box').contents().length == 0){
   $('#box').hide();
} else {
   $('#box').show();
}
});

$(document).ready(function(){
    $("#click").click(function(){
        $("#box").slideToggle("slow");
    });
});

I tried with in CSSlike this...

 $("div:empty").hide();
 div:empty { display: none }

and in jQuery like

$('div').filter(function() {    
  return $.trim($(this).text()) === ''    
}).remove()

None of these working due to div Red box is also involved with blank space even it is an empty box, or is showing PHP code inside of the box and still consider for css or jquery, not an empty box.

How can I solve that to auto hide if a box is empty?

See sample code in jsfiddle

Upvotes: 0

Views: 2065

Answers (1)

CumminUp07
CumminUp07

Reputation: 1978

You can pull just the text from the box and if it just contains white space, after you trim it will see it as empty. Example:

$(document).ready(function () {
    if ($('#box').text().trim().length == 0){
        $('#box').hide();
    } else {
       $('#box').show();
    }
});

and an update to your fiddle working https://jsfiddle.net/t1oum9xe/

Upvotes: 2

Related Questions