Friday, September 26, 2025

Contoh Drag & Drop Sederhana

 <!DOCTYPE html>

<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      position: relative;
      height: 100px;
      width: 100px;
      border: 2px solid #333;
      border-radius: 10px;
      background-size: cover;
      background-position: center;
      margin: 10px;
      display: inline-block;
    }

    .image {
      height: 100px;
      width: 100px;
      background: url("sam.jpeg") center/cover no-repeat;
      border: 2px solid red;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <div class="box"></div>
  <div class="image" draggable="true"></div>

  <script>
    const boxes = document.querySelectorAll(".box");
    const image = document.querySelector(".image");

    // supaya image bisa di-drag
    image.addEventListener("dragstart", (e) => {
      e.dataTransfer.setData("text/plain", "dragged-image");
    });

    boxes.forEach((box) => {
      box.addEventListener("dragover", (e) => {
        e.preventDefault();
      });

      box.addEventListener("drop", (e) => {
        e.preventDefault();
        box.appendChild(image);
      });
    });
  </script>
</body>
</html>

Friday, July 18, 2025

Geser Array Dengan PHP

<?php
$arr1 = [1, 2];
$arr2 = ['a', 'b'];
function geserArray($arr1, $arr2) {
    $result = [];
    $maxLength = max(count($arr1), count($arr2));
   
    for ($i = 0; $i < $maxLength; $i++) {
        if (isset($arr1[$i])) {
            $result[] = $arr1[$i];
        }
        if (isset($arr2[$i])) {
            $result[] = $arr2[$i];
        }
    }
   
    return $result;
}

$result = geserArray($arr1, $arr2);
print_r($result);
?>

Output // [1,'a', 2, 'b']

Monday, June 2, 2025

Heat Map Dengan Sigmoid

 <!DOCTYPE html>

<html>
<head>
    <title>Heat Map dengan Sigmoid</title>
    <style>
        #heatmap {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(30px, 1fr));
            gap: 2px;
            width: 400px;
            margin: 20px auto;
        }
        .cell {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <h2 align="center">Heat Map dengan Fungsi Sigmoid</h2>
    <div id="heatmap"></div>

    <script>
        function sigmoid(x) {
            return 1 / (1 + Math.exp(-x));
        }

        function normalizeWithSigmoid(value, maxValue) {
            // Scale nilai ke range -6 sampai 6 untuk sigmoid
            const scaledValue = (value / maxValue) * 12 - 6;
            return sigmoid(scaledValue);
        }

        const data = [
            [5, 10, 15, 20, 25],
            [30, 35, 40, 45, 50],
            [55, 60, 65, 70, 75],
            [80, 85, 90, 95, 100],
            [105, 110, 115, 120, 125]
        ];

        const maxValue = Math.max(...data.flat());
        const heatmap = document.getElementById('heatmap');
        heatmap.innerHTML = '';
        data.forEach(row => {
            row.forEach(value => {
                const normalized = normalizeWithSigmoid(value, maxValue);
                const hue = (1 - normalized) * 240; // 240 (biru) ke 0 (merah)
                const color = `hsl(${hue}, 100%, 50%)`;
               
                const cell = document.createElement('div');
                cell.className = 'cell';
                cell.style.backgroundColor = color;
                cell.textContent = value;               
                heatmap.appendChild(cell);
            });
        });
    </script>
</body>
</html>

Friday, May 23, 2025

text to speech atau kata kata ke suara dengan vanilla javascript

<html lang="en">


<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text To SPeech Javascript</title>
</head>

<body>
<h1>Text To Speech</h1>
<hr>
<p><textarea cols="60" rows="15" id="textdata"></textarea></p>
<p><button onclick="speakNow()">Speak Now</button></p>

<script>
function speakNow() {
let texts = document.getElementById("textdata").value;
let utterence = new SpeechSynthesisUtterance(texts);
utterence.lang = "id-ID";
speechSynthesis.speak(utterence);
}
</script>
</body>

</html>

Monday, March 17, 2025

multer rename file express.js

 const multer = require('multer');

const path = require('path');


// Konfigurasi penyimpanan multer

const storage = multer.diskStorage({

  destination: (req, file, cb) => {

    cb(null, 'uploads/'); // Folder tujuan penyimpanan file

  },

  filename: (req, file, cb) => {

    // Mengganti nama file

    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);

    const fileExtension = path.extname(file.originalname); // Ambil ekstensi file asli

    const newFileName = `image-${uniqueSuffix}${fileExtension}`; // Nama file baru

    cb(null, newFileName);

  }

});


