MNie
MNie

Reputation: 1367

Adding existing canvas to a div dynamically

I have a problem with adding existing canvas to a div dynamically via jQuery. Also I try numerous options to append this but any one works.

Here is my code:

<div class="a"> 
    <div id="b"></div> 
    <div id="c" class="c"> 
    </div> 
</div>

jQuery:

$(document).ready(function()
{
    if($('.myDivIfLoad').text().length >= 0)
    {
        //$('canvas[class="canvasClass"]').appendTo($('.c')); // doesn't work
        //$('canvas[class="canvasClass"]').append($('.c')); // doesn't work
        //var canv= $('canvas[class="canvasClass"]'); //doesn't work
        //document.getElementById('c').appendChild(canv)        // doesn't work
        $('canvas.canvasClass').appendTo('.c')
        $(function()
        { 
            $(".a").hover(function()
            { 
                $(".a").stop(true, false).animate({right: "0" }, 800, 'easeOutQuint' ); 
            }, function()
            { 
                $(".a").stop(true, false).animate({right: "-245" }, 800, 'easeInQuint' ); 
            },1000); 
        }); 
    }
});

If someone could help me I will be very grateful!

Edit

If it depends in my code I based on this tutorial: http://w3lessons.info/demo/sliding-facebook-likebox/

Upvotes: 0

Views: 219

Answers (2)

dfsq
dfsq

Reputation: 193301

You can append it like this for example using appendTo method (instead of append):

$('canvas[class="canvasClass"]').appendTo('.c');

or better

$('canvas.canvasClass').appendTo('.c');

Or

var canv = $('canvas.canvasClass');
$('.c').append(canv);

Or even if you really want

var canv = $('canvas.canvasClass');
document.getElementById('c').appendChild(canv[0]);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Four things:

  1. In CSS, identifiers (id values, class names) cannot start with a digit, so the selector .3 is invalid (as is the selector #1, etc.). (You've said below that those aren't your real ids and classes, and that your real ones don't start with digits.)

    Consider starting your ids and class names with a letter so your selectors are valid.

  2. Your appendTo, not append, was the right way to go, it was just the selector that was the problem.

  3. canvas[class="canvasClass"] looks for a canvas with exactly the class canvasClass and no others. It'll match <canvas class="canvasClass">..</canvas>" but not <canvas class="foo canvasClass">..</canvas> or similar. The best way to select by class is a class selector, canvas.canvasClass, which will match any element with that class (even if it also has others).

  4. This is suspect: $('.myDivIfLoad').val().length. The class suggests it's a div, but divs don't have values. They have contents. You may want .text().length or .html().length or .children().length or .contents().length depending on what your goal with that line is.

Upvotes: 1

Related Questions