Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript help using createElement() and appendChild()

I'm having trouble writing some JavaScript for a project. I have the HTML code:

<html>
<head>
<title>Mouse Tail and Spawn</title>
<script src="tail.js"></script>
</head>
<body>
<div id="tail" style="position:absolute; display:none">
Click to spawn an egg.
</div>
</body>
</html>

I want to write the JavaScript to have the text in the div to follow the mouse cursor and also for it to spawn an 'o' when and where the mouse is clicked. I'm wanting to use the DOM methods createElement and appendChild to do so but can't envisage in my head how to do it, at this stage I have no JavaScript written. Does anyone have any links to tutorials on this or have any tips to help.

like image 497
Crakrjack Avatar asked Aug 30 '26 01:08

Crakrjack


1 Answers

This is actually fairly straight-forward. We need only to listen for clicks on the root element, inspect the click event object for click coordinates, and set up some basic styling of an ad-hoc element:

// Listen for click events on the <body> element
document.documentElement.addEventListener( "click", function ( event ) {
    
    // Create an element to hold out "o", and some styles
    var element = document.createElement( "span" ),
        elStyle = {
            position: "absolute",
            top: event.clientY + "px",
            left: event.clientX + "px",
        };
    
    // Apply our styles to the element
    Object.keys( elStyle ).forEach( function ( property ) {
        element.style[ property ] = elStyle[ property ];
    });
    
    // Set the innerHTML of the element, and insert it into the <body>
    element.innerHTML = "o";
    document.body.appendChild( element );
    
});
html { cursor: pointer }
like image 125
Sampson Avatar answered Sep 01 '26 14:09

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!