3
\$\begingroup\$

Looking for feedback on any bad practices and general advice on how I might better structure my code.

$(function() {
    // Load song on page load
    var song = new Audio('./songs/DJ Snake - Middle (Bad Royale Remix).mp3');
    song.load();

    // Update song duration display
    song.addEventListener('timeupdate', function(){
        updateTime(song);
    });

    // Set the play/pause button to play when song ends
    song.onended = function() {
        $('#play-pause').toggleClass('fa-play').toggleClass('fa-pause');
    };

    // Play or pause song when play/pause button pressed
    $('#play-pause').click(function() {
        togglePlay(song);
    });

    // Play song that was clicked
    $('.song').click(function() {
        if (!song.paused) {
            togglePlay(song);
        }
        song.src = "./songs/" + $(this).data('audio-src');
        $('#current-artist').text($(this).find('.artist').text() + " - ");
        $('#current-title').text($(this).find('.title').text());
        $('#current-artwork').attr('src', $(this).find('.artwork').attr('src'));
        song.load();
        song.currentTime = 0;
        togglePlay(song);
    });

    // Marquee scrolling for current song info
    setInterval(function() {
        var $elmt = $('.current-song-info');
        if ($('h1', $elmt).prop('scrollWidth') > $elmt.width()) {
            if (typeof mq === 'undefined') {
                mq = $('.marquee').marquee({
                    duration: 15000,
                    delayBeforeStart: 0,
                    pauseOnHover: true,
                    startVisible: true,
                    gap: 15,
                    duplicated: true
                });
            }
        } else if (typeof mq !== 'undefined') {
            mq.marquee('destroy');
            mq = undefined;
        }
    }, 1000);
});

function togglePlay(song) {
    if (song.paused) {
        song.play();
    } else {
        song.pause();
    }
    $('#play-pause').toggleClass('fa-play').toggleClass('fa-pause');
}

function updateTime(song) {
    var currentMinutes = Math.floor(song.currentTime / 60);
    var currentSeconds = (Math.floor(song.currentTime % 60) < 10 ? '0' : '' ) + Math.floor(song.currentTime % 60);

    $('#current-time').text(currentMinutes + ":" + currentSeconds);
    $('#progress').css('width', song.currentTime / song.duration * 100 + '%');
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.