Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
370 lines (309 loc) Β· 10.1 KB
/
Copy pathscript.js
File metadata and controls
370 lines (309 loc) Β· 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// ===========================================
// My Book Library - JavaScript
// PhillyCoderDojo Session 17: JavaScript & DOM
// ===========================================
// ============================================
// SECTION 1: Global Variables
// ============================================
// Our books array - will be loaded from localStorage
// In C#, this would be: List<Book> books = new List<Book>();
let books = [];
// DOM element references - set when page loads
let bookForm;
let titleInput;
let authorInput;
let searchInput;
let bookList;
let bookCount;
let emptyMessage;
// ============================================
// SECTION 2: localStorage Functions
// ============================================
/**
* Save books to localStorage
* Think of this like File.WriteAllText() in C#
*/
function saveBooks() {
// JSON.stringify converts our array to a text string
// localStorage can only store strings!
const booksJson = JSON.stringify(books);
localStorage.setItem('myBooks', booksJson);
console.log('Saved', books.length, 'books to localStorage');
}
/**
* Load books from localStorage
* Think of this like File.ReadAllText() in C#
*/
function loadBooks() {
const savedBooks = localStorage.getItem('myBooks');
if (savedBooks) {
// JSON.parse converts the text string back to an array
books = JSON.parse(savedBooks);
console.log('Loaded', books.length, 'books from localStorage');
} else {
// No saved data - start with some sample books
books = getDefaultBooks();
console.log('No saved books found, using defaults');
}
}
/**
* Get default sample books
* In C#, this would return a new List<Book> with initial data
*/
function getDefaultBooks() {
return [
{
id: 1,
title: 'Harry Potter and the Sorcerer\'s Stone',
author: 'J.K. Rowling'
},
{
id: 2,
title: 'The Hobbit',
author: 'J.R.R. Tolkien'
},
{
id: 3,
title: 'Diary of a Wimpy Kid',
author: 'Jeff Kinney'
},
{
id: 4,
title: 'Percy Jackson: The Lightning Thief',
author: 'Rick Riordan'
}
];
}
// ============================================
// SECTION 3: Display Functions
// ============================================
/**
* Display all books on the page
* This is where DOM manipulation happens!
*/
function displayBooks(booksToDisplay) {
// Use all books if no specific list provided
if (booksToDisplay === undefined) {
booksToDisplay = books;
}
// Clear the current display
// innerHTML = '' removes all child elements
bookList.innerHTML = '';
// Update the book count
updateBookCount();
// Check if we have any books to show
if (booksToDisplay.length === 0) {
emptyMessage.style.display = 'block';
return;
} else {
emptyMessage.style.display = 'none';
}
// Loop through each book and create a card
// In C#, this would be: foreach (var book in booksToDisplay)
booksToDisplay.forEach(function(book) {
const card = createBookCard(book);
bookList.appendChild(card);
});
}
/**
* Create a book card element
* This shows how to create DOM elements dynamically
*
* In C#/WPF, this would be like creating a new UserControl
*/
function createBookCard(book) {
// Step 1: Create the container div
const card = document.createElement('div');
card.className = 'book-card';
// Add a data attribute to store the book's ID
// This helps us find the book later
card.setAttribute('data-id', book.id);
// Step 2: Create the title element
const title = document.createElement('h3');
title.textContent = book.title;
// Step 3: Create the author element
const author = document.createElement('p');
author.textContent = 'by ' + book.author;
// Step 4: Create the delete button
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = 'Delete';
// Step 5: Add click event to delete button
// In C#, this would be: deleteBtn.Click += (sender, e) => DeleteBook(book.id);
deleteBtn.addEventListener('click', function() {
deleteBook(book.id);
});
// Step 6: Assemble the card
card.appendChild(title);
card.appendChild(author);
card.appendChild(deleteBtn);
return card;
}
/**
* Update the book count display
*/
function updateBookCount() {
bookCount.textContent = books.length;
}
// ============================================
// SECTION 4: CRUD Operations
// ============================================
/**
* Add a new book
* CRUD = Create, Read, Update, Delete
* This is the "Create" operation
*/
function addBook(title, author) {
// Validate inputs
if (!title || !author) {
alert('Please enter both a title and author!');
return false;
}
// Create a new book object
// Date.now() gives us a unique ID (milliseconds since 1970)
const newBook = {
id: Date.now(),
title: title.trim(),
author: author.trim()
};
// Add to our array
// In C#: books.Add(newBook);
books.push(newBook);
// Save to localStorage
saveBooks();
// Refresh the display
displayBooks();
console.log('Added new book:', newBook.title);
return true;
}
/**
* Delete a book by ID
* This is the "Delete" operation in CRUD
*/
function deleteBook(id) {
// Ask for confirmation
const confirmed = confirm('Are you sure you want to delete this book?');
if (!confirmed) {
return; // User clicked Cancel
}
// Filter out the book with this ID
// In C#: books = books.Where(b => b.Id != id).ToList();
books = books.filter(function(book) {
return book.id !== id;
});
// Save to localStorage
saveBooks();
// Refresh the display
displayBooks();
console.log('Deleted book with ID:', id);
}
/**
* Search/filter books by title or author
* This is like LINQ's Where() in C#
*/
function searchBooks(searchTerm) {
// Convert to lowercase for case-insensitive search
const term = searchTerm.toLowerCase().trim();
if (term === '') {
// Empty search - show all books
displayBooks(books);
return;
}
// Filter books that match the search term
// In C#: books.Where(b => b.Title.Contains(term) || b.Author.Contains(term))
const filtered = books.filter(function(book) {
const titleMatch = book.title.toLowerCase().includes(term);
const authorMatch = book.author.toLowerCase().includes(term);
return titleMatch || authorMatch;
});
displayBooks(filtered);
console.log('Found', filtered.length, 'books matching "' + term + '"');
}
// ============================================
// SECTION 5: Event Handlers
// ============================================
/**
* Handle form submission
* This runs when user clicks "Add Book" button
*/
function handleFormSubmit(event) {
// IMPORTANT: Prevent the default form behavior
// Without this, the page would refresh and lose our data!
event.preventDefault();
// Get values from input fields
const title = titleInput.value;
const author = authorInput.value;
// Try to add the book
const success = addBook(title, author);
if (success) {
// Clear the form inputs
// form.reset() clears all inputs in the form
bookForm.reset();
// Focus back on the title input for easy adding
titleInput.focus();
}
}
/**
* Handle search input
* This runs every time the user types in the search box
*/
function handleSearchInput(event) {
const searchTerm = event.target.value;
searchBooks(searchTerm);
}
// ============================================
// SECTION 6: Initialization
// ============================================
/**
* Initialize the application
* This runs when the DOM is fully loaded
*/
function initializeApp() {
console.log('Initializing Book Library...');
// Step 1: Get references to DOM elements
// These are like finding controls on a Windows Form
bookForm = document.getElementById('bookForm');
titleInput = document.getElementById('titleInput');
authorInput = document.getElementById('authorInput');
searchInput = document.getElementById('searchInput');
bookList = document.getElementById('bookList');
bookCount = document.getElementById('bookCount');
emptyMessage = document.getElementById('emptyMessage');
// Verify all elements were found
if (!bookForm || !titleInput || !authorInput || !bookList) {
console.error('Could not find required DOM elements!');
return;
}
// Step 2: Load saved books from localStorage
loadBooks();
// Step 3: Display the books
displayBooks();
// Step 4: Set up event listeners
// In C#, these would be like: button.Click += HandleClick;
// Listen for form submissions
bookForm.addEventListener('submit', handleFormSubmit);
// Listen for search input
searchInput.addEventListener('input', handleSearchInput);
console.log('Book Library is ready!');
console.log('Total books:', books.length);
}
// ============================================
// SECTION 7: Start the Application
// ============================================
// Wait for the DOM to be fully loaded before running our code
// This is VERY important! Without this, our elements might not exist yet.
//
// In C#/WPF, this is similar to the Window.Loaded event
document.addEventListener('DOMContentLoaded', initializeApp);
// ============================================
// BONUS: Debugging Tips
// ============================================
// You can open the browser console (F12 -> Console tab) and type:
//
// books - See all books
// books.length - Count of books
// localStorage - See what's saved
// books.push({id: 999, title: 'Test', author: 'Me'}) - Add a book manually
// displayBooks() - Refresh the display
//
// This is great for testing and understanding how the code works!