Where should this code be positioned within the javascript?

After improving this code, where should it be placed?
https://jsfiddle.net/xeqtcp5k/155/

    button.addEventListener("mousedown", function (evt) {
        if (evt.detail > 1) {
            evt.preventDefault();
        }
    }, false);

Towards the bottom
Which is where I originally had it placed, should I stick with this spot?

Above:
sent.addEventListener("click", function () {

or towards the top,

Above:
function playPauseIcon(play) {

Full Code:

(function iife() {
    "use strict";
    const player = document.getElementById("player");
    const button = document.getElementById("button");
    const value = document.getElementById("input");
    const sent = document.getElementById("sent");

    function playPauseIcon(play) {
        if (play) {
            button.classList.add("is-playing");
        } else {
            button.classList.remove("is-playing");
        }
    }
    button.addEventListener("click", function () {
        if (player.paused) {
            player.play();
            playPauseIcon(true);
        } else {
            player.pause();
            playPauseIcon(false);
        }
    });

    sent.addEventListener("click", function () {
        player.src = value.value;
        player.volume = 1.0;
        playPauseIcon(true);
    });
}());

Here’s the thing – event listeners aren’t really order-specific. So long as the element itself is loaded before you attach your listener, it shouldn’t matter. So loading your consts before you add the listeners is exactly right.

For the record, rather than making the value of your text input someValueHere, make that the placeholder attribute. It will display, but it won’t be the hard-coded value of the thing.

I usually put them alphabetically after variable declarations but before function definitions (except of course arrow functions which can’t be hoisted):

const element = document.getElementByID("element");
const freds = document.getElementsByClassName("fred");

const handleMe = () => // return something;

// 'e' comes before 'f'
element.addEventListener("click", handleIt);

for (fred of freds) {
    fred.addEventListener("keyup", handleMe);
}

/* If there were more functions, I will usually do a hybrid of the newspaper and
alphabetical:
functions go above the functions they depend on. If there are no dependencies
or they are equal, then I arrange them alphabetically.*/
function handleIt (event) {
    // do something
}

So something like that, but YMMV. And when you get a job, it may be dictated by your job’s style guide.

1 Like