// Fungsi untuk memfilter tipe file

const fileFilter = (req, file, cb) => {

  // Tipe MIME yang diizinkan untuk gambar

  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

  

  if (allowedTypes.includes(file.mimetype)) {

    // File diterima

    cb(null, true);

  } else {

    // File ditolak

    cb(new Error('Hanya file gambar (JPEG, PNG, GIF) yang diizinkan!'), false);

  }

};


// Inisialisasi multer dengan storage dan filter

const upload = multer({

  storage: storage,

  fileFilter: fileFilter,

  limits: { fileSize: 5 * 1024 * 1024 } // Opsional: batas ukuran file 5MB

});


// Endpoint untuk mengunggah file

app.post('/upload', upload.single('file'), (req, res) => {

  res.send('File gambar berhasil diunggah dengan nama baru!');

}, (err, req, res, next) => {

  // Penanganan error

  if (err instanceof multer.MulterError) {

    return res.status(400).send('Terjadi kesalahan saat mengunggah file: ' + err.message);

  } else if (err) {

    return res.status(400).send(err.message);

  }

  next();

});


// Jalankan server

app.listen(3000, () => {

  console.log('Server berjalan di port 3000');

});

Saturday, March 8, 2025

Multipage PDF vanilla.js

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>JSON to Multi-Page PDF with Table</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.8.2/jspdf.plugin.autotable.min.js"></script>

</head>

<body>

    <button onclick="generatePDF()">Generate PDF</button>


    <script>

        const { jsPDF } = window.jspdf;


        const jsonData = {

            employees: [

                { firstName: "John", lastName: "Doe", age: 30, role: "Developer" },

                { firstName: "Jane", lastName: "Smith", age: 25, role: "Designer" },

                { firstName: "Peter", lastName: "Jones", age: 35, role: "Manager" },

                { firstName: "Alice", lastName: "Brown", age: 28, role: "Analyst" },

                { firstName: "Bob", lastName: "Wilson", age: 40, role: "Engineer" },

                { firstName: "Carol", lastName: "Davis", age: 32, role: "Support" }

            ]

        };


        function generatePDF() {

            const doc = new jsPDF();


            // Define table columns

            const columns = [

                { header: "First Name", dataKey: "firstName" },

                { header: "Last Name", dataKey: "lastName" },

                { header: "Age", dataKey: "age" },

                { header: "Role", dataKey: "role" }

            ];


            // Add table with auto-pagination

            doc.autoTable({

                head: [columns.map(col => col.header)],

                body: jsonData.employees.map(employee => [

                    employee.firstName,

                    employee.lastName,

                    employee.age,

                    employee.role

                ]),

                startY: 20,

                theme: "grid",

                margin: { top: 10 }

            });


            // Save the PDF

            doc.save("employees_table.pdf");

        }

    </script>

</body>

</html>

Thursday, March 6, 2025

Generator Kata Sandi Kuat dengan Vanilla Javascript

 <!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Generator Kata Sandi Kuat</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            text-align: center;

            margin-top: 50px;

        }

        #passwordOutput {

            font-size: 20px;

            margin-top: 20px;

            padding: 10px;

            border: 1px solid #ccc;

            display: inline-block;

        }

        button {

            padding: 10px 20px;

            font-size: 16px;

            cursor: pointer;

        }

    </style>

</head>

<body>

    <h1>Generator Kata Sandi Kuat</h1>

    <button onclick="generatePassword()">Buat Kata Sandi</button>

    <div id="passwordOutput"></div>


    <script>

        function generatePassword() {

            // Karakter yang bisa digunakan dalam kata sandi

            const hurufKecil = 'abcdefghijklmnopqrstuvwxyz';

            const hurufBesar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

            const angka = '0123456789';

            const simbol = '!@#$%^&*()_+-=[]{}|;:,.<>?';

            const semuaKarakter = hurufKecil + hurufBesar + angka + simbol;


            // Panjang kata sandi (misalnya 12 karakter)

            const panjang = 12;

            let kataSandi = '';


            // Pastikan minimal 1 karakter dari setiap jenis

            kataSandi += hurufKecil[Math.floor(Math.random() * hurufKecil.length)];

            kataSandi += hurufBesar[Math.floor(Math.random() * hurufBesar.length)];

            kataSandi += angka[Math.floor(Math.random() * angka.length)];

            kataSandi += simbol[Math.floor(Math.random() * simbol.length)];


            // Tambahkan karakter acak sampai mencapai panjang yang diinginkan

            for (let i = kataSandi.length; i < panjang; i++) {

                kataSandi += semuaKarakter[Math.floor(Math.random() * semuaKarakter.length)];

            }


            // Acak ulang kata sandi agar posisi karakter lebih random

            kataSandi = kataSandi.split('').sort(() => Math.random() - 0.5).join('');


            // Tampilkan kata sandi di halaman

            document.getElementById('passwordOutput').innerText = kataSandi;

        }

    </script>

