Greg Peckory
Greg Peckory

Reputation: 8058

Div created with jQuery does not show on screen

I'm using an online tutorial to learn some jQuery because I was told that was the way to go if I wanted to build websites. I know a reasonable amount of html, javascript and css. I basically copied this jQuery script from the online tutorial so the script can't be wrong. So my assumption is that I'm writing the script in the wrong place in my html document. Any ideas? Thanks for any answers in advance.

Also, i was told this creates a new div. I'm beginning to have doubts about that now. If it's wrong could you let me know how this is done properly. Cheers.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href = "Jquery.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        jQuery('<div/>', {
            id: 'box',
            css: {

                fontWeight: 500,
                color: 'green'

            },
            click: function(){
                alert('You clicked the box');
            }

        });
    </script>
</head>

<body>


</body>
</html>

Upvotes: 1

Views: 112

Answers (2)

mickadoo
mickadoo

Reputation: 3483

I'm no expert on jquery, but that looks different from what I usually deal with. I did the same thing in simpler common terms, there's probably a faster way of doing this but this works on my local setup..

Edit : looking at the accepted answer seems there was no need to rewrite it all.. oh well

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>
<script>
    $('body').html('<div id = "box">123</div>');
    $('#box').css('color','green');
    $('#box').css('font-weight','500');

    $('#box').click(function(){
        alert('You clicked here');
    });
</script>
</body>
</html>

Upvotes: 1

colestrode
colestrode

Reputation: 10658

You'll need to add that div to the DOM. One approach is to use the jQuery appendTo() method:

Working Demo

jQuery('<div/>', {
    id: 'box',
    css: {
        fontWeight: 500,
        color: 'green'
    },
    click: function () {
        alert('You clicked the box');
    }

}).appendTo('body');

Also, it is best practice to wrap your jQuery code inside a $(document).ready(function() {...}). This will ensure that the DOM elements you need to interact with will be present when your code runs. You can read more about that here: http://api.jquery.com/ready

Upvotes: 7

Related Questions