<h1>YouTube Notes App</h1>
<!-- Section to Add Video URL -->
<div class="form-section" aria-labelledby="add-video-heading">
<h2 id="add-video-heading">Add YouTube Video</h2>
<form id="addVideoForm">
<label for="videoURL">YouTube Video URL:</label>
<input type="text" id="videoURL" name="videoURL" placeholder="Enter YouTube URL" required aria-required="true">
<button type="submit"><i class="fa fa-plus"></i> Add Video</button>
<span id="addVideoLoader" class="loader" style="display:none;"></span>
</form>
</div>
<!-- Search Section -->
<div class="search-section" aria-labelledby="search-heading">
<h2 id="search-heading">Saved Videos</h2>
<div class="search-bar">
<input type="text" id="searchInput" placeholder="Search videos..." aria-label="Search videos">
<button id="clearSearchBtn" title="Clear Search"><i class="fa fa-times"></i></button>
</div>
</div>
<ul id="videoList" aria-live="polite">
<!-- Video items will be populated here -->
</ul>
<div id="videoDisplay">
<!-- Embedded video and notes will appear here -->
<div id="videoContainer" style="display:none;" aria-labelledby="video-heading">
<h2 id="video-heading">Video</h2>
<div id="playerWrapper">
<div id="videoPlayer"></div>
</div>
<button id="deselectButton" style="margin-top: 15px;"><i class="fa fa-times-circle"></i> Deselect Video</button>
</div>
<div id="notesContainer" style="display:none;" aria-labelledby="notes-heading">
<h2 id="notes-heading">Notes</h2>
<div class="notes-section" id="notesSection">
<!-- Notes will be populated here -->
</div>
<!-- Inline Note Input -->
<div class="add-note-inline">
<label for="inlineNoteContent">Add a new note:</label>
<textarea id="inlineNoteContent" name="inlineNoteContent" rows="3" placeholder="Type your note and press Enter..." required aria-required="true"></textarea>
</div>
</div>
</div>
<!-- Modal for Confirmations and Alerts -->
<div id="modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-heading">
<div class="modal-content">
<button class="close-btn" aria-label="Close Modal">×</button>
<div class="modal-header">
<h2 id="modal-heading">Modal Title</h2>
</div>
<div class="modal-body" id="modal-body">
<!-- Modal content goes here -->
</div>
<div class="modal-footer" id="modal-footer">
<!-- Modal buttons go here -->
</div>
</div>
</div>
<script>
// Function to extract YouTube Video ID from URL
function getYouTubeID(url) {
const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?(?:.*&)?v=|embed\/)|youtu\.be\/)([^\s&?]+)/;
const match = url.match(regex);
return match ? match[1] : null;
}
// Retrieve videos from localStorage or initialize empty array
function getVideos() {
const videos = localStorage.getItem('videos');
return videos ? JSON.parse(videos) : [];
}
// Save videos array to localStorage
function saveVideos(videos) {
localStorage.setItem('videos', JSON.stringify(videos));
}
// Function to show modal
function showModal(title, message, buttons = []) {
const modal = document.getElementById('modal');
const modalTitle = document.querySelector('.modal-header h2');
const modalBody = document.getElementById('modal-body');
const modalFooter = document.getElementById('modal-footer');
modalTitle.textContent = title;
modalBody.innerHTML = message;
modalFooter.innerHTML = '';
buttons.forEach(btn => {
const button = document.createElement('button');
button.textContent = btn.text;
button.className = btn.class || '';
if (btn.icon) {
const icon = document.createElement('i');
icon.className = btn.icon;
button.prepend(icon);
button.style.marginRight = '5px';
}
button.addEventListener('click', btn.handler);
modalFooter.appendChild(button);
});
modal.style.display = 'flex';
}
// Function to close modal
function closeModal() {
const modal = document.getElementById('modal');
modal.style.display = 'none';
}
// Add event listener to close modal when clicking outside the content
window.addEventListener('click', function(event) {
const modal = document.getElementById('modal');
if (event.target === modal) {
closeModal();
}
});
// Attach event listener to close button
document.querySelector('.close-btn').addEventListener('click', closeModal);
// Show loading indicator
function showLoading(show) {
const loader = document.getElementById('addVideoLoader');
if (show) {
loader.style.display = 'inline-block';
} else {
loader.style.display = 'none';
}
}
// Add a new video
async function addVideo(url) {
const videoID = getYouTubeID(url);
if (!videoID) {
showModal('Invalid URL', '<p>Please enter a valid YouTube URL.</p>', [
{ text: 'OK', handler: closeModal }
]);
return;
}
const videos = getVideos();
// Check for duplicates
let video = videos.find(video => video.id === videoID);
if (video) {
showModal('Duplicate Video', '<p>This video is already added.</p>', [
{ text: 'OK', handler: closeModal }
]);
return;
}
showLoading(true);
try {
// Fetch video details using oEmbed
const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoID}&format=json`);
if (!response.ok) {
throw new Error('Failed to fetch video details. Please ensure the URL is correct.');
}
const data = await response.json();
const title = data.title;
const thumbnail_url = data.thumbnail_url;
video = { id: videoID, url: url, title: title, thumbnail_url: thumbnail_url, notes: [] };
videos.push(video);
saveVideos(videos);
renderVideoList();
document.getElementById('addVideoForm').reset();
showModal('Success', '<p>Video added successfully!</p>', [
{ text: 'OK', handler: closeModal }
]);
} catch (error) {
console.error(error);
showModal('Error', `<p>Unable to add video. Please check the URL and try again.</p>`, [
{ text: 'OK', handler: closeModal }
]);
} finally {
showLoading(false);
}
}
// Add a new note to a video
function addNote(videoID, content) {
const videos = getVideos();
const video = videos.find(v => v.id === videoID);
if (!video) return;
if (content.trim() !== "") {
video.notes.push({ content: content.trim() });
saveVideos(videos);
renderVideoList();
if (currentDisplayedVideo === videoID) {
displayVideo(videoID);
}
document.getElementById('inlineNoteContent').value = '';
showModal('Success', '<p>Note added successfully!</p>', [
{ text: 'OK', handler: closeModal }
]);
}
}
// Render the list of saved videos
function renderVideoList(filter = '') {
const videos = getVideos();
const videoList = document.getElementById('videoList');
videoList.innerHTML = '';
const filteredVideos = videos.filter(video => video.title.toLowerCase().includes(filter.toLowerCase()));
if (filteredVideos.length === 0) {
videoList.innerHTML = '<p>No videos found.</p>';
return;
}
filteredVideos.forEach(video => {
const li = document.createElement('li');
const thumbnail = document.createElement('img');
thumbnail.src = video.thumbnail_url;
thumbnail.alt = video.title;
thumbnail.className = 'video-thumbnail';
const title = document.createElement('span');
title.textContent = video.title;
title.className = 'video-title';
const actionsDiv = document.createElement('div');
actionsDiv.className = 'video-actions';
const viewButton = document.createElement('button');
viewButton.innerHTML = '<i class="fa fa-eye"></i> View';
viewButton.setAttribute('data-id', video.id);
viewButton.className = 'view-btn';
viewButton.title = 'View Video and Notes';
const deleteButton = document.createElement('button');
deleteButton.innerHTML = '<i class="fa fa-trash"></i> Delete';
deleteButton.setAttribute('data-id', video.id);
deleteButton.className = 'delete-btn';
deleteButton.title = 'Delete Video';
actionsDiv.appendChild(viewButton);
actionsDiv.appendChild(deleteButton);
li.appendChild(thumbnail);
li.appendChild(title);
li.appendChild(actionsDiv);
videoList.appendChild(li);
});
// Attach event listeners to the newly added buttons
const viewButtons = document.querySelectorAll('.view-btn');
viewButtons.forEach(button => {
button.addEventListener('click', () => displayVideo(button.getAttribute('data-id')));
});
const deleteButtons = document.querySelectorAll('.delete-btn');
deleteButtons.forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
confirmDeleteVideo(button.getAttribute('data-id'));
});
});
}
// Confirm before deleting a video
function confirmDeleteVideo(id) {
showModal('Confirm Delete', '<p>Are you sure you want to delete this video and all its notes?</p>', [
{ text: 'Cancel', handler: closeModal },
{ text: 'Delete', class: 'delete-confirm-btn', handler: () => { deleteVideo(id); closeModal(); } }
]);
}
// Delete a video
function deleteVideo(id) {
let videos = getVideos();
videos = videos.filter(video => video.id !== id);
saveVideos(videos);
renderVideoList(document.getElementById('searchInput').value);
// Clear video display if deleted video was displayed
if (currentDisplayedVideo === id) {
if (player && typeof player.stopVideo === 'function') {
player.stopVideo();
}
document.getElementById('videoContainer').style.display = 'none';
document.getElementById('notesContainer').style.display = 'none';
document.getElementById('deselectButton').style.display = 'none';
currentDisplayedVideo = null;
}
showModal('Deleted', '<p>Video and its notes have been deleted.</p>', [
{ text: 'OK', handler: closeModal }
]);
}
// Edit a note
function editNote(videoId, noteIndex) {
const videos = getVideos();
const video = videos.find(v => v.id === videoId);
if (!video) return;
const note = video.notes[noteIndex];
const modalContent = `
<label for="editNoteContent">Edit your note:</label>
<textarea id="editNoteContent" rows="4" required>${sanitizeHTML(note.content)}</textarea>
`;
showModal('Edit Note', modalContent, [
{ text: 'Cancel', handler: closeModal },
{ text: 'Save', handler: () => {
const newContent = document.getElementById('editNoteContent').value.trim();
if (newContent !== "") {
video.notes[noteIndex].content = newContent;
saveVideos(videos);
renderVideoList(document.getElementById('searchInput').value);
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
closeModal();
showModal('Success', '<p>Note updated successfully!</p>', [
{ text: 'OK', handler: closeModal }
]);
} else {
// Highlight the textarea if empty
document.getElementById('editNoteContent').style.borderColor = '#e74c3c';
}
} }
]);
}
// Confirm before deleting a note
function confirmDeleteNote(videoId, noteIndex) {
showModal('Confirm Delete', '<p>Are you sure you want to delete this note?</p>', [
{ text: 'Cancel', handler: closeModal },
{ text: 'Delete', class: 'delete-confirm-btn', handler: () => { deleteNote(videoId, noteIndex); closeModal(); } }
]);
}
// Delete a note
function deleteNote(videoId, noteIndex) {
const videos = getVideos();
const video = videos.find(v => v.id === videoId);
if (!video) return;
video.notes.splice(noteIndex, 1);
saveVideos(videos);
renderVideoList(document.getElementById('searchInput').value);
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
showModal('Deleted', '<p>Note has been deleted.</p>', [
{ text: 'OK', handler: closeModal }
]);
}
// Simple sanitization to prevent XSS
function sanitizeHTML(str) {
const temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
}
// Handle Add Video form submission
document.getElementById('addVideoForm').addEventListener('submit', async function(e) {
e.preventDefault();
const url = document.getElementById('videoURL').value.trim();
await addVideo(url);
});
// Handle Inline Note addition on Enter key
document.getElementById('inlineNoteContent').addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) { // Press Enter without Shift
e.preventDefault();
const content = e.target.value.trim();
if (content !== "") {
addNote(currentDisplayedVideo, content);
}
}
});
// Initial render
renderVideoList();
// YouTube IFrame API for controlling video playback
function loadYouTubeAPI() {
const tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
loadYouTubeAPI();
let player;
let playerReady = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('videoPlayer', {
height: '300',
width: '100%',
videoId: '', // Start with no video
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
playerReady = true;
// Dispatch a custom event to notify that the player is ready
window.dispatchEvent(new Event('playerReady'));
}
// Display the selected video and its notes
let currentDisplayedVideo = null;
function displayVideo(id) {
const videos = getVideos();
const video = videos.find(v => v.id === id);
if (!video) return;
currentDisplayedVideo = id;
const videoContainer = document.getElementById('videoContainer');
const notesContainer = document.getElementById('notesContainer');
const notesSection = document.getElementById('notesSection');
// Load the video using the YouTube IFrame API
if (playerReady) {
player.loadVideoById(video.id);
} else {
// If player isn't ready yet, wait until it is
window.addEventListener('playerReady', () => {
player.loadVideoById(video.id);
}, { once: true });
}
// Populate notes
notesSection.innerHTML = '';
if (video.notes.length === 0) {
notesSection.innerHTML = '<p>No notes added yet.</p>';
} else {
video.notes.forEach((note, index) => {
const noteDiv = document.createElement('div');
noteDiv.className = 'note-item';
noteDiv.innerHTML = `
<div class="note-content">${sanitizeHTML(note.content)}</div>
<div class="note-actions">
<button aria-label="Edit Note"><i class="fa fa-edit"></i></button>
<button aria-label="Delete Note"><i class="fa fa-trash"></i></button>
</div>
`;
// Attach event listeners to buttons
const [editBtn, deleteBtn] = noteDiv.querySelectorAll('button');
editBtn.addEventListener('click', () => editNote(id, index));
deleteBtn.addEventListener('click', () => confirmDeleteNote(id, index));
notesSection.appendChild(noteDiv);
});
}
videoContainer.style.display = 'block';
notesContainer.style.display = 'block';
// Scroll to video display
videoContainer.scrollIntoView({ behavior: 'smooth' });
}
// Deselect the currently selected video
function deselectVideo() {
if (player && typeof player.stopVideo === 'function') {
player.stopVideo();
}
document.getElementById('videoContainer').style.display = 'none';
document.getElementById('notesContainer').style.display = 'none';
document.getElementById('deselectButton').style.display = 'none';
currentDisplayedVideo = null;
// Optionally, scroll back to top or to the video list
window.scrollTo({ top: 0, behavior: 'smooth' });
}
// Handle Deselect button click
document.getElementById('deselectButton').addEventListener('click', deselectVideo);
// Search Functionality
document.getElementById('searchInput').addEventListener('input', function(e) {
const filter = e.target.value.trim();
renderVideoList(filter);
});
// Clear Search Button
document.getElementById('clearSearchBtn').addEventListener('click', function() {
document.getElementById('searchInput').value = '';
renderVideoList();
document.getElementById('searchInput').focus();
});
// Attach functions to window to make them accessible from inline onclick handlers (if any)
window.editNote = editNote;
window.deleteNote = deleteNote;
window.confirmDeleteVideo = confirmDeleteVideo;
window.confirmDeleteNote = confirmDeleteNote;
window.deselectVideo = deselectVideo;
</script>
Hello! I'd be happy to help you fix the bug in your YouTube Notes App. I've reviewed your code and identified some potential issues that might be causing problems. Below, I'll outline these issues along with suggested fixes.
Issue 1: 'Deselect Video' Button Not Showing
Problem:
When you select a video to view, the "Deselect Video" button may not appear, making it difficult to return to the main list.
Solution:
In your displayVideo function, you're showing the videoContainer and notesContainer, but you're not making the deselectButton visible. You need to set its display property to block or inline-block when a video is selected.
Code Fix:
Add the following line to your displayVideo function:
javascript
function displayVideo(id) {
// existing code...
videoContainer.style.display = 'block';
notesContainer.style.display = 'block';
// Add this line to show the deselect button
document.getElementById('deselectButton').style.display = 'inline-block';
// Scroll to video display
videoContainer.scrollIntoView({ behavior: 'smooth' });
}
Issue 2: YouTube IFrame API Not Loading Correctly
Problem:
The YouTube player might not initialize properly if the onYouTubeIframeAPIReady function isn't accessible globally.
Solution:
Ensure that the onYouTubeIframeAPIReady function is attached to the window object so that the YouTube IFrame API can call it when it's ready.
Code Fix:
Modify your function definition as follows:
javascript
// Assign the function to the global window object
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('videoPlayer', {
height: '300',
width: '100%',
videoId: '', // Start with no video
events: {
'onReady': onPlayerReady
}
});
};
Issue 3: Error Handling in 'addVideo' Function
Problem:
If fetching video details from the oEmbed API fails (e.g., due to an invalid URL or network issue), your code might not handle the error gracefully, leading to unexpected results.
Solution:
Improve your error handling by checking the response before parsing it. Also, encode the video URL to handle special characters.
Code Fix:
javascript
async function addVideo(url) {
const videoID = getYouTubeID(url);
if (!videoID) {
showModal('Invalid URL', '<p>Please enter a valid YouTube URL.</p>', [
{ text: 'OK', handler: closeModal }
]);
return;
}
const videos = getVideos();
// Check for duplicates
let video = videos.find(video => video.id === videoID);
if (video) {
showModal('Duplicate Video', '<p>This video is already added.</p>', [
{ text: 'OK', handler: closeModal }
]);
return;
}
showLoading(true);
try {
// Encode URL to handle special characters
const encodedURL = encodeURIComponent(`https://www.youtube.com/watch?v=${videoID}`);
// Fetch video details using oEmbed
const response = await fetch(`https://www.youtube.com/oembed?url=${encodedURL}&format=json`);
if (!response.ok) {
throw new Error('Failed to fetch video details. Please ensure the URL is correct.');
}
const data = await response.json();
const title = data.title;
const thumbnail_url = data.thumbnail_url;
video = { id: videoID, url: url, title: title, thumbnail_url: thumbnail_url, notes: [] };
videos.push(video);
saveVideos(videos);
renderVideoList();
document.getElementById('addVideoForm').reset();
showModal('Success', '<p>Video added successfully!</p>', [
{ text: 'OK', handler: closeModal }
]);
} catch (error) {
console.error(error);
showModal('Error', `<p>${error.message}</p>`, [
{ text: 'OK', handler: closeModal }
]);
} finally {
showLoading(false);
}
}
Issue 4: Extracting YouTube Video ID
Problem:
The getYouTubeID function may not correctly extract the video ID from all valid YouTube URLs due to limitations in the regular expression.
Solution:
Use a more comprehensive regular expression to handle various YouTube URL formats.
Code Fix:
Update your getYouTubeID function:
javascript
function getYouTubeID(url) {
const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([^&\n?#]+)/;
const match = url.match(regex);
return match ? match[1] : null;
}
This regex handles different YouTube URL formats, including:
https://www.youtube.com/watch?v=VIDEO_ID
https://youtu.be/VIDEO_ID
https://www.youtube.com/embed/VIDEO_ID
https://www.youtube.com/v/VIDEO_ID
Issue 5: Player 'loadVideoById' May Be Called Before Player Is Ready
Problem:
There's a potential race condition where player.loadVideoById(video.id) is called before the player is fully ready, especially on slower connections.
Solution:
Use a Promise to ensure that player.loadVideoById is only called after the player is ready.
Code Fix:
Define a Promise that resolves when the player is ready:
javascript
let playerReadyPromise = new Promise((resolve) => {
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('videoPlayer', {
height: '300',
width: '100%',
videoId: '', // Start with no video
events: {
'onReady': (event) => {
onPlayerReady(event);
resolve(); // Resolve the promise when player is ready
}
}
});
};
});
function displayVideo(id) {
const videos = getVideos();
const video = videos.find(v => v.id === id);
if (!video) return;
currentDisplayedVideo = id;
const videoContainer = document.getElementById('videoContainer');
const notesContainer = document.getElementById('notesContainer');
const notesSection = document.getElementById('notesSection');
// Wait until the player is ready
playerReadyPromise.then(() => {
player.loadVideoById(video.id);
});
// Populate notes...
// existing code...
videoContainer.style.display = 'block';
notesContainer.style.display = 'block';
document.getElementById('deselectButton').style.display = 'inline-block';
// Scroll to video display
videoContainer.scrollIntoView({ behavior: 'smooth' });
}
Issue 6: Sanitizing User Input Properly
Problem:
While you have a sanitizeHTML function to prevent XSS attacks, when inserting HTML content dynamically, you should also consider using textContent instead of innerHTML when possible.
Solution:
Set the text content directly to avoid any potential HTML injection.
Code Fix:
In your note rendering code, modify it as follows:
javascript
const noteContentDiv = document.createElement('div');
noteContentDiv.className = 'note-content';
noteContentDiv.textContent = note.content; // Use textContent instead of innerHTML
noteDiv.appendChild(noteContentDiv);
Similarly, when populating the edit textarea:
javascript
const modalContent = `
<label for="editNoteContent">Edit your note:</label>
<textarea id="editNoteContent" rows="4" required></textarea>
`;
showModal('Edit Note', modalContent, [
// buttons...
]);
// After showing the modal, set the textarea value safely
document.getElementById('editNoteContent').value = note.content;
Additional Recommendations
Check Console for Errors:
Open your browser's developer console to see if there are any error messages. This can provide valuable clues about what's going wrong.
Verify Element IDs and Classes:
Ensure that all element IDs and class names used in your JavaScript match those in your HTML.
Ensure Local Storage Availability:
Be aware that localStorage might not be available in some browser modes (like incognito/private browsing). Add checks to handle such cases gracefully.
Test in Different Browsers:
Sometimes, issues can be browser-specific. Test your app in multiple browsers to see if the issue persists.
Network Issues:
If you're running the app locally, ensure that CORS policies aren't blocking your requests to YouTube's oEmbed API. You might need to serve your app over a local server rather than opening the HTML file directly.
Summary
By addressing these issues, your YouTube Notes App should function more reliably. Make sure to update your code with the suggested fixes and test each feature thoroughly.
If you continue to experience problems, please provide:
Specific details about what's not working.
Any error messages from the console.
Steps to reproduce the issue.
I'll be happy to assist you further based on that information.
Feel free to ask if you have any questions or need clarification on any of the steps!