1. Getting Started
  2. Introduction

Getting Started

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.

Getting Started

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.

Why Choose YakaJS?

The Evolution of JavaScript Libraries

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.

Familiar Syntax, Modern Capabilities

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()});

Comprehensive Feature Comparison

Understanding how YakaJS compares to other popular libraries helps you make informed decisions:

FeaturejQuery 3.xYakaJS 1.1Notes
Core Features
DOM ManipulationBoth provide comprehensive DOM APIs
Event HandlingYakaJS adds improved delegation
CSS ManipulationIdentical syntax and capabilities
AJAXYakaJS adds retry, timeout, progress
Animations
Basic Animationsfade, slide, show, hide
Advanced Effectsbounce, shake, pulse, flip3D, etc.
Animation ChainingFluent chaining support
Modern Features
State ManagementVuex-style store with mutations
ReactivitySignals and computed values
SPA RoutingFull-featured router with guards
Voice CommandsUnique to YakaJS
Virtual ScrollHandle 10,000+ items smoothly
Command PaletteVS Code-style interface
Security
XSS ProtectionManual✓ Built-inAutomatic HTML sanitization
CSRF TokensManual✓ Built-inAutomatic token inclusion
Input SanitizationMultiple sanitization methods
Developer Experience
TypeScript SupportCommunity✓ OfficialFull type definitions included
DocumentationGoodExcellent12+ comprehensive guides
Bundle Size87 KB151 KB+74% for 3x features
Browser SupportIE11+ModernFocused on modern browsers

Key Advantages

Production-Ready Architecture

  • 150+ features rigorously tested across multiple browsers
  • Comprehensive error handling with optional safe mode
  • Battle-tested in production applications
  • Regular updates and active maintenance

Superior Developer Experience

  • Complete TypeScript definitions with IntelliSense support
  • Extensive documentation with 500+ code examples
  • 12 interactive demos showcasing real-world usage
  • Familiar API reduces learning curve

Performance Optimization

  • Batched DOM updates prevent layout thrashing
  • Efficient event delegation for dynamic content
  • Smart caching mechanisms
  • Optimized selector engine

Built-in Security

  • Automatic XSS protection for HTML content
  • CSRF token management for POST requests
  • URL and input sanitization utilities
  • Content Security Policy support

Installation Methods

YakaJS offers multiple installation methods to suit different project setups and workflows.

Method 1: CDN (Fastest Setup)

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:

  • Zero configuration required
  • No build tools needed
  • Perfect for learning and experimentation
  • Cached by CDN for fast loading

Use Cases:

  • Static HTML websites
  • Quick prototypes and demos
  • Learning and experimentation
  • Projects without build pipelines

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 yakajs

After 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:

  • Integrates with modern build tools
  • Enables code splitting and tree-shaking
  • TypeScript support out of the box
  • Version management via package.json

Use Cases:

  • Single-page applications
  • React, Vue, or Angular projects
  • TypeScript applications
  • Production applications with build pipelines

Method 3: Build from Source

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 build

This generates three optimized versions:

  1. min.yaka.js (155 KB) - Standard minification with readable code
  2. ultra.min.yaka.js (155 KB) - Aggressive compression
  3. hyper.min.yaka.js (151 KB) - Maximum compression for production

Advantages:

  • Access to source code
  • Custom build configurations
  • Development and contribution

Use Cases:

  • Contributing to YakaJS
  • Creating custom builds
  • Learning from source code
  • Debugging deep issues

Quick Start Tutorial

Let's build a complete, functional application to demonstrate YakaJS capabilities. This tutorial covers DOM manipulation, events, AJAX, and animations.

Step 1: Create Your HTML File

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>

Step 2: Initialize YakaJS

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();});

Understanding the Code

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.

Step 3: Test Your Application

  1. Open index.html in a web browser
  2. Add some tasks using the input field
  3. Click tasks to mark them complete
  4. Delete tasks using the delete button
  5. Watch the statistics update automatically

This example demonstrates core YakaJS features: DOM manipulation, event handling, animations, and notifications.

Core Concepts Explained

1. Element Selection

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 context

Performance Tips:

  • ID selectors are fastest: _('#id')
  • Class selectors are highly optimized: _('.class')
  • Avoid overly complex selectors
  • Use context when searching within specific containers

2. Method Chaining

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:

  • More readable code
  • Fewer variable declarations
  • Compact, expressive syntax
  • Reduced repetition

3. Safe Mode

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 missing

When to Use Safe Mode:

  • Working with dynamically loaded content
  • Optional UI elements
  • During development/debugging
  • Cross-browser compatibility scenarios

4. Event Handling

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();

Practical Examples

Example 1: Form Validation

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...)

Copyright © 2026 Yaka UI Labs·Trademark Policy