</body>

</html>

Wednesday, March 5, 2025

Refresh Div Elelment

 setInterval(function(){

  var refreshDiv = document.getElementById('#refresh'),

      request = XMLHttpRequest();

  

  request.open("GET", "myurl.html", false);

  request.send(null);

  

  var doc = document.implementation.createHTMLDocument("example");

  doc.documentElement.innerHTML = request.responseText;

  

  var refreshContent = doc.getElementById('#refresh').innerHTML;

  refreshDiv.innerHTML = refreshContent;

  

},5000);

Saturday, February 1, 2025

Drag Drop Menu Vanilla.JS

 <!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Drag and Drop Menu dengan Submenu</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.2/Sortable.min.js"></script>

    <style>

        body { font-family: Arial, sans-serif; }

        ul { list-style: none; padding: 0; width: 300px; }

        li {

            padding: 10px;

            margin: 5px;

            background: #f0f0f0;

            cursor: grab;

            border: 1px solid #ccc;

        }

        .submenu {

            padding-left: 20px;

        }

    </style>

</head>

<body>


<h3>Drag & Drop Menu dengan Submenu</h3>

<ul id="menu">

    <li>Home</li>

    <li>About

        <ul class="submenu">

            <li>Team</li>

            <li>Company</li>

        </ul>

    </li>

    <li>Services

        <ul class="submenu">

            <li>Web Design</li>

            <li>SEO</li>

        </ul>

    </li>

    <li>Contact</li>

</ul>


<script>

    new Sortable(document.getElementById("menu"), {

        animation: 150,

        group: "nested",

        fallbackOnBody: true,

        swapThreshold: 0.65

    });


    document.querySelectorAll('.submenu').forEach(sub => {

        new Sortable(sub, {

            animation: 150,

            group: "nested",

            fallbackOnBody: true,

            swapThreshold: 0.65

        });

    });

</script>


</body>

</html>


Drag and Drop Table Row Vanilla Javascript

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Drag & Drop Table Rows</title>

    <style>

        table {

            width: 100%;

            border-collapse: collapse;

        }

        th, td {

            padding: 10px;

            border: 1px solid #ddd;

            text-align: center;

        }

        tr.dragging {

            background-color: #f0f0f0;

            opacity: 0.6;

        }

    </style>

</head>

<body>


    <table>

        <thead>

            <tr>

                <th>#</th>

                <th>Name</th>

                <th>Age</th>

            </tr>

        </thead>

        <tbody id="table-body">

            <tr draggable="true">

                <td>1</td>

                <td>Alice</td>

                <td>25</td>

            </tr>

            <tr draggable="true">

                <td>2</td>

                <td>Bob</td>

                <td>30</td>

            </tr>

            <tr draggable="true">

                <td>3</td>

                <td>Charlie</td>

                <td>28</td>

            </tr>

        </tbody>

    </table>


    <script>

        document.addEventListener("DOMContentLoaded", () => {

            const tableBody = document.getElementById("table-body");

            let draggedRow = null;


            tableBody.addEventListener("dragstart", (event) => {

                draggedRow = event.target;

                draggedRow.classList.add("dragging");

            });


            tableBody.addEventListener("dragover", (event) => {

                event.preventDefault();

                const afterElement = getDragAfterElement(tableBody, event.clientY);

                if (afterElement == null) {

                    tableBody.appendChild(draggedRow);

                } else {

                    tableBody.insertBefore(draggedRow, afterElement);

                }

            });


            tableBody.addEventListener("dragend", () => {

                draggedRow.classList.remove("dragging");

            });


            function getDragAfterElement(container, y) {

                const rows = [...container.querySelectorAll("tr:not(.dragging)")];


                return rows.reduce((closest, child) => {

                    const box = child.getBoundingClientRect();

                    const offset = y - box.top - box.height / 2;

                    if (offset < 0 && offset > closest.offset) {

                        return { offset, element: child };

                    } else {

                        return closest;

                    }

                }, { offset: Number.NEGATIVE_INFINITY }).element;

            }

        });

    </script>


