Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

Dynamically created div doesn't show up

I'm trying to show a tooltip when a user clicks on a div element. I found this fiddle where a dynamically created div is used, but it doesn't get shown when I click on it. What am I doing wrong here?

$(document).ready(function(){

    $('.somefield').click(showBox).mouseleave(hideBox);

    function showBox(e){
        $newDiv = $('<div></div>');
        $newDiv.addClass('tooltip');
        $newDiv.append('adfhadfhadfhadfh')
        $(newDiv).fadeIn().css(({ left:  e.pageX, top: e.pageY }));
    }

    function hideBox(){
        $('.tooltip').fadeOut();
    }
});

Upvotes: 0

Views: 1258

Answers (3)

BrunoLM
BrunoLM

Reputation: 100381

Example on jsFiddle

You are using jQuery to create a div then later you try wrap an in-existent object in a jQuery object. Change $(newDiv) to $newDiv.

It doesn't show up because you need to add it on the document, you can append to body

$newDiv.appendTo("body");

If you are fading in, the element must first be hidden

$newDiv.css("display", "none");

So the fixed code looks like this

$(document).ready(function(){

    $('.somefield').click(showBox).mouseleave(hideBox);

    function showBox(e){
        var $newDiv = $('<div></div>');
        $newDiv.css("display", "none");
        $newDiv.addClass('tooltip');
        $newDiv.append('adfhadfhadfhadfh')
        $newDiv.appendTo("body");
        $newDiv.fadeIn().css(({ left:  e.pageX, top: e.pageY }));
    }

    function hideBox(){
        $('.tooltip').fadeOut();
    }
});

appart from the addition of $newDiv.appendTo("body"); also mind the var in the declaration of $newDiv

Upvotes: 1

kushyar
kushyar

Reputation: 1191

You are not appending your div to any other element inside DOM.

var newDiv = $("<div>", {
        'class': "tooltip"   
    });

newDiv.appendTo($('body'));
$('.tooltip').fadeIn().css(({ left:  e.pageX, top: e.pageY }));

Upvotes: 1

buritos
buritos

Reputation: 598

you need to insert $newDiv somewhere in the dom. for example $('body').append($newDiv)

Moreover $newDiv is implicit global which it shouldn't be. use var $newDiv = ... instead.

Upvotes: 0

Related Questions