user1150837
user1150837

Reputation: 3

Remove DIV only if empty

I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:

$(document).ready(function() {
    $.get('/codes/php/nf.php', function(a) {
        $('#nfbadge').html(a);
        $('#nfbadge:empty').remove();
    })
});
setInterval(function() {
    $.get('http://localhost/codes/php/nf.php', function(a) {
        $('#nfbadge').html(a);
        $('#nfbadge:empty').remove();
    })
}, 8000);

The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?

Upvotes: 0

Views: 600

Answers (4)

adeneo
adeneo

Reputation: 318232

You should probably do something more like this:

var elm = $('#nfbadge'),
      T = setInterval(getCodes, 8000);

function getCodes() {
    $.get('/codes/php/nf.php', function(a) {
        elm.html(a);
        if (elm.is(':empty') && elm.is(':visible')) {
            elm.hide();
        }else{
            elm.show();
        }
   });
}

Will need some more work on your part, but should get you on the right track!

Upvotes: 1

HandiworkNYC.com
HandiworkNYC.com

Reputation: 11104

If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.

In your PHP template you should include the #nfbadge div in a conditional statement, something like:

if($notifications) {
     echo '<div id="nfbadge">';
     //notification stuff
     echo '</div>';
}

Then with your jQuery code you could do something like the following:

 var $nfbadge = $('#nfbadge');
 if($nfbadge) {$nfbadge.html(a)}

Upvotes: 0

shaunsantacruz
shaunsantacruz

Reputation: 8930

.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead

Upvotes: 1

webdad3
webdad3

Reputation: 9080

Why don't you just make the div hidden?

http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/

Upvotes: 0

Related Questions