Getting Started
Learn how to install and use YakaJS. A comprehensive guide covering installation methods, core concepts, and practical examples to get you building modern web applications.
YakaJS is a next-generation JavaScript library that bridges the gap between jQuery's simplicity and modern framework capabilities. It provides a familiar, jQuery-like API while incorporating cutting-edge features such as reactive state management, voice commands, built-in routing, and comprehensive security measures.
Modern web development demands more than basic DOM manipulation. Applications need state management, routing, reactivity, and security—features traditionally requiring multiple libraries. YakaJS consolidates these capabilities into a single, cohesive library that's both powerful and approachable.
If you've worked with jQuery, YakaJS will feel immediately familiar. The core API maintains jQuery's elegant chainable syntax while extending it with modern features:
// Classic jQuery-style DOM manipulation_('#element') .addClass('active') .fadeIn(300) .css('color', 'blue');// Modern reactive state managementconst count = _.signal(0);const doubled = _.computed(() => count() * 2);_.effect(() => { _('#counter').text(`Count: ${count()}, Doubled: ${doubled()}`);});count.set(5); // Automatically updates the DOM// Built-in SPA routingconst router = _.createRouter();router.addRoute('/user/:id', { component: (params) => `<h1>User ${params.id}</h1>`, beforeEnter: async () => await checkAuth()});// Voice command integration_.voice.listen({ 'show menu': () => _('#menu').slideDown(), 'hide menu': () => _('#menu').slideUp()});Understanding how YakaJS compares to other popular libraries helps you make informed decisions:
| Feature | jQuery 3.x | YakaJS 1.1 | Notes |
|---|---|---|---|
| Core Features | |||
| DOM Manipulation | ✓ | ✓ | Both provide comprehensive DOM APIs |
| Event Handling | ✓ | ✓ | YakaJS adds improved delegation |
| CSS Manipulation | ✓ | ✓ | Identical syntax and capabilities |
| AJAX | ✓ | ✓ | YakaJS adds retry, timeout, progress |
| Animations | |||
| Basic Animations | ✓ | ✓ | fade, slide, show, hide |
| Advanced Effects | ✗ | ✓ | bounce, shake, pulse, flip3D, etc. |
| Animation Chaining | ✓ | ✓ | Fluent chaining support |
| Modern Features | |||
| State Management | ✗ | ✓ | Vuex-style store with mutations |
| Reactivity | ✗ | ✓ | Signals and computed values |
| SPA Routing | ✗ | ✓ | Full-featured router with guards |
| Voice Commands | ✗ | ✓ | Unique to YakaJS |
| Virtual Scroll | ✗ | ✓ | Handle 10,000+ items smoothly |
| Command Palette | ✗ | ✓ | VS Code-style interface |
| Security | |||
| XSS Protection | Manual | ✓ Built-in | Automatic HTML sanitization |
| CSRF Tokens | Manual | ✓ Built-in | Automatic token inclusion |
| Input Sanitization | ✗ | ✓ | Multiple sanitization methods |
| Developer Experience | |||
| TypeScript Support | Community | ✓ Official | Full type definitions included |
| Documentation | Good | Excellent | 12+ comprehensive guides |
| Bundle Size | 87 KB | 151 KB | +74% for 3x features |
| Browser Support | IE11+ | Modern | Focused on modern browsers |
Production-Ready Architecture
Superior Developer Experience
Performance Optimization
Built-in Security
YakaJS offers multiple installation methods to suit different project setups and workflows.
The CDN approach is ideal for quick prototypes, demos, or projects without build tools. Simply include the script tag in your HTML, and YakaJS is immediately available.
<!-- Add to your HTML file --><script src="https://cdn.jsdelivr.net/gh/Yaka-UI-Labs/YakaJS@latest/dist/min.yaka.js"></script><!-- YakaJS is now available globally as _ --><script> _('#element').fadeIn();</script>Advantages:
Use Cases:
For modern applications using build tools like Webpack, Vite, or Rollup, npm installation provides the best integration and enables tree-shaking.
# Install via npmnpm install yakajs# Or using yarnyarn add yakajs# Or using pnpmpnpm add yakajsAfter installation, import YakaJS in your JavaScript or TypeScript files:
// ES6 module importimport _ from 'yakajs';// Use YakaJS_('#app').fadeIn();// Import specific utilities if neededimport { signal, computed, effect } from 'yakajs';const count = signal(0);TypeScript Integration:
YakaJS includes complete TypeScript definitions. Your IDE will provide full autocomplete and type checking:
import Yaka from 'yakajs';// Full type safetyYaka('#button') .addClass('active') .on('click', (e: Event) => { console.log('Clicked!'); });// Type-safe utilitiesconst items: number[] = Yaka.chunk([1, 2, 3, 4, 5, 6], 2);const unique: string[] = Yaka.uniq(['a', 'b', 'a', 'c']);Advantages:
Use Cases:
For contributors or those needing custom builds, you can clone and build YakaJS locally:
# Clone the repositorygit clone https://github.com/Yaka-UI-Labs/YakaJS.gitcd YakaJS# Install dependenciesnpm install# Build all versionsnpm run buildThis generates three optimized versions:
Advantages:
Use Cases:
Let's build a complete, functional application to demonstrate YakaJS capabilities. This tutorial covers DOM manipulation, events, AJAX, and animations.
Create a new file called index.html:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>YakaJS Task Manager</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; } .container { background: white; border-radius: 12px; padding: 30px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); max-width: 500px; width: 100%; } h1 { color: #333; margin-bottom: 20px; font-size: 28px; } .input-group { display: flex; gap: 10px; margin-bottom: 20px; } input { flex: 1; padding: 12px; border: 2px solid #e1e8ed; border-radius: 8px; font-size: 16px; transition: border-color 0.3s; } input:focus { outline: none; border-color: #667eea; } button { padding: 12px 24px; background: #667eea; color: white; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; transition: background 0.3s; } button:hover { background: #5568d3; } .task-list { list-style: none; } .task-item { background: #f7fafc; padding: 15px; margin-bottom: 10px; border-radius: 8px; display: flex; justify-content: space-between; align-items: center; transition: transform 0.2s; } .task-item:hover { transform: translateX(5px); } .task-item.completed { opacity: 0.6; text-decoration: line-through; } .delete-btn { background: #e53e3e; padding: 8px 16px; font-size: 14px; } .delete-btn:hover { background: #c53030; } .stats { margin-top: 20px; padding-top: 20px; border-top: 2px solid #e1e8ed; color: #666; font-size: 14px; } </style></head><body> <div class="container"> <h1>Task Manager</h1> <div class="input-group"> <input type="text" id="taskInput" placeholder="Enter a new task..."> <button id="addBtn">Add Task</button> </div> <ul class="task-list" id="taskList"></ul> <div class="stats"> <strong>Total Tasks:</strong> <span id="totalTasks">0</span> | <strong>Completed:</strong> <span id="completedTasks">0</span> </div> </div> <!-- Include YakaJS --> <script src="https://cdn.jsdelivr.net/gh/Yaka-UI-Labs/YakaJS@latest/dist/min.yaka.js"></script> <script> // Application code will go here </script></body></html>Add the application logic inside the script tag:
// Wait for DOM to be ready_(function() { // Initialize state let tasks = []; // Add task function function addTask() { const taskText = _('#taskInput').val().trim(); if (taskText === '') { _.notify('Please enter a task', 'warning'); return; } // Create task object const task = { id: Date.now(), text: taskText, completed: false }; tasks.push(task); renderTasks(); // Clear input and focus _('#taskInput').val('').focus(); // Show success notification _.notify('Task added successfully!', 'success'); } // Render tasks function function renderTasks() { const $list = _('#taskList'); $list.empty(); tasks.forEach(task => { const $item = _('<li>') .addClass('task-item') .toggleClass('completed', task.completed) .attr('data-id', task.id) .html(` <span class="task-text">${task.text}</span> <button class="delete-btn">Delete</button> `) .hide(); $list.append($item); $item.fadeIn(300); }); updateStats(); } // Update statistics function updateStats() { const total = tasks.length; const completed = tasks.filter(t => t.completed).length; _('#totalTasks').text(total); _('#completedTasks').text(completed); } // Event: Add task on button click _('#addBtn').on('click', addTask); // Event: Add task on Enter key _('#taskInput').on('keypress', function(e) { if (e.key === 'Enter') { addTask(); } }); // Event: Toggle task completion (delegation) _('#taskList').on('click', '.task-text', function() { const id = Number(_(this).closest('.task-item').attr('data-id')); const task = tasks.find(t => t.id === id); if (task) { task.completed = !task.completed; _(this).closest('.task-item') .toggleClass('completed') .bounce(); updateStats(); } }); // Event: Delete task (delegation) _('#taskList').on('click', '.delete-btn', function() { const $item = _(this).closest('.task-item'); const id = Number($item.attr('data-id')); // Animate removal $item.slideUp(300, function() { tasks = tasks.filter(t => t.id !== id); $item.remove(); updateStats(); }); }); // Initial render renderTasks();});Let's break down what's happening:
DOM Ready Handler:
_(function() { // Code runs when DOM is ready});YakaJS provides a convenient way to wait for the DOM to be fully loaded. This ensures all elements are available before your code runs.
Selector and Manipulation:
const taskText = _('#taskInput').val().trim();_('#taskInput').val('').focus();The _() function selects elements using CSS selectors. Methods like .val(), .focus(), and .text() work identically to jQuery.
Method Chaining:
_('#taskInput').val('').focus();Most YakaJS methods return the YakaJS object, allowing you to chain multiple operations elegantly.
Event Delegation:
_('#taskList').on('click', '.task-text', function() { // Handles clicks on dynamically added elements});Event delegation attaches handlers to parent elements, automatically handling events from dynamically added children.
Animations:
$item.fadeIn(300);$item.slideUp(300, callback);YakaJS includes 15+ built-in animations that can be chained and customized.
index.html in a web browserThis example demonstrates core YakaJS features: DOM manipulation, event handling, animations, and notifications.
YakaJS uses CSS selectors to target DOM elements, providing maximum flexibility:
// Select by ID - fastest method_('#header')// Select by class - matches all elements with class_('.menu-item')// Select by tag name_('button')// Select by attribute_('[data-role="navigation"]')_('[type="email"]')// Complex selectors with combinators_('div.container > p.highlight') // Direct children_('ul li a') // Descendants_('h1 + p') // Adjacent sibling_('h1 ~ p') // General sibling// Pseudo-selectors_('li:first-child')_('input:checked')_('div:not(.excluded)')// Context-based selection (search within element)_('li', '#specificList') // Only <li> in #specificList_('.item', _('#container')) // Using YakaJS object as contextPerformance Tips:
_('#id')_('.class')YakaJS embraces method chaining, allowing you to perform multiple operations in a single, readable statement:
// Chain multiple operations_('#element') .addClass('active') .css('color', 'blue') .attr('data-state', 'ready') .fadeIn(300) .on('click', handleClick);// Conditional chaining_('#element') .addClass('base-class') [condition ? 'addClass' : 'removeClass']('conditional-class') .fadeIn();// Chaining with callbacks_('#box') .fadeOut(200, function() { _(this).text('Updated!').fadeIn(200); });Benefits:
One of YakaJS's most valuable features is safe mode, which prevents errors when elements don't exist:
// Without safe mode - throws error_('#nonexistent').hide(); // Error: Cannot read property...// With safe mode - fails gracefully_('#nonexistent').safe().hide(); // No error, silently ignored// Enable debug mode for development_.debug = true;_('#nonexistent').safe().hide(); // Logs: "Warning: No elements found"// Safe mode with chaining_('#maybe-exists') .safe() .addClass('active') .fadeIn() .css('color', 'red'); // All operations skip if element missingWhen to Use Safe Mode:
YakaJS provides powerful event handling with automatic delegation support:
// Basic event binding_('#button').on('click', function(event) { console.log('Clicked!');});// Multiple events with same handler_('#input').on('focus blur', function(event) { console.log('Event:', event.type);});// Event delegation for dynamic content_('#list').on('click', 'li', function(event) { // Handles clicks on current AND future <li> elements console.log('Clicked item:', this);});// Event namespacing_('#element').on('click.myNamespace', handler);_('#element').off('.myNamespace'); // Remove all events in namespace// One-time events_('#button').one('click', function() { console.log('Runs once only');});// Remove specific handlerfunction myHandler() { }_('#button').on('click', myHandler);_('#button').off('click', myHandler);// Remove all events_('#button').off();Complete form handling with real-time validation:
_(function() { const validationRules = { username: { required: true, minLength: 3, maxLength: 20, pattern: /^[a-zA-Z0-9_]+$/, requiredMessage: 'Username is required', minLengthMessage: 'Username must be at least 3 characters', patternMessage: 'Username can only contain letters, numbers, and underscores' }, email: { required: true, email: true, requiredMessage: 'Email is required', emailMessage: 'Please enter a valid email address' }, password: { required: true, minLength: 8, pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, requiredMessage: 'Password is required', minLengthMessage: 'Password must be at least 8 characters', patternMessage: 'Password must contain uppercase, lowercase, and number' } }; // Real-time validation on blur _('#registrationForm input').on('blur', function() { const field = _(this).attr('name'); validateField(field); }); function validateField(fieldName) { const rules = validationRules[fieldName]; if (!rules) return true; const $field = _(`[name="${fieldName}"]`); const $error = $field.next('.error-message'); const result = _('#registrationForm').validate({ [fieldName]: rules }); if (!result.valid && result.errors[fieldName]) { $field.addClass('error'); $error.text(result.errors[fieldName][0]).fadeIn(200); return false; } else { $field.removeClass('error').addClass('valid'); $error.fadeOut(200); return true; } } // Form submission _('#registrationForm').on('submit', async function(e) { e.preventDefault(); const result = _(this).validate(validationRules); if (result.valid) { const formData = _(this).serializeObject(); _('#submitBtn').prop('disabled', true).text('Submitting...'); try { await _.post('/api/register', formData); _.notify('Registration successful!', 'success'); window.location.href = '/dashboard'; } catch (error) { _.notify('Registration failed. Please try again.', 'error'); } finally { _('#submitBtn').prop('disabled', false).text('Submit'); } } });});(Continuing in next message due to length...)