JavaScript Stuff

This is a playground for JS dev.

Part 1

User input/interaction

Player 1: Name

The Code

    const para = document.querySelector('#name-input');

    para.addEventListener('click', updateName);

    function updateName() {
        const name = prompt('Enter a new name');
        para.textContent = `Player 1: ${name}`;
    }

Q & A

Is ...querySelector('#id') the same as ...getElementById('id)?
Yes, exactly the same!

Lessons Learned

People interact with a website by clicking and typing. However, the most fundament action is the mouse click. Which, the 'website' 'listens' for with event listers such as ...addEventListener('event', function).

Part 2: Adding JS to a Page

The button example

    Where should JavaScript code be added?

    In <script></script> tags immediately before the </body> tag
        <script>
            ...code...
        </script>
    </body>
    As the page is generally parsed from top to bottom, putting the code at the very end allows the HTML to fully load before running your code.
    In <script></script> tags immediately before the </head> tag
    This requires a workaround as the body has not even started to load.
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                ...code...
            });
        </script>
    </head>
    This works because it has the browser listen for the 'DOMContentLoaded' event (the whole HTML page is loaded) and only then parse the interior JavaScript.
    In an external script.js file, linked immediately before the </head> tag
    This method runs into the same issues as the previous option, but the workaround is much simpler.
        <script src="/script.js" defer></script>
    </head>
    We are able to do away with the DOMContentLoaded code in favor of the defer attribute which accomplishes essentially the same thing.

    Hot and Cold Numbers

    Welcome to our number guessing game! We have randomly picked a number from 1 to 100. Each time you guess, we'll tell you if it's correct, too low, or too high. Seems easy, right? The catch is, you only have 7 guesses!