Javascript Cheatsheet

Check if Element With ID Exists

With jquery...

if($("#" + name).length == 0) {  
  //it doesn't exist

Get Whether Checkbox Ticked

Use jquery .is(':checked')

Execute Script When Document Loaded


You can chain these multiple times and all will execute. E.g.



Using pure javascript, you can use:


This will execute when all of the body is loaded, but these cannot be "chained". You are setting the onload property of the body instead of adding more methods to a queue to be executed.

Fade Away Text On Click

The code below shows you how to have some text appear beside the mouse that will eventually fade away, when you click on something.

        <script src="" crossorigin="anonymous"></script>
        <script type="text/javascript">

        // Track the mouse position and set it to global variables
        var g_mouseX = 0;
        var g_mouseY = 0;
        $(document ).on("mousemove", function( event ) {
            g_mouseX = event.pageX;
            g_mouseY = event.pageY;

        function fadeAwayTextClickHandler(clickedElement, textToShow)
            var alpha = 1;
            var startingLeft = g_mouseX + 20;
            var startingTop = g_mouseY - 20;

            var fadeAwayTextElement = document.createElement("p");
            fadeAwayTextElement = $(fadeAwayTextElement);
            fadeAwayTextElement.css("position", "absolute");
            fadeAwayTextElement.css("top", g_mouseY + "px");
            fadeAwayTextElement.css("left", startingLeft + "px");
            fadeAwayTextElement.css("z-index", 100);

            fadeAwayTextElement.css("color", "rgba(0,0,0, " + alpha + ")");

            var difference = 0;
            var step = 1;
            var alphaStep = 0.02;

            var fader = function() {
                alpha -= alphaStep;
                difference += step;

                fadeAwayTextElement.css("color", "rgba(0,0,0, " + alpha + ")");
                var newTop = startingTop + difference;
                fadeAwayTextElement.css("top", newTop);

                if (alpha > 0)



        <a href="javaScript:void(0);" onclick="fadeAwayTextClickHandler(this, 'Copied!');"">advancedClickHandler</a>





Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to and affiliated sites. More info.