How to create a EMI, BMI, and Age Calculator

Calculator widgets are compact, interactive tools integrated into HTML CSS and JAVA SCRIPT They are particularly useful for:

  • Financial planning (EMI calculators).
  • Health assessments (BMI calculators).
  • Personal milestones (Age calculators).

Step 1: HTML Structure

First, create the basic structure for the card slider. Below is a simple HTML template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator Widgets</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <header>
        <nav>
            <div class="logo">
                <i class="fas fa-calculator"></i>
                <span>Calculator Widgets</span>
            </div>
        </nav>
    </header>

    <main>
        <section class="hero">
            <h1>Useful Calculators for Your Daily Needs</h1>
            <p>Easy-to-use calculators for financial planning and health monitoring.</p>
        </section>

        <section class="calculators-grid">
            <!-- EMI Calculator -->
            <div class="calculator-card" id="emi-calculator">
                <h2>EMI Calculator</h2>
                <div class="calculator-form">
                    <div class="input-group">
                        <label for="loan-amount">Loan Amount (₹)</label>
                        <input type="number" id="loan-amount" placeholder="Enter loan amount">
                    </div>
                    <div class="input-group">
                        <label for="interest-rate">Interest Rate (%)</label>
                        <input type="number" id="interest-rate" placeholder="Enter interest rate">
                    </div>
                    <div class="input-group">
                        <label for="loan-tenure">Loan Tenure (Years)</label>
                        <input type="number" id="loan-tenure" placeholder="Enter loan tenure">
                    </div>
                    <button onclick="calculateEMI()">Calculate EMI</button>
                    <div id="emi-result" class="result"></div>
                </div>
            </div>

            <!-- BMI Calculator -->
            <div class="calculator-card" id="bmi-calculator">
                <h2>BMI Calculator</h2>
                <div class="calculator-form">
                    <div class="input-group">
                        <label for="weight">Weight (kg)</label>
                        <input type="number" id="weight" placeholder="Enter weight">
                    </div>
                    <div class="input-group">
                        <label for="height">Height (cm)</label>
                        <input type="number" id="height" placeholder="Enter height">
                    </div>
                    <button onclick="calculateBMI()">Calculate BMI</button>
                    <div id="bmi-result" class="result"></div>
                </div>
            </div>

            <!-- Age Calculator -->
            <div class="calculator-card" id="age-calculator">
                <h2>Age Calculator</h2>
                <div class="calculator-form">
                    <div class="input-group">
                        <label for="birth-date">Birth Date</label>
                        <input type="date" id="birth-date">
                    </div>
                    <button onclick="calculateAge()">Calculate Age</button>
                    <div id="age-result" class="result"></div>
                </div>
            </div>
        </section>
    </main>

    <footer>
        <div class="footer-content">
            <p>&copy; 2025 Calculator Widgets. All rights reserved.</p>
        </div>
    </footer>

    <script src="script.js"></script>
</body>
</html>

1. Input Data Options

Step 2: CSS for Styling the Slider

Add CSS to style the card slider and make it responsive. Below is an example of basic styling:

:root {
    --primary-color: #3498db;
    --secondary-color: #2c3e50;
    --background-color: #f5f5f5;
    --card-background: #ffffff;
    --text-color: #333333;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    background-color: var(--background-color);
}

/* Header Styles */
header {
    background-color: var(--secondary-color);
    color: white;
    padding: 1rem;
}

nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
    max-width: 1200px;
    margin: 0 auto;
}

.logo {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 1.5rem;
    color: var(--primary-color);
}

.nav-buttons {
    display: flex;
    gap: 1rem;
}

button {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.3s ease;
}

.login-btn {
    background-color: transparent;
    color: var(--primary-color);
}

.signup-btn {
    background-color: var(--primary-color);
    color: rgb(225, 250, 242);
}

/* Main Content Styles */
main {
    margin-top: 80px;
    padding: 2rem;
}

