NullVoxPopuli
NullVoxPopuli

Reputation: 65123

jQuery: $j('body').append(...) doesn't work?

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?

Upvotes: 1

Views: 5251

Answers (3)

hunter
hunter

Reputation: 63512

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')
}

Upvotes: 5

meder omuraliev
meder omuraliev

Reputation: 186562

$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 ) { }

Upvotes: 1

NullVoxPopuli
NullVoxPopuli

Reputation: 65123

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')
}

Upvotes: 0

Related Questions