Certainly! Below is the comprehensive JavaScript code tailored to your Forex Checklist Analyzer web application. This script fulfills all the specified requirements, including checklist management, real-time progress calculation, data persistence, import/export functionality, search capability, and smooth drag-and-drop reordering.
Please ensure to place this script within the <script> tag in your HTML as indicated.
<script>
// Forex Checklist Analyzer JavaScript
document.addEventListener('DOMContentLoaded', () => {
initializeChecklist('1');
});
function initializeChecklist(sectionId) {
// Load and render the checklist from LocalStorage
loadChecklist(sectionId);
// Initialize event listeners for import/export buttons
const container = document.getElementById(`containerSection${sectionId}`);
container.querySelector('.add-button').addEventListener('click', () => addCriteria(sectionId));
container.querySelector('.export-button').addEventListener('click', () => exportChecklistData(sectionId));
container.querySelector('.import-button').addEventListener('click', () => importChecklistData(sectionId));
// Event delegation for checklist items
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
checklistContainer.addEventListener('change', (e) => {
const target = e.target;
const itemId = target.closest('.checklist-item').dataset.id;
if (target.classList.contains('checkbox')) {
toggleActive(sectionId, itemId);
}
});
checklistContainer.addEventListener('dblclick', (e) => {
const target = e.target;
if (target.classList.contains('priority-label')) {
const itemId = target.closest('.checklist-item').dataset.id;
editPriority(sectionId, itemId);
}
});
checklistContainer.addEventListener('click', (e) => {
const target = e.target;
if (target.classList.contains('delete-button')) {
const itemId = target.closest('.checklist-item').dataset.id;
deleteCriteria(sectionId, itemId);
}
});
// Initialize drag and drop
initializeDragAndDrop(sectionId);
// Initialize editable title
const editableTitle = container.querySelector('.editable-title');
editableTitle.addEventListener('blur', () => saveChecklist(sectionId));
}
function getStorageKey(sectionId) {
return `forexChecklistSection${sectionId}`;
}
function loadChecklist(sectionId) {
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey)) || {
title: `Essential Criteria`,
criteria: []
};
// Update the editable title
const editableTitle = document.getElementById(`titleSection${sectionId}`);
editableTitle.textContent = data.title;
// Render the checklist
renderChecklist(sectionId, data.criteria);
// Update progress
updateProgress(sectionId, data.criteria);
}
function saveChecklist(sectionId) {
const storageKey = getStorageKey(sectionId);
const container = document.getElementById(`containerSection${sectionId}`);
const editableTitle = container.querySelector('.editable-title').textContent.trim() || `Essential Criteria`;
const criteria = Array.from(container.querySelectorAll('.checklist-item')).map(item => ({
id: item.dataset.id,
name: item.querySelector('textarea').value.trim(),
priority: parseInt(item.querySelector('.priority-label').textContent),
active: item.querySelector('.checkbox').checked
}));
const data = {
title: editableTitle,
criteria: criteria
};
localStorage.setItem(storageKey, JSON.stringify(data));
// Update progress
updateProgress(sectionId, criteria);
}
function renderChecklist(sectionId, criteria) {
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
checklistContainer.innerHTML = ''; // Clear existing items
criteria.forEach(criterion => {
const item = createChecklistItem(sectionId, criterion);
checklistContainer.appendChild(item);
});
// Update item counts
updateItemCounts(sectionId, criteria);
}
function createChecklistItem(sectionId, criterion) {
const itemDiv = document.createElement('div');
itemDiv.classList.add('checklist-item');
itemDiv.setAttribute('draggable', 'true');
itemDiv.dataset.id = criterion.id;
// Checkbox
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.classList.add('checkbox');
checkbox.checked = criterion.active;
itemDiv.appendChild(checkbox);
// Textarea for name
const textarea = document.createElement('textarea');
textarea.value = criterion.name;
textarea.addEventListener('input', () => saveChecklist(sectionId));
itemDiv.appendChild(textarea);
// Priority label
const priorityLabel = document.createElement('span');
priorityLabel.classList.add('priority-label', 'priority-box');
priorityLabel.textContent = criterion.priority;
itemDiv.appendChild(priorityLabel);
// Delete button
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('delete-button');
itemDiv.appendChild(deleteButton);
return itemDiv;
}
function addCriteria(sectionId) {
const name = prompt("Enter the name of the new criterion:");
if (name === null) return; // User cancelled
const trimmedName = name.trim();
if (trimmedName === '') {
alert("Criterion name cannot be empty.");
return;
}
const priorityInput = prompt("Enter the priority (number) for this criterion:");
if (priorityInput === null) return; // User cancelled
const priority = parseInt(priorityInput.trim());
if (isNaN(priority) || priority < 0) {
alert("Please enter a valid non-negative number for priority.");
return;
}
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey)) || {
title: `Essential Criteria`,
criteria: []
};
const newCriterion = {
id: generateUniqueId(),
name: trimmedName,
priority: priority,
active: true
};
data.criteria.push(newCriterion);
localStorage.setItem(storageKey, JSON.stringify(data));
// Render the new criterion
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const newItem = createChecklistItem(sectionId, newCriterion);
checklistContainer.appendChild(newItem);
// Update progress and item counts
updateProgress(sectionId, data.criteria);
updateItemCounts(sectionId, data.criteria);
}
function deleteCriteria(sectionId, itemId) {
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey));
if (!data) return;
data.criteria = data.criteria.filter(criterion => criterion.id !== itemId);
localStorage.setItem(storageKey, JSON.stringify(data));
// Remove from UI
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const itemToDelete = checklistContainer.querySelector(`.checklist-item[data-id="${itemId}"]`);
if (itemToDelete) {
checklistContainer.removeChild(itemToDelete);
}
// Update progress and item counts
updateProgress(sectionId, data.criteria);
updateItemCounts(sectionId, data.criteria);
}
function toggleActive(sectionId, itemId) {
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey));
if (!data) return;
const criterion = data.criteria.find(c => c.id === itemId);
if (criterion) {
criterion.active = !criterion.active;
localStorage.setItem(storageKey, JSON.stringify(data));
// Update progress and item counts
updateProgress(sectionId, data.criteria);
updateItemCounts(sectionId, data.criteria);
}
}
function editPriority(sectionId, itemId) {
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey));
if (!data) return;
const criterion = data.criteria.find(c => c.id === itemId);
if (!criterion) return;
const newPriorityInput = prompt("Enter the new priority (number) for this criterion:", criterion.priority);
if (newPriorityInput === null) return; // User cancelled
const newPriority = parseInt(newPriorityInput.trim());
if (isNaN(newPriority) || newPriority < 0) {
alert("Please enter a valid non-negative number for priority.");
return;
}
criterion.priority = newPriority;
localStorage.setItem(storageKey, JSON.stringify(data));
// Update UI
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const item = checklistContainer.querySelector(`.checklist-item[data-id="${itemId}"]`);
if (item) {
const priorityLabel = item.querySelector('.priority-label');
priorityLabel.textContent = newPriority;
}
// Update progress
updateProgress(sectionId, data.criteria);
}
function updateProgress(sectionId, criteria) {
const activeTotal = criteria
.filter(c => c.active)
.reduce((sum, c) => sum + c.priority, 0);
const cappedTotal = Math.min(activeTotal, 100);
const sliderFill = document.getElementById(`sliderFillSection${sectionId}`);
sliderFill.style.width = `${cappedTotal}%`;
const numericalLabel = document.getElementById(`numericalLabelSection${sectionId}`);
numericalLabel.textContent = `${cappedTotal}`;
// Adjust the position of the numerical label
numericalLabel.style.left = `${cappedTotal}%`;
// Update item counts
updateItemCounts(sectionId, criteria);
}
function updateItemCounts(sectionId, criteria) {
const totalSpan = document.getElementById(`totalItemsSection${sectionId}`);
const activeSpan = document.getElementById(`activeItemsSection${sectionId}`);
totalSpan.textContent = criteria.length;
const activeCount = criteria.filter(c => c.active).length;
activeSpan.textContent = activeCount;
}
function exportChecklistData(sectionId) {
const storageKey = getStorageKey(sectionId);
const data = JSON.parse(localStorage.getItem(storageKey));
if (!data) {
alert("No data to export.");
return;
}
const dataStr = JSON.stringify(data, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `forex_checklist_section${sectionId}.json`;
a.click();
URL.revokeObjectURL(url);
}
function importChecklistData(sectionId) {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.onchange = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const importedData = JSON.parse(event.target.result);
validateImportedData(importedData);
// Save to LocalStorage
const storageKey = getStorageKey(sectionId);
localStorage.setItem(storageKey, JSON.stringify(importedData));
// Render the imported checklist
renderChecklist(sectionId, importedData.criteria);
updateProgress(sectionId, importedData.criteria);
alert("Checklist imported successfully!");
} catch (error) {
alert("Failed to import checklist. Please ensure the JSON file is properly formatted.");
console.error(error);
}
};
reader.readAsText(file);
};
input.click();
}
function validateImportedData(data) {
if (!data.criteria || !Array.isArray(data.criteria)) {
throw new Error("Invalid data format.");
}
data.criteria.forEach(c => {
if (typeof c.id !== 'string' || typeof c.name !== 'string' || typeof c.priority !== 'number' || typeof c.active !== 'boolean') {
throw new Error("Invalid criterion format.");
}
});
}
function searchCriteria(sectionId) {
const searchTerm = document.getElementById(`searchBoxSection${sectionId}`).value.toLowerCase();
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const items = checklistContainer.querySelectorAll('.checklist-item');
items.forEach(item => {
const name = item.querySelector('textarea').value.toLowerCase();
if (name.includes(searchTerm)) {
item.style.display = 'flex';
} else {
item.style.display = 'none';
}
});
}
function generateUniqueId() {
return 'id-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
}
function initializeDragAndDrop(sectionId) {
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
let dragSrcEl = null;
checklistContainer.addEventListener('dragstart', (e) => {
const item = e.target.closest('.checklist-item');
if (item) {
dragSrcEl = item;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', item.outerHTML);
item.classList.add('dragging');
}
});
checklistContainer.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const target = e.target.closest('.checklist-item');
if (target && target !== dragSrcEl) {
const rect = target.getBoundingClientRect();
const next = (e.clientY - rect.top) / (rect.bottom - rect.top) > 0.5;
checklistContainer.insertBefore(dragSrcEl, next ? target.nextSibling : target);
}
});
checklistContainer.addEventListener('drop', (e) => {
e.preventDefault();
if (dragSrcEl) {
dragSrcEl.classList.remove('dragging');
saveReorderedChecklist(sectionId);
dragSrcEl = null;
}
});
checklistContainer.addEventListener('dragend', () => {
if (dragSrcEl) {
dragSrcEl.classList.remove('dragging');
dragSrcEl = null;
}
});
}
function saveReorderedChecklist(sectionId) {
const storageKey = getStorageKey(sectionId);
const checklistContainer = document.getElementById(`checklistContainerSection${sectionId}`);
const items = checklistContainer.querySelectorAll('.checklist-item');
const data = {
title: document.getElementById(`titleSection${sectionId}`).textContent.trim(),
criteria: Array.from(items).map(item => ({
id: item.dataset.id,
name: item.querySelector('textarea').value.trim(),
priority: parseInt(item.querySelector('.priority-label').textContent),
active: item.querySelector('.checkbox').checked
}))
};
localStorage.setItem(storageKey, JSON.stringify(data));
// Update progress
updateProgress(sectionId, data.criteria);
}
</script>
Explanation of the JavaScript Code
-
Initialization (DOMContentLoaded Event)
- When the document is fully loaded, the
initializeChecklist function is invoked for section '1'. This sets up the checklist by loading existing data, rendering the UI, and setting up necessary event listeners.
-
Data Structure and LocalStorage Handling
getStorageKey(sectionId): Generates a unique key for storing checklist data in LocalStorage based on the section ID.
loadChecklist(sectionId): Retrieves checklist data from LocalStorage. If no data exists, it initializes with an empty criteria list. It then updates the editable title, renders the checklist, and updates the progress bar.
saveChecklist(sectionId): Saves the current state of the checklist (including the title and all criteria) to LocalStorage. It also updates the progress bar accordingly.
-
Rendering the Checklist
renderChecklist(sectionId, criteria): Clears the existing checklist UI and repopulates it with the current list of criteria. It also updates the total and active item counts.
createChecklistItem(sectionId, criterion): Creates a DOM element for a single checklist item, including the checkbox, editable textarea for the criterion name, priority label, and delete button.
-
Checklist Management Functions
addCriteria(sectionId): Prompts the user to enter a new criterion's name and priority. It validates the inputs, adds the new criterion to the data structure, updates LocalStorage, and renders the new item in the UI.
deleteCriteria(sectionId, itemId): Removes a criterion from the data structure and updates the UI and LocalStorage.
toggleActive(sectionId, itemId): Toggles the active state of a criterion when its checkbox is clicked and updates the progress bar.
editPriority(sectionId, itemId): Allows the user to edit the priority of a criterion via a prompt. It validates the input and updates both the data and UI accordingly.
-
Progress Bar and Item Counts
- : Calculates the total priority of active criteria, caps it at 100, and updates the width of the progress bar and the numerical label. It also adjusts the position of the numerical label to align with the progress bar.
Notes and Recommendations
-
Data Validation: The script includes thorough validation for user inputs when adding or editing criteria, ensuring that the criterion name is not empty and that the priority is a valid non-negative number.
-
Error Handling: Importing data includes error handling to alert the user in case of improperly formatted JSON files.
-
User Experience: The progress bar and numerical label update in real-time, providing immediate feedback to the user as they interact with the checklist.
-
Drag-and-Drop: The drag-and-drop functionality is implemented using native JavaScript APIs, ensuring smooth reordering of checklist items without relying on external libraries.
-
Extensibility: Although the current implementation focuses on a single section (sectionId = '1'), the code is structured in a way that allows for easy extension to multiple sections if needed in the future.
This JavaScript code should seamlessly integrate with your provided HTML and CSS, delivering a fully functional Forex Checklist Analyzer web application. If you encounter any issues or have further customization requests, feel free to ask!