.hero {
    text-align: center;
    padding: 2rem;
    background-color: var(--primary-color);
    color: white;
}

.hero h1 {
    font-size: 2.5rem;
    margin-bottom: 1rem;
}

.calculators-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
    padding: 2rem;
    max-width: 1200px;
    margin: 0 auto;
}

.calculator-card {
    background-color: var(--card-background);
    border-radius: 10px;
    padding: 2rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.calculator-card h2 {
    color: var(--secondary-color);
    margin-bottom: 1.5rem;
    text-align: center;
}

.calculator-form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.input-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.input-group label {
    font-weight: 600;
    color: var(--secondary-color);
}

.input-group input {
    padding: 0.8rem;
    border: 1px solid #ddd;
    border-radius: 5px;
    font-size: 1rem;
}

button {
    background-color: var(--primary-color);
    color: white;
    padding: 0.8rem;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #2980b9;
}

.result {
    margin-top: 1rem;
    padding: 1rem;
    background-color: #f8f9fa;
    border-radius: 5px;
    text-align: center;
    font-weight: 600;
}

/* Footer Styles */
footer {
    background-color: var(--secondary-color);
    color: white;
    text-align: center;
    padding: 1rem;
    margin-top: 2rem;
}

/* Responsive Design */
@media (max-width: 768px) {
    .hero h1 {
        font-size: 2rem;
    }
    
    .calculators-grid {
        grid-template-columns: 1fr;
        padding: 1rem;
    }
}

Step 3: JavaScript for Sliding Functionality

Use JavaScript to add the functionality that allows the cards to slide when the buttons are clicked:

// PDF Processing Functions
const PDFTools = {
    async mergePDFs(pdfFiles) {
        const mergedPdf = await PDFLib.PDFDocument.create();
        
        for (const file of pdfFiles) {
            const pdfBytes = await file.arrayBuffer();
            const pdf = await PDFLib.PDFDocument.load(pdfBytes);
            const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
            copiedPages.forEach((page) => mergedPdf.addPage(page));
        }
        
        const mergedPdfFile = await mergedPdf.save();
        return new Blob([mergedPdfFile], { type: 'application/pdf' });
    },

    async splitPDF(pdfFile, pageRanges) {
        const pdfBytes = await pdfFile.arrayBuffer();
        const pdf = await PDFLib.PDFDocument.load(pdfBytes);
        const results = [];

        for (const range of pageRanges) {
            const newPdf = await PDFLib.PDFDocument.create();
            const pages = await newPdf.copyPages(pdf, range);
            pages.forEach(page => newPdf.addPage(page));
            const newPdfBytes = await newPdf.save();
            results.push(new Blob([newPdfBytes], { type: 'application/pdf' }));
        }

        return results;
    },

    async rotatePDF(pdfFile, degrees) {
        const pdfBytes = await pdfFile.arrayBuffer();
        const pdf = await PDFLib.PDFDocument.load(pdfBytes);
        
        for (let i = 0; i < pdf.getPageCount(); i++) {
            const page = pdf.getPage(i);
            page.setRotation(PDFLib.degrees(degrees));
        }
        
        const rotatedPdfBytes = await pdf.save();
        return new Blob([rotatedPdfBytes], { type: 'application/pdf' });
    },

    async compressPDF(pdfFile) {
        const pdfBytes = await pdfFile.arrayBuffer();
        const pdf = await PDFLib.PDFDocument.load(pdfBytes);
        
        // Basic compression by removing metadata
        pdf.setTitle('');
        pdf.setAuthor('');
        pdf.setSubject('');
        pdf.setKeywords([]);
        pdf.setProducer('');
        pdf.setCreator('');
        
        const compressedPdfBytes = await pdf.save({ useObjectStreams: true });
        return new Blob([compressedPdfBytes], { type: 'application/pdf' });
    }
};

// Tool Card Component Class
class ToolCard {
    constructor(title, description, iconClass, action) {
        this.title = title;
        this.description = description;
        this.iconClass = iconClass;
        this.action = action;
    }

    createCard() {
        const card = document.createElement('div');
        card.className = 'tool-card';
        
        card.innerHTML = `
            <div class="tool-icon">
                <i class="${this.iconClass}"></i>
            </div>
            <h3>${this.title}</h3>
            <p>${this.description}</p>
        `;
        
        card.addEventListener('click', () => this.handleToolClick());
        return card;
    }

    async handleToolClick() {
        const modal = document.getElementById('processingModal');
        const fileInput = document.getElementById('pdfInput');
        const processButton = document.getElementById('processButton');
        const statusDiv = document.getElementById('processingStatus');
        
        modal.style.display = 'block';
        
        processButton.onclick = async () => {
            const files = fileInput.files;
            if (files.length === 0) {
                statusDiv.textContent = 'Please select at least one PDF file.';
                return;
            }

            statusDiv.innerHTML = '<div class="loading"></div> Processing...';
            
            try {
                const result = await this.action(files);
                if (result) {
                    if (Array.isArray(result)) {
                        result.forEach((blob, index) => {
                            saveAs(blob, `output_${index + 1}.pdf`);
                        });
                    } else {
                        saveAs(result, 'output.pdf');
                    }
                    statusDiv.textContent = 'Processing complete! Files have been downloaded.';
                }
            } catch (error) {
                statusDiv.textContent = `Error: ${error.message}`;
            }
        };
    }
}

// Tools Data with Actions
const toolsData = [
    {
        title: 'Merge PDF',
        description: 'Combine multiple PDFs into a single file.',
        icon: 'fas fa-object-group',
        action: async (files) => await PDFTools.mergePDFs(Array.from(files))
    },
    {
        title: 'Split PDF',
        description: 'Split a PDF into multiple files.',
        icon: 'fas fa-cut',
        action: async (files) => {
            if (files.length !== 1) throw new Error('Please select exactly one PDF file.');
            return await PDFTools.splitPDF(files[0], [[0], [1]]);  // Split into individual pages
        }
    },
    {
        title: 'Rotate PDF',
        description: 'Rotate PDF pages by 90, 180, or 270 degrees.',
        icon: 'fas fa-redo',
        action: async (files) => {
            if (files.length !== 1) throw new Error('Please select exactly one PDF file.');
            return await PDFTools.rotatePDF(files[0], 90);
        }
    },
    {
        title: 'Compress PDF',
        description: 'Reduce PDF file size while maintaining quality.',
        icon: 'fas fa-compress',
        action: async (files) => {
            if (files.length !== 1) throw new Error('Please select exactly one PDF file.');
            return await PDFTools.compressPDF(files[0]);
        }
    }
];

// Initialize Application
document.addEventListener('DOMContentLoaded', () => {
    const toolsGrid = document.querySelector('.tools-grid');
    const modal = document.getElementById('processingModal');
    
    // Clear existing tools
    toolsGrid.innerHTML = '';
    
    // Create and append tool cards
    toolsData.forEach(tool => {
        const toolCard = new ToolCard(tool.title, tool.description, tool.icon, tool.action);
        toolsGrid.appendChild(toolCard.createCard());
    });

    // Modal close functionality
    document.querySelector('.cancel-btn').onclick = () => {
        modal.style.display = 'none';
        document.getElementById('processingStatus').textContent = '';
        document.getElementById('pdfInput').value = '';
    };

    // File drag and drop functionality
    const fileUploadArea = document.querySelector('.file-upload-area');
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, () => {
            fileUploadArea.classList.add('highlight');
        });
    });

    ['dragleave', 'drop'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, () => {
            fileUploadArea.classList.remove('highlight');
        });
    });

    fileUploadArea.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        const files = dt.files;
        document.getElementById('pdfInput').files = files;
        updateFileList(files);
    });

    document.getElementById('pdfInput').addEventListener('change', (e) => {
        updateFileList(e.target.files);
    });

    function updateFileList(files) {
        const fileList = document.getElementById('fileList');
        fileList.innerHTML = '';
        Array.from(files).forEach(file => {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <span>${file.name}</span>
                <span>${(file.size / 1024 / 1024).toFixed(2)} MB</span>
            `;
            fileList.appendChild(fileItem);
        });
    }
});

// Add smooth scrolling for better UX
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

// EMI Calculator
function calculateEMI() {
    const loanAmount = parseFloat(document.getElementById('loan-amount').value);
    const interestRate = parseFloat(document.getElementById('interest-rate').value);
    const loanTenure = parseFloat(document.getElementById('loan-tenure').value);

    if (isNaN(loanAmount) || isNaN(interestRate) || isNaN(loanTenure)) {
        document.getElementById('emi-result').innerHTML = 'Please enter valid numbers';
        return;
    }

    const monthlyInterestRate = (interestRate / 12) / 100;
    const numberOfPayments = loanTenure * 12;
    
    const emi = loanAmount * monthlyInterestRate * 
               (Math.pow(1 + monthlyInterestRate, numberOfPayments)) / 
               (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);

    document.getElementById('emi-result').innerHTML = 
        `Monthly EMI: ₹${emi.toFixed(2)}<br>
         Total Payment: ₹${(emi * numberOfPayments).toFixed(2)}<br>
         Total Interest: ₹${(emi * numberOfPayments - loanAmount).toFixed(2)}`;
}

// BMI Calculator
function calculateBMI() {
    const weight = parseFloat(document.getElementById('weight').value);
    const height = parseFloat(document.getElementById('height').value);

    if (isNaN(weight) || isNaN(height)) {
        document.getElementById('bmi-result').innerHTML = 'Please enter valid numbers';
        return;
    }

    const heightInMeters = height / 100;
    const bmi = weight / (heightInMeters * heightInMeters);
    let category = '';

    if (bmi < 18.5) category = 'Underweight';
    else if (bmi < 25) category = 'Normal weight';
    else if (bmi < 30) category = 'Overweight';
    else category = 'Obese';

    document.getElementById('bmi-result').innerHTML = 
        `Your BMI: ${bmi.toFixed(1)}<br>
         Category: ${category}`;
}

// Age Calculator
function calculateAge() {
    const birthDate = new Date(document.getElementById('birth-date').value);
    const today = new Date('2025-01-11'); // Using the provided current date

    if (isNaN(birthDate.getTime())) {
        document.getElementById('age-result').innerHTML = 'Please enter a valid date';
        return;
    }

    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }

    const years = age;
    let months = monthDiff;
    if (months < 0) months += 12;
    
    const days = today.getDate() - birthDate.getDate();

    document.getElementById('age-result').innerHTML = 
        `Age: ${years} years, ${months} months, ${days >= 0 ? days : 30 + days} days`;
}
How to create a  EMI, BMI, and Age Calculator
How to create a EMI, BMI, and Age Calculator

Additional Ideas for Calculators

  1. Tax Calculator: Calculate income tax based on user input.
  2. Savings Calculator: Help users plan their savings goals.
  3. Pregnancy Due Date Calculator: Useful for maternity-focused websites.
  4. Calorie Calculator: Allow users to calculate daily calorie intake needs.
  5. Distance Calculator: Measure distances between two locations.
  6. Currency Converter: Convert currencies in real-time.

EMI Calculator

  • Best EMI calculator tool
  • Loan EMI calculator for home loans
  • Online EMI calculator with interest rate
  • Free EMI calculation tool
  • EMI calculator for personal loans

BMI Calculator

  • Free BMI calculator for men and women
  • Body Mass Index calculator online
  • Calculate BMI using height and weight
  • BMI chart calculator
  • Health BMI calculator tool

Age Calculator

  • Free online age calculator by date of birth
  • Birthday age calculator tool
  • Accurate age difference calculator
  • Age calculator for next milestone
  • Calculate exact age instantly

1 Comment

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *