JavaScript Fun Coding Projects
JavaScript Fun Coding Projects
// Array of quotes
In this example, we first get the list and all list items. We add a
dragstart event listener to each item that sets the data and effect
on the drag event. We then add a dragover event listener to the
list that prevents the default behavior and sets the drop effect.
Finally, we add a drop event listener to the list that prevents the
table.appendChild(tbody);
document.body.appendChild(table);
const fileInput =
document.querySelector('#file-input');
const dropArea = document.querySelector('#drop-area');
dropArea.addEventListener('dragover', e => {
e.preventDefault();
dropArea.classList.add('dragging');
});
dropArea.addEventListener('dragleave', e => {
e.preventDefault();
dropArea.classList.remove('dragging');
});
This code creates a drag and drop file uploader. We first get the
file input and drop area elements using querySelector(). We add
event listeners to the drop area for dragover, dragleave, and drop
events. When the user drags a file over the drop area, we prevent
the default behavior and add a CSS class to highlight the area.
When the user leaves the drop area, we remove the CSS class.
When the user drops the file, we prevent the default behavior,
remove the CSS class, and set the file input's files property to the
dropped files.
Stopwatch
const stopwatchDisplay =
document.querySelector('#stopwatch');
let startTime;
function updateStopwatch() {
const elapsed = Date.now() - startTime;
const minutes = Math.floor(elapsed / 60000);
const seconds = Math.floor((elapsed % 60000) / 1000);
const milliseconds = elapsed % 1000;
stopwatchDisplay.textContent =
`${minutes.toString().padStart(2,
'0')}:${seconds.toString().padStart(2,
'0')}.${milliseconds.toString().padStart(3, '0')}`;
}
function stopStopwatch() {
clearInterval(updateStopwatch);
}
startStopwatch();
Rock-Paper-Scissors Game
function playRound(playerChoice) {
const computerChoice =
choices[Math.floor(Math.random() * choices.length)];
let result = '';