Category: Documentation

  • The Ultimate Guide to Centering a Div

    Centering a <div> is one of the most common tasks in web development, yet it often confuses beginners due to the variety of available techniques. Depending on layout requirements, browser support, and project complexity, different approaches can be used to center elements both horizontally and vertically.

    In this guide, we’ll explore the most effective and widely used methods to center a <div> in CSS.


    1. Using CSS Flexbox (Modern Recommended Approach)

    Flexbox is the most popular and easiest method for centering elements in modern web development.

    Example:

    <div class="parent">
      <div class="child">Centered Div</div>
    </div>
    
    .parent {
      display: flex;
      justify-content: center;  /* Horizontal */
      align-items: center;      /* Vertical */
      height: 100vh;
    }
    
    .child {
      width: 200px;
      height: 100px;
      background-color: lightblue;
    }
    

    Why use Flexbox?

    • Simple and clean syntax
    • Works for both directions
    • Responsive-friendly

    2. Using CSS Grid

    CSS Grid is another modern layout system that makes centering extremely easy.

    Example:

    <div class="parent">
      <div class="child">Centered Div</div>
    </div>
    
    .parent {
      display: grid;
      place-items: center;
      height: 100vh;
    }
    

    Why use Grid?

    • Minimal code
    • Powerful layout system
    • Ideal for full-page centering

    3. Using Text Alignment (Horizontal Only)

    This method works only for horizontal centering.

    Example:

    <div class="parent">
      <div class="child">Centered Div</div>
    </div>
    
    .parent {
      text-align: center;
    }
    
    .child {
      display: inline-block;
    }
    

    Limitation:

    • Does not center vertically

    4. Using Position + Transform

    A classic and widely used technique for perfect centering.

    Example:

    <div class="parent">
      <div class="child">Centered Div</div>
    </div>
    
    .parent {
      position: relative;
      height: 100vh;
    }
    
    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    

    Why it works:

    • Moves element to center point
    • Adjusts offset using transform

    5. Using Table Display Method (Legacy Approach)

    This method is mostly used for older projects.

    Example:

    .parent {
      display: table;
      width: 100%;
      height: 100vh;
    }
    
    .child {
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    

    Note:

    • Useful for legacy browser support
    • Not recommended for modern apps

    6. Using Inline Styles (Quick Prototyping)

    Good for quick testing but not production use.

    Example:

    <div style="display:flex;justify-content:center;align-items:center;height:100vh;">
      <div style="width:200px;height:100px;">Centered Div</div>
    </div>
    

    7. Using Margin Auto (Horizontal Centering Only)

    Works when width is defined and only horizontal centering is needed.

    Example:

    .child {
      width: 200px;
      margin: 0 auto;
    }
    

    📊 Comparison of Methods

    MethodHorizontalVerticalModern Use
    Flexbox⭐⭐⭐⭐⭐
    Grid⭐⭐⭐⭐⭐
    Position/Transform⭐⭐⭐⭐
    Text Align⭐⭐
    Table Cell
    Margin Auto⭐⭐⭐

    🚀 Conclusion

    There are multiple ways to center a <div>, but the best modern solutions are:

    • Flexbox → Most flexible and widely used
    • CSS Grid → Clean and powerful for layouts

    Older methods like table display and inline styles still exist but are less preferred in modern development.

    Understanding all techniques helps you handle both modern projects and legacy code efficiently.


    💡 Tip: In real-world projects, Flexbox or Grid should be your default choice for centering elements.

    Happy coding! 🎯

  • Customize the Placeholder Color of an HTML Input Using CSS

    When designing modern user interfaces, small visual details play a major role in creating a clean and professional user experience. One such detail is the styling of placeholder text inside input fields. By default, browsers render placeholder text in a light gray tone, but CSS allows you to fully customize it to match your design system.


    🧩 What Is Placeholder Text?

    Placeholder text is the faint text displayed inside input fields before the user enters any value. It provides hints or examples to guide users.

    Example:

    • “Enter your name”
    • “Enter your email address”
    • “Search here…”

    It disappears once the user starts typing.


    🎯 Why Customize Placeholder Color?

    Customizing placeholder styles improves both design and usability.

    Benefits:

    • Enhances UI consistency with brand colors
    • Improves readability in different themes (light/dark mode)
    • Creates a more polished and modern interface
    • Improves user guidance and experience

    🎨 CSS Pseudo-Element for Placeholder Styling

    To style placeholder text, we use the ::placeholder pseudo-element.

    Basic Example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Placeholder Styling</title>
    
      <style>
        input::placeholder {
          color: #888888;
          font-style: italic;
        }
    
        input {
          border: 1px solid #ccc;
          padding: 8px;
          border-radius: 4px;
          width: 100%;
          max-width: 300px;
        }
      </style>
    </head>
    <body>
    
      <input type="text" placeholder="Enter your name">
      <input type="email" placeholder="Enter your email">
    
    </body>
    </html>
    

    🌐 Browser Compatibility

    Most modern browsers support ::placeholder, but older browsers require vendor prefixes.

    Cross-Browser Support:

    input::-webkit-input-placeholder {
      color: #888888;
    }
    
    input:-moz-placeholder {
      color: #888888;
    }
    
    input::-moz-placeholder {
      color: #888888;
    }
    
    input:-ms-input-placeholder {
      color: #888888;
    }
    

    💡 Best Practices

    🎯 Ensure Good Contrast

    Make sure placeholder text is readable against the input background.

    🎯 Don’t Replace Labels

    Placeholders should guide users, not replace proper form labels.

    🎯 Keep It Consistent

    Use consistent placeholder styling across all input fields in your application.

    🎯 Keep It Subtle

    Avoid overly bold or distracting placeholder designs.


    🚀 Real-World Use Cases

    • Login & signup forms
    • Search bars
    • Contact forms
    • E-commerce checkout forms
    • Dashboard filters

    📌 Conclusion

    Customizing placeholder text color using CSS is a simple yet powerful way to enhance your form design. With just a few lines of code, you can align your inputs with your brand identity and improve overall user experience.

    A well-designed placeholder may be small, but it contributes significantly to a polished and professional UI.


    Experiment with different colors and styles to create forms that feel intuitive, modern, and user-friendly.

  • Steps to Create Your Own NPM Module

    Creating your own NPM (Node Package Manager) module is one of the best ways to contribute to the JavaScript ecosystem, improve your development skills, and build reusable tools for real-world applications. NPM is the largest package registry in the world, and publishing your own module allows other developers to easily install and use your code in their projects.

    In this guide, we’ll walk through a practical step-by-step process to create, test, and link your own NPM module.


    🚀 Why Create an NPM Module?

    Before diving into the steps, here’s why it matters:

    • Reuse your code across multiple projects
    • Share your utilities with other developers
    • Improve modular programming skills
    • Gain open-source visibility
    • Learn package management deeply

    🧱 Step 1: Create Project Structure

    Create two separate folders:

    • Library folder → Your NPM module (core logic)
    • Demo folder → To test and use the module

    Example:

    /my-library
    /demo-app
    

    ⚙️ Step 2: Initialize NPM in Both Folders

    Run the following command in both folders:

    npm init -y
    

    This creates a package.json file for both projects.


    📦 Step 3: Setup Library Project

    Inside the library folder, install Parcel:

    npm install parcel
    

    Create the source file:

    src/index.ts
    

    Add your reusable code inside index.ts.

    Example:

    export function greet(name: string) {
        return `Hello, ${name}!`;
    }
    

    🔧 Step 4: Configure Library Build

    Update your package.json:

    • Set entry point
    • Configure build scripts using Parcel

    Example:

    "source": "src/index.ts",
    "main": "dist/index.js"
    

    🖥️ Step 5: Setup Demo Project

    Inside the demo folder, install Parcel:

    npm install parcel
    

    Create the following structure:

    src/
      index.html
      style.css
      app.js
    

    🔗 Step 6: Link Library to Demo

    Run this command inside the demo folder:

    npm link ../library
    

    This connects your local module to the demo project.


    📥 Step 7: Import Your Module

    In app.js, import your library:

    import { greet } from "your-library-name";
    
    console.log(greet("Skriptx"));
    

    ▶️ Step 8: Run the Projects

    Run both projects simultaneously:

    In library folder:

    npm run watch
    

    In demo folder:

    npm start
    

    🔄 Troubleshooting Tip

    If changes are not reflected:

    • Remove import line
    • Re-type the import
    • Restart the dev server

    📌 Final Workflow Summary

    1. Create library & demo folders
    2. Initialize NPM in both
    3. Build library using Parcel
    4. Create demo UI
    5. Link library using npm link
    6. Import module in demo
    7. Run both projects simultaneously

    🎯 Conclusion

    Creating your own NPM module is a powerful step toward becoming a professional JavaScript developer. It helps you understand modular architecture, build reusable components, and contribute to the developer ecosystem.

    Start small, build utilities, and gradually scale your modules into production-ready packages that others can use.


    🚀 Now go ahead and publish your first NPM module to the world!

  • How to Sort an Array of Integers in JavaScript

    Sorting is one of the most common operations in programming. In this article, we’ll learn how to sort an array of integers in ascending order using JavaScript.

    We will also explore a simple custom sorting logic using loops and array manipulation.


    🧠 Problem Statement

    Given a number (or array of numbers), we want to sort all digits in ascending order.

    For example:

    • Input: 123496758789456
    • Output: 123445567778899

    💡 Approach

    We will:

    1. Convert the number into a string
    2. Split it into individual digits
    3. Compare and rearrange digits using loops
    4. Return the sorted result

    This approach demonstrates basic sorting logic without using built-in sort().


    💻 JavaScript Program

    const nos = 123496758789456;
    
    console.log("Original:", nos);
    
    const sorted = sorter(nos).join('');
    console.log("Sorted:", sorted);
    
    function sorter(nos) {
        const splitted = nos.toString().split('');
    
        for (let i = 0; i < splitted.length; i++) {
            for (let j = i + 1; j < splitted.length; j++) {
    
                if (parseInt(splitted[j - 1]) > parseInt(splitted[j])) {
                    let temp = splitted[j - 1];
    
                    splitted.splice(j - 1, 1);
                    splitted.splice(j, 0, temp);
                }
            }
        }
    
        return splitted;
    }
    

    🔍 How It Works

    Step 1: Convert Number to String

    nos.toString().split('')
    

    This converts the number into an array of digits.


    Step 2: Compare Adjacent Elements

    We use nested loops to compare each digit with the next ones.


    Step 3: Swap Elements

    If the previous digit is greater than the next one, we swap them using splice().


    📊 Output Example

    Input:

    123496758789456
    

    Output:

    123445567778899
    

    ⚡ Better Approach (Recommended)

    Instead of manual sorting, JavaScript provides a built-in method:

    const nos = 123496758789456;
    
    const sorted = nos
        .toString()
        .split('')
        .sort((a, b) => a - b)
        .join('');
    
    console.log(sorted);
    

    🚀 Key Takeaways

    • Sorting can be done using loops or built-in methods
    • Manual sorting helps understand algorithm logic
    • .sort() is the most efficient and readable approach in JavaScript
    • Always prefer built-in functions in real-world applications

    🎯 Conclusion

    Sorting digits is a great exercise to understand array manipulation and comparison logic in JavaScript. While manual sorting builds algorithmic thinking, built-in methods like .sort() make code cleaner and more efficient.

    Keep practicing to strengthen your JavaScript fundamentals!

  • Convert a Number into Binary and Check if It’s a Palindrome

    Have you ever wondered whether the binary representation of a number reads the same forwards and backwards? If yes, you are exploring the concept of a binary palindrome. In this post, we’ll understand how to convert a number into binary and check whether that binary representation is a palindrome using a simple Python program.


    🔢 What is Binary?

    Binary is a number system that uses only 0s and 1s. It is the fundamental language of computers, where every piece of data is ultimately represented in binary form.

    Examples:

    • Decimal 5 → Binary 101
    • Decimal 9 → Binary 1001
    • Decimal 12 → Binary 1100

    🔁 What is a Palindrome?

    A palindrome is a sequence that reads the same forward and backward.

    Examples:

    • "121" → Palindrome ✅
    • "101" → Palindrome ✅
    • "110" → Not a palindrome ❌
    • "1001" → Palindrome ✅

    So, a binary palindrome means the binary form of a number looks the same in both directions.


    💡 Problem Statement

    We need to:

    1. Take a number as input
    2. Convert it into binary
    3. Check whether the binary string is a palindrome

    🧠 Approach

    To solve this problem, we follow these steps:

    Step 1: Convert Number to Binary

    In Python, we can use the built-in bin() function:

    bin(number)
    

    This returns a string like "0b101" — so we remove the "0b" prefix.


    Step 2: Check Palindrome

    A string is a palindrome if:

    string == string[::-1]
    

    💻 Python Program

    def is_binary_palindrome(n):
        # Convert number to binary and remove '0b' prefix
        binary = bin(n)[2:]
        
        # Check if binary string is palindrome
        return binary == binary[::-1]
    
    # Example usage
    num = int(input("Enter a number: "))
    
    binary_form = bin(num)[2:]
    print("Binary Representation:", binary_form)
    
    if is_binary_palindrome(num):
        print("The binary number is a palindrome ✔")
    else:
        print("The binary number is NOT a palindrome ❌")
    

    🧪 Sample Output

    Input:

    Enter a number: 9
    

    Output:

    Binary Representation: 1001
    The binary number is a palindrome ✔
    

    🚀 Key Takeaways

    • Binary is the base-2 number system used in computing
    • A palindrome reads the same forwards and backwards
    • We can easily check binary palindromes using Python string slicing
    • This is a great beginner problem for learning both number systems and string manipulation

    🎯 Conclusion

    Understanding binary palindromes helps strengthen your knowledge of number systems and programming logic. With just a few lines of Python code, you can convert numbers and analyze their binary patterns efficiently.

    Keep practicing and explore more such logical problems to improve your coding skills!

  • 5 Compelling Reasons to Use @skriptx2/jspaginator

    Pagination plays a crucial role in delivering a better user experience when displaying large datasets. Whether you’re building tables, card layouts, product listings, or dynamic dashboards, an efficient pagination solution helps keep your application organized and performant.

    @skriptx2/jspaginator is a lightweight and flexible open-source package designed to simplify pagination across a wide variety of use cases. Unlike many pagination libraries that are tightly coupled with tables, jspaginator provides a framework-agnostic approach that works seamlessly with any type of data representation.

    In this article, we’ll explore five compelling reasons why developers should consider using @skriptx2/jspaginator in their projects.


    1. Open Source and Community Driven

    One of the biggest advantages of @skriptx2/jspaginator is that it is completely open source.

    Being open source provides several benefits:

    • Transparency in implementation.
    • Freedom to customize the library according to project requirements.
    • Continuous improvements and updates.
    • Community contributions and feedback.
    • Long-term maintainability.

    Developers can inspect the source code, extend functionality, and integrate it into their applications without vendor lock-in.

    GitHub Repository

    https://github.com/skriptxadmin/jspaginator
    

    2. Lightweight and Performance Focused

    Modern applications demand speed and efficiency. Heavy dependencies and bloated libraries can negatively affect performance and increase loading times.

    @skriptx2/jspaginator is designed with simplicity and performance in mind.

    Benefits

    • Minimal overhead.
    • Faster execution.
    • Lightweight package size.
    • Improved application responsiveness.
    • Suitable for both small and large projects.

    Because it avoids unnecessary complexity, developers can implement pagination without sacrificing performance.


    3. Not Limited to Tables

    Many pagination libraries are designed exclusively for HTML tables. However, modern applications often display information in multiple formats.

    @skriptx2/jspaginator is flexible enough to work with:

    • Tables
    • Lists
    • Cards
    • Product Catalogs
    • Dashboards
    • Grids
    • Galleries
    • Custom Components

    This versatility makes it an excellent choice for applications with dynamic user interfaces.

    Example Use Cases

    • E-commerce websites
    • Blog listings
    • User management systems
    • Product grids
    • Analytics dashboards
    • Portfolio galleries

    4. Easy Configuration

    Developers appreciate tools that are simple to understand and quick to implement.

    @skriptx2/jspaginator provides developer-friendly APIs that make pagination configuration straightforward.

    Customization Options

    • Items per page
    • Previous and next navigation
    • Page numbering
    • Custom styles
    • Dynamic page updates
    • User-defined controls

    Its intuitive design enables beginners and experienced developers alike to integrate pagination within minutes.


    5. Seamless Integration with Any Framework

    One of the standout features of @skriptx2/jspaginator is its framework independence.

    It integrates smoothly with modern JavaScript ecosystems including:

    • React
    • Angular
    • Vue
    • Next.js
    • Nuxt
    • Vanilla JavaScript
    • TypeScript Applications

    This flexibility allows developers to adopt the library without restructuring their existing projects.

    Framework Benefits

    • No vendor lock-in.
    • Easy adoption.
    • Reusable logic.
    • Consistent pagination behavior.
    • Reduced development time.

    Installation

    Install the package using npm:

    npm install @skriptx2/jspaginator
    

    Why Choose @skriptx2/jspaginator?

    ✔ Open Source

    Transparent and customizable.

    ✔ Lightweight

    Optimized for speed and performance.

    ✔ Flexible

    Works with tables, cards, grids, lists, and custom layouts.

    ✔ Easy to Configure

    Simple APIs with intuitive options.

    ✔ Framework Agnostic

    Compatible with React, Angular, Vue, Next.js, and plain JavaScript.


    GitHub Repository

    https://github.com/skriptxadmin/jspaginator
    

    NPM Package

    https://www.npmjs.com/package/@skriptx2/jspaginator
    

    Conclusion

    Choosing the right pagination solution can significantly improve both user experience and application performance. With its lightweight architecture, framework independence, flexible design, and easy configuration, @skriptx2/jspaginator offers a practical solution for modern web applications.

    Whether you’re building a simple website or a large-scale enterprise application, @skriptx2/jspaginator provides the flexibility and simplicity needed to implement efficient pagination without unnecessary complexity.

    Give @skriptx2/jspaginator a try and simplify pagination in your next project.

  • Detecting Screen Size on the Fly with jsMediaQuery in JavaScript

    Responsive web design has become an essential part of modern application development. Websites and applications are expected to provide a seamless experience across desktops, tablets, and mobile devices. While CSS media queries are the foundation of responsive design, there are situations where JavaScript needs to detect screen sizes dynamically and respond accordingly.

    This is where jsMediaQuery comes into play. It provides a simple and reusable way to detect breakpoints directly within JavaScript, allowing developers to build more dynamic and adaptive applications.


    Why Use jsMediaQuery?

    CSS media queries are excellent for controlling layouts, but some scenarios require JavaScript-based screen detection.

    Dynamic Content Rendering

    Applications may need to load or modify content based on the viewport size without requiring a page refresh.

    Examples include:

    • Displaying different components on mobile and desktop.
    • Switching navigation styles dynamically.
    • Loading optimized images and assets.

    Triggering Responsive Animations

    Certain animations or interactions depend on screen dimensions and cannot be controlled purely with CSS.

    Examples:

    • Different animation timings for mobile devices.
    • Sidebar transitions for desktop screens.
    • Conditional UI effects based on viewport width.

    Optimized Resource Loading

    By detecting screen sizes with JavaScript, applications can load lighter resources for smaller devices, improving performance and reducing bandwidth consumption.

    Examples:

    • Loading smaller images for mobile users.
    • Fetching fewer records for compact layouts.
    • Disabling unnecessary features on smaller screens.

    Interactive Components

    Many UI components require JavaScript intervention and need awareness of the current breakpoint.

    Examples:

    • Responsive sliders.
    • Conditional modals.
    • Dynamic menus.
    • Dashboard widgets.

    Getting Started

    Install the package using npm:

    npm install @skriptx2/jsmediaquery
    

    Importing the Library

    import { MediaQuery } from "@skriptx2/jsmediaquery";
    

    Detecting Breakpoints

    Small Devices

    Returns true when the viewport width is between 577px and 767px.

    MediaQuery.sm();
    

    Example:

    if (MediaQuery.sm()) {
        console.log("Small device detected");
    }
    

    Getting the Current Breakpoint

    The get() method returns the active breakpoint.

    MediaQuery.get();
    

    Example:

    console.log(MediaQuery.get());
    

    Output:

    {
        breakpoint: "md",
        width: 820
    }
    

    Practical Example

    import { MediaQuery } from "@skriptx2/jsmediaquery";
    
    if (MediaQuery.sm()) {
        document.body.classList.add("mobile-layout");
    }
    

    This enables developers to apply custom behavior depending on the detected screen size.


    Common Use Cases

    Responsive Navigation

    if (MediaQuery.sm()) {
        showHamburgerMenu();
    } else {
        showDesktopNavigation();
    }
    

    Loading Optimized Images

    if (MediaQuery.sm()) {
        image.src = "/images/mobile-banner.webp";
    } else {
        image.src = "/images/desktop-banner.webp";
    }
    

    Conditional Components

    if (MediaQuery.sm()) {
        renderMobileCards();
    } else {
        renderDesktopTable();
    }
    

    Benefits of jsMediaQuery

    • Lightweight and easy to use.
    • Reduces repetitive media query logic.
    • Provides cleaner and more maintainable code.
    • Enhances dynamic responsiveness.
    • Improves performance by enabling optimized resource loading.
    • Ideal for modern JavaScript frameworks and applications.

    Conclusion

    Responsive design goes beyond CSS. Modern applications often require dynamic behavior based on screen size, and jsMediaQuery provides a clean and efficient way to achieve that. Whether you’re building dashboards, e-commerce platforms, or interactive web applications, jsMediaQuery helps you detect breakpoints on the fly and create experiences that adapt seamlessly across all devices.

    Start integrating jsMediaQuery into your projects and simplify responsive JavaScript development.