add deselection of videos and just make it so you can type in the notes box instead of…
- User
add deselection of videos and just make it so you can type in the notes box instead of having a separate button
code - Assistant
add deselection of videos and just make it so you can type in the notes box instead of having a separate button
<h1>YouTube Notes App</h1>
<!-- Section to Add Video URL -->
<div class="form-section">
<h2>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>
<button type="submit">Add Video</button>
</form>
</div>
<!-- Section to Add Notes -->
<div class="form-section" id="addNoteSection" style="display:none;">
<h2>Add Notes</h2>
<form id="addNoteForm">
<label for="selectedVideo">Selected Video:</label>
<input type="text" id="selectedVideo" name="selectedVideo" readonly>
<label for="noteContent">Notes:</label>
<textarea id="noteContent" name="noteContent" rows="4" placeholder="Enter your notes here..." required></textarea>
<button type="submit">Add Note</button>
</form>
</div>
<h2>Saved Videos</h2>
<ul id="videoList">
<!-- Video items will be populated here -->
</ul>
<div id="videoDisplay">
<!-- Embedded video and notes will appear here -->
<div id="videoContainer" style="display:none;">
<h2>Video</h2>
<div id="playerWrapper">
<div id="videoPlayer"></div>
</div>
</div>
<div id="notesContainer" style="display:none;">
<h2>Notes</h2>
<div class="notes-section" id="notesSection">
<!-- Notes will be populated 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));
}
// Add a new video
async function addVideo(url) {
const videoID = getYouTubeID(url);
if (!videoID) {
alert('Please enter a valid YouTube URL.');
return;
}
const videos = getVideos();
// Check for duplicates
let video = videos.find(video => video.id === videoID);
if (video) {
alert('This video is already added.');
return;
}
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();
} catch (error) {
console.error(error);
alert('Unable to add video. Please check the URL and try again.');
}
}
// 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('addNoteForm').reset();
alert('Note added successfully!');
}
}
// Render the list of saved videos
function renderVideoList() {
const videos = getVideos();
const videoList = document.getElementById('videoList');
videoList.innerHTML = '';
videos.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.textContent = 'View';
viewButton.setAttribute('data-id', video.id);
viewButton.className = 'viewButton';
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.setAttribute('data-id', video.id);
deleteButton.className = 'deleteButton';
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('.viewButton');
viewButtons.forEach(button => {
button.addEventListener('click', () => displayVideo(button.getAttribute('data-id')));
});
const deleteButtons = document.querySelectorAll('.deleteButton');
deleteButtons.forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
deleteVideo(button.getAttribute('data-id'));
});
});
}
// Display the selected video and its notes
let currentDisplayedVideo = null;
let player;
let playerReady = false;
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 = '';
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 onclick="window.editNote('${id}', ${index})">✏️</button>
<button onclick="window.deleteNote('${id}', ${index})">🗑️</button>
</div>
`;
notesSection.appendChild(noteDiv);
});
videoContainer.style.display = 'block';
notesContainer.style.display = 'block';
// Show the Add Note section
const addNoteSection = document.getElementById('addNoteSection');
addNoteSection.style.display = 'block';
document.getElementById('selectedVideo').value = video.title;
// Scroll to video display
videoContainer.scrollIntoView({ behavior: 'smooth' });
}
// Delete a video
function deleteVideo(id) {
if (!confirm("Are you sure you want to delete this video and all its notes?")) return;
let videos = getVideos();
videos = videos.filter(video => video.id !== id);
saveVideos(videos);
renderVideoList();
// 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('addNoteSection').style.display = 'none';
currentDisplayedVideo = null;
}
}
// 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 newContent = prompt("Edit your note:", note.content);
if (newContent !== null) {
video.notes[noteIndex].content = newContent.trim();
saveVideos(videos);
renderVideoList();
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
}
}
// Delete a note
function deleteNote(videoId, noteIndex) {
const videos = getVideos();
const video = videos.find(v => v.id === videoId);
if (!video) return;
if (confirm("Are you sure you want to delete this note?")) {
video.notes.splice(noteIndex, 1);
saveVideos(videos);
renderVideoList();
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
}
}
// 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 Add Note form submission
document.getElementById('addNoteForm').addEventListener('submit', function(e) {
e.preventDefault();
if (!currentDisplayedVideo) {
alert('Please select a video first.');
return;
}
const content = document.getElementById('noteContent').value.trim();
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();
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'));
}
// Attach functions to window to make them accessible from inline onclick handlers
window.editNote = editNote;
window.deleteNote = deleteNote;
</script>
Certainly! I've updated your YouTube Notes App to incorporate the following features based on your requirements:
Deselection of Videos: Added a "Deselect" button that appears when a video is selected, allowing users to deselect the current video and hide the video display and notes sections.
Inline Note Adding: Removed the separate "Add Note" form and integrated a textarea directly into the notes section. Users can now type their notes and press "Enter" to add them without needing a separate button.
Below is the revised code with detailed comments highlighting the changes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>YouTube Notes App</title>
<style>
/* Existing styles remain unchanged */
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f4f4f4;
}
h1, h2 {
color: #333;
}
.form-section {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
margin-bottom: 30px;
}
input[type="text"], textarea {
width: 100%;
padding: 10px;
margin-top: 5px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
label {
font-weight: bold;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
#videoList {
list-style-type: none;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 15px;
}
#videoList li {
padding: 10px;
background-color: #fff;
margin-bottom: 5px;
cursor: pointer;
border: 1px solid #ddd;
border-radius: 4px;
display: flex;
align-items: center;
width: calc(33% - 10px);
box-sizing: border-box;
transition: background-color 0.3s;
}
#videoList li:hover {
background-color: #ececec;
}
.video-thumbnail {
width: 120px;
height: 90px;
margin-right: 10px;
flex-shrink: 0;
border-radius: 4px;
object-fit: cover;
}
.video-title {
flex-grow: 1;
font-size: 14px;
color: #333;
}
.video-actions {
display: flex;
gap: 5px;
}
.video-actions button {
background-color: #ff4d4d;
color: white;
border: none;
padding: 5px 8px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.video-actions button:hover {
background-color: #e60000;
}
#videoDisplay {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
#videoContainer, #notesContainer {
flex: 1 1 45%;
background-color: #fff;
padding: 15px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
iframe {
width: 100%;
height: 300px;
border: none;
border-radius: 4px;
}
.notes-section {
margin-top: 15px;
display: flex;
flex-direction: column;
gap: 10px;
}
.note-item {
background-color: #f9f9f9;
padding: 10px;
margin-bottom: 10px;
border-left: 4px solid #4CAF50;
border-radius: 3px;
position: relative;
}
.note-content {
margin-top: 5px;
white-space: pre-wrap; /* Preserve line breaks */
}
.note-actions {
position: absolute;
top: 10px;
right: 10px;
display: flex;
gap: 5px;
}
.note-actions button {
background-color: transparent;
border: none;
color: #888;
cursor: pointer;
font-size: 14px;
}
.note-actions button:hover {
color: #333;
}
/* New styles for inline note input */
.add-note-inline {
margin-top: 15px;
}
.add-note-inline textarea {
resize: vertical;
}
@media (max-width: 992px) {
#videoList li {
width: calc(50% - 10px);
}
}
@media (max-width: 600px) {
#videoList li {
width: 100%;
}
#videoContainer, #notesContainer {
flex: 1 1 100%;
}
}
</style>
</head>
<body>
<h1>YouTube Notes App</h1>
<!-- Section to Add Video URL -->
<div class="form-section">
<h2>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>
<button type="submit">Add Video</button>
</form>
</div>
<h2>Saved Videos</h2>
<ul id="videoList">
<!-- Video items will be populated here -->
</ul>
<div id="videoDisplay">
<!-- Embedded video and notes will appear here -->
<div id="videoContainer" style="display:none;">
<h2>Video</h2>
<div id="playerWrapper">
<div id="videoPlayer"></div>
</div>
<!-- Deselect Button -->
<button id="deselectButton" style="margin-top: 10px; background-color: #555;">Deselect Video</button>
</div>
<div id="notesContainer" style="display:none;">
<h2>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></textarea>
</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));
}
// Add a new video
async function addVideo(url) {
const videoID = getYouTubeID(url);
if (!videoID) {
alert('Please enter a valid YouTube URL.');
return;
}
const videos = getVideos();
// Check for duplicates
let video = videos.find(video => video.id === videoID);
if (video) {
alert('This video is already added.');
return;
}
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();
} catch (error) {
console.error(error);
alert('Unable to add video. Please check the URL and try again.');
}
}
// 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 = '';
alert('Note added successfully!');
}
}
// Render the list of saved videos
function renderVideoList() {
const videos = getVideos();
const videoList = document.getElementById('videoList');
videoList.innerHTML = '';
videos.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.textContent = 'View';
viewButton.setAttribute('data-id', video.id);
viewButton.className = 'viewButton';
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.setAttribute('data-id', video.id);
deleteButton.className = 'deleteButton';
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('.viewButton');
viewButtons.forEach(button => {
button.addEventListener('click', () => displayVideo(button.getAttribute('data-id')));
});
const deleteButtons = document.querySelectorAll('.deleteButton');
deleteButtons.forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
deleteVideo(button.getAttribute('data-id'));
});
});
}
// Display the selected video and its notes
let currentDisplayedVideo = null;
let player;
let playerReady = false;
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 = '';
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 onclick="window.editNote('${id}', ${index})">✏️</button>
<button onclick="window.deleteNote('${id}', ${index})">🗑️</button>
</div>
`;
notesSection.appendChild(noteDiv);
});
videoContainer.style.display = 'block';
notesContainer.style.display = 'block';
// Show the Deselect button
const deselectButton = document.getElementById('deselectButton');
deselectButton.style.display = 'inline-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' });
}
// Delete a video
function deleteVideo(id) {
if (!confirm("Are you sure you want to delete this video and all its notes?")) return;
let videos = getVideos();
videos = videos.filter(video => video.id !== id);
saveVideos(videos);
renderVideoList();
// 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;
}
}
// 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 newContent = prompt("Edit your note:", note.content);
if (newContent !== null) {
video.notes[noteIndex].content = newContent.trim();
saveVideos(videos);
renderVideoList();
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
}
}
// Delete a note
function deleteNote(videoId, noteIndex) {
const videos = getVideos();
const video = videos.find(v => v.id === videoId);
if (!video) return;
if (confirm("Are you sure you want to delete this note?")) {
video.notes.splice(noteIndex, 1);
saveVideos(videos);
renderVideoList();
if (currentDisplayedVideo === videoId) {
displayVideo(videoId);
}
}
}
// 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();
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'));
}
// Attach functions to window to make them accessible from inline onclick handlers
window.editNote = editNote;
window.deleteNote = deleteNote;
window.deselectVideo = deselectVideo;
// Handle Deselect button click
document.getElementById('deselectButton').addEventListener('click', deselectVideo);
</script>
</body>
</html>
Deselection of Videos:
videoContainer, a "Deselect Video" button is added. This button appears only when a video is selected.deselectVideo Function: This function hides the video and notes sections, stops the video playback, and resets the current selection.deselectVideo function when clicked.Inline Note Adding:
Enter key press (without the Shift key). When detected, it adds the note and clears the textarea. This allows users to add notes by simply typing and pressing Enter.Additional Enhancements:
Shift+Enter.Add a Video:
View and Add Notes:
Enter. To add a multi-line note, press Shift+Enter to insert a line break.Deselect a Video:
Edit or Delete Notes:
Delete a Video:
Feel free to further customize the app to fit your specific needs!
Not yet included in a published release.