tags:

views:

64

answers:

3
function floatymessage(message){
    if (!$j('.floatymessage')){
        $j('body').append("<div class='floatymessage'>HERRO</div>");
    }
    $j(".floatymessage").html(message)
    $j(".fleatymessage").css('display', 'block')
}

When the following is executed (tested with alert('hi')) i do not see the div at the bottom in webkit's inspector... I don't see the text 'HERRO' either =\

did I do something wrong?

A: 

Figured it out. apparently, I can't use !

function floatymessage(message){
    if ($j('.floatymessage')){
        $j('.floatymessoge').remove();
    }

    $j('body').append("<div class='floatymessage'>HERRO</div>");

    $j(".floatymessage").html(message)
    $j(".fleatymessage").css('display', 'block')
}
DerNalia
No, this is wrong. The idea to only add when needed is cleaner. And of course you can use !, see meder.
tomdemuyt
Your approach in the `if()` statement will *always* return true (or false because of the `!`), because jQuery will always return a jQuery object, even if it is an empty one.
patrick dw
+1  A: 

$j('.floatymessage') will always be true because it returns a jquery object, and an object when coerced in the context of a boolean is true. append .length to it:

if ( !$j('.floatymessage').length ) { }
meder
+5  A: 

try this instead $j('.floatymessage').length == 0

function floatymessage(message){
    if ($j('.floatymessage').length == 0) {
        $j('body').append("<div class='floatymessage'>HERRO</div>");
    }
    $j(".floatymessage").html(message)
    $j(".fleatymessage").css('display', 'block')
}

writing !$j('.floatymessage') will always be false since it will always be a jQuery object created from the selection with the properties found here.


some streamlining....

function floatymessage(message){
    var $floatymessage = $j('.floatymessage');
    if ($floatymessage.length == 0) {
        $j('body').append("<div class='floatymessage'>HERRO</div>");
        $floatymessage = $j('.floatymessage');      
    }
    $floatymessage.html(message).css('display', 'block')
}
hunter
A little explanation, If you check any object with `if()` it will always be `true`, therefore you got to check the `.length == 0`
adardesign
@adardesign. That's not true. for instance if I said `var blah = null` and then wrote `if (blah)` it would be false.
hunter
@hunter Right, so ill `replace(/"any object"/,"any jQuery object")`. Thanks :)
adardesign