</body>

</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag & Drop Table Rows</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: center;
        }
        tr.dragging {
            background-color: #f0f0f0;
            opacity: 0.6;
        }
    </style>
</head>
<body>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody id="table-body">
            <tr draggable="true">
                <td>1</td>
                <td>Alice</td>
                <td>25</td>
            </tr>
            <tr draggable="true">
                <td>2</td>
                <td>Bob</td>
                <td>30</td>
            </tr>
            <tr draggable="true">
                <td>3</td>
                <td>Charlie</td>
                <td>28</td>
            </tr>
        </tbody>
    </table>

    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const tableBody = document.getElementById("table-body");
            let draggedRow = null;

            tableBody.addEventListener("dragstart", (event) => {
                draggedRow = event.target;
                draggedRow.classList.add("dragging");
            });

            tableBody.addEventListener("dragover", (event) => {
                event.preventDefault();
                const afterElement = getDragAfterElement(tableBody, event.clientY);
                if (afterElement == null) {
                    tableBody.appendChild(draggedRow);
                } else {
                    tableBody.insertBefore(draggedRow, afterElement);
                }
            });

            tableBody.addEventListener("dragend", () => {
                draggedRow.classList.remove("dragging");
            });

            function getDragAfterElement(container, y) {
                const rows = [...container.querySelectorAll("tr:not(.dragging)")];

                return rows.reduce((closest, child) => {
                    const box = child.getBoundingClientRect();
                    const offset = y - box.top - box.height / 2;
                    if (offset < 0 && offset > closest.offset) {
                        return { offset, element: child };
                    } else {
                        return closest;
                    }
                }, { offset: Number.NEGATIVE_INFINITY }).element;
            }
        });
    </script>

</body>
</html>

Monday, January 27, 2025

Crypto.JS Vanilla JS

 <!DOCTYPE html>

<html>

<head>

  <title>Contoh CryptoJS</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

</head>

<body>

  <input type="text" id="input-text" placeholder="Masukkan teks">

  <button onclick="encrypt()">Enkripsi</button>

  <button onclick="decrypt()">Dekripsi</button>

  <p id="result"></p>

  <script>

    function encrypt() {

      var message = document.getElementById('input-text').value;

      var key = "your_secret_key"; // Ganti dengan kunci rahasia Anda


      // Enkripsi menggunakan AES

      var ciphertext = CryptoJS.AES.encrypt(message, key).toString();


      document.getElementById('result').textContent = "Teks Terenkripsi: " + ciphertext;

    }


    function decrypt() {

      var ciphertext = document.getElementById('result').textContent.split(": ")[1];

      var key = "your_secret_key"; // Pastikan kunci sama dengan saat enkripsi


      // Dekripsi

      var bytes = CryptoJS.AES.decrypt(ciphertext, key);

      var originalText = bytes.toString(CryptoJS.enc.Utf8);


      document.getElementById('result').textContent = "Teks Asli: " + originalText;

    }

  </script>

</body>


</html>

Thursday, January 9, 2025

HMAC Untuk WEB TOKEN DENGAN Beda Server dengan PHP & Vanilla_JS

Server 1 = http://localhost:7000

hmac.php

<?php

header("Access-Control-Allow-Origin: *");

header("Content-Type: application/json; charset=UTF-8");

header("Access-Control-Allow-Headers: X-ACCESS_TOKEN, Origin, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$getheaders = getallheaders();

$secretKey = '8uRhAeH89naXfFXKGOEj';

$value = 'username=rasmuslerdorf';

$signature = $getheaders['Authorization'];

if (hash_equals(hash_hmac('sha256', $value, $secretKey), $signature)) {

    echo json_encode("The value is correctly signed.");

} else {

    echo json_encode("The value was tampered with.");

}

?>


Server 1 = http://localhost:9000

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

</body>

<script>

    window.addEventListener("load", async () => {

        await callData();

    })

    function callData() {

        fetch('http://localhost:7000/hmac.php', {

            method: 'GET',

            headers: {

                'Authorization': '8c35009d3b50caf7f5d2c1e031842e6b7823a1bb781d33c5237cd27b57b5f327'

            }

        })

            .then(response => response.json())

            .then(data => {

                console.log(data)

            })

    }

</script>

</html>


Set Cookie dan Remove Cookie dengan php vanilla.js

< html lang = "en" > < head >     < meta charset = "UTF-8" >     < meta name = "viewport...