JavaScript
Add interactivity and enhanced functionality with JavaScript.
Including JavaScript Files
In your template:
{% block body_javascript %}
{{ parent() }} {# Include default scripts #}
{# Your theme scripts #}
<script src="{{ asset('assets/theme/my-theme/js/main.js') }}"></script>
<script src="{{ asset('assets/theme/my-theme/js/components/charts.js') }}"></script>
{% endblock %}JavaScript Structure
// public/assets/theme/my-theme/js/main.js
(function() {
'use strict';
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
console.log('Theme JavaScript loaded');
initTheme();
initComponents();
initEventListeners();
});
function initTheme() {
// Theme initialization logic
loadUserPreferences();
applyThemeSettings();
}
function initComponents() {
// Initialize custom components
initTooltips();
initPopovers();
initCharts();
}
function initEventListeners() {
// Set up event listeners
setupNavigationHandlers();
setupFormValidation();
setupAjaxHandlers();
}
// Export functions to global scope if needed
window.MyTheme = {
refresh: initTheme,
notify: showNotification
};
})();Common JavaScript Patterns
AJAX Requests
Event Delegation
Form Validation
Notifications
Working with Bootstrap JavaScript
PteroCA includes Bootstrap. Use Bootstrap components:
Useful Patterns
Debouncing
Prevent excessive function calls:
Throttling
Limit function execution rate:
Local Storage
Persist user preferences:
Confirmation Dialogs
Working with Forms
Dynamic Form Fields
AJAX Form Submission
Performance Optimization
Lazy Loading Images
Minimize DOM Manipulation
Best Practices
Use strict mode -
'use strict';Avoid global variables - use IIFEs or modules
Handle errors gracefully - use try/catch and .catch()
Optimize performance - debounce/throttle event handlers
Make accessible - support keyboard navigation
Test across browsers - ensure compatibility
Minify for production - reduce file size
Debugging
Console methods:
Breakpoints:
Browser DevTools:
Use Console tab for output
Use Sources tab for debugging
Use Network tab for AJAX requests
Use Performance tab for profiling
Related Guides
Styling - CSS customization
Twig Guide - Templating
Testing - Quality assurance
Theme Structure - File organization
External Resources
You Don't Know JS - In-depth JavaScript
Last updated