Skip to main content

JavaScript
How to Use URLSearchParams

script.js

// AZUL CODING ---------------------------------------
// JavaScript - How to Use URLSearchParams
// https://youtu.be/KUN0Vkn207k


var urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("red")) addvalue("red", urlParams.get("red"));
if (urlParams.has("green")) addvalue("green", urlParams.get("green"));
if (urlParams.has("blue")) addvalue("blue", urlParams.get("blue"));

for (let p of urlParams) {
    console.log(p[0] + " : " + p[1]);
}

function randomise() {
    var urlParams = new URLSearchParams();
    urlParams.set("red", Math.round(Math.random() * 255));
    urlParams.set("green", Math.round(Math.random() * 255));
    urlParams.set("blue", Math.round(Math.random() * 255));
    window.location.href = "/?" + urlParams.toString();
}

function addvalue(name, val) {
    const element = document.getElementById(name).innerText = val;
}

Enjoying this tutorial?


index.html

<!-- AZUL CODING --------------------------------------- -->
<!-- JavaScript - How to Use URLSearchParams -->
<!-- https://youtu.be/KUN0Vkn207k -->


<!DOCTYPE html>
<html>
    <head>
        <title>URLSearchParams</title>
        <style>
            body {
                margin: 30px;
                font-family: 'Roboto';
            }
            table {
                text-align: left;
                border-spacing: 0;
            }
            h2 {
                margin: 0;
                padding-right: 20px;
            }
            button {
                margin-top: 30px;
                font-size: 16px;
                font-family: 'Roboto';
            }
        </style>
    </head>
    <body>
        <h1>URLSearchParams</h1>
        <table>
            <tr>
                <th><h2 style="color:red">Red</h2></th>
                <td><h2 id="red">0</h2></td>
            </tr>
            <tr>
                <th><h2 style="color:green">Green</h2></th>
                <td><h2 id="green">0</h2></td>
            </tr>
            <tr>
                <th><h2 style="color:blue">Blue</h2></th>
                <td><h2 id="blue">0</h2></td>
            </tr>
        </table>
        <button onclick="randomise();">Random</button>
        <script src="script.js"></script>
    </body>
</html>