HTMX Color Grid Demo

This is a demo of the HTMX javascript library.

To start with we draw a 8 x 8 grid of boxes and then when we click on them they will change to a random color.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Color Grid</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(8, 50px);
            grid-gap: 10px;
        }
        .grid-item {
            width: 50px;
            height: 50px;
            background-color: #DDD;
            border: 1px solid #333;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="grid-container" id="grid-container">
        <!-- Generate grid items using JavaScript -->
    </div>
    <script src="https://unpkg.com/htmx.org"></script>
    <script>
        function generateGrid() {
            const container = document.getElementById('grid-container');
            for (let i = 0; i < 64; i++) {
                const div = document.createElement('div');
                div.classList.add('grid-item');
                div.addEventListener('click', function() {
                    this.style.backgroundColor = getRandomColor();
                });
                container.appendChild(div);
            }
        }

        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        generateGrid();
    </script>
</body>
</html>


See it working here. Click on a box to see it change color randomly.


Color Grid

Now lets add in some htmx to the mix with an API to fetch a random media image from our media library to show how htmx can simplify using ajax and the WordPress json api endpoint.

So we will need a php script to function as our api that we can call to get a random image url from the image library. We will filter out all the non image media using regex and then return a random url of an image as a link. If you click on the link a image page will be displayed. If you click inside the box in an area not on the actual link displayed it will generate a new link dynamically.

PHP
<?php
$api_url = 'https://geekzonehosting.com/wp-json/wp/v2/media';
$json_data = file_get_contents($api_url);
$media_items = json_decode($json_data, true);

$filtered_media_items = array_filter($media_items, function ($item) {
    $file_url = $item['guid']['rendered'];
    return preg_match('/\.(webp|jpg|jpeg|png|gif)$/i', $file_url);
});

if (count($filtered_media_items) > 0) {
    $random_index = array_rand($filtered_media_items);
    $random_media = $filtered_media_items[$random_index];
    $media_id = $random_media['id'];
    $media_link = $random_media['guid']['rendered'];

    echo "<a href='{$media_link}' target='_blank'>Mystery Image #{$media_id}</a>";
} else {
    echo "No suitable media found.";
}
?>

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Grid with HTMX and PHP</title>
    <style>
        .grid-container1 {
            display: grid;
            grid-template-columns: repeat(8, 60px);
            grid-gap: 10px;
        }
        .grid-item {
            width: 60px;
            height: 60px;
            background-color: #DDD;
            border: 1px solid #333;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="grid-container1" id="grid-container1">
        <!-- Grid items will be generated here -->
    </div>
    <script src="https://unpkg.com/htmx.org"></script>
    <script>
        function generateGrid() {
            const container1 = document.getElementById('grid-container1');
            for (let i = 0; i < 64; i++) {
                const div = document.createElement('div');
                div.classList.add('grid-item');
                // HTMX AJAX call on click, set to fetch-random-image.php
                div.setAttribute('hx-get', 'fetch-random-image.php');
                div.setAttribute('hx-trigger', 'click');
                container1.appendChild(div);
            }
        }

        generateGrid();
    </script>
</body>
</html>

This is showing the code above as it is working.


Image Grid with HTMX and PHP

Now lets pull random posts and make links to them.


PHP
<?php
$api_url = 'https://geekzonehosting.com/wp-json/wp/v2/posts';
$json_data = file_get_contents($api_url);
$posts = json_decode($json_data, true);

if (count($posts) > 0) {
    $random_index = array_rand($posts);
    $random_post = $posts[$random_index];
    $post_id = $random_post['id'];
    $post_link = $random_post['link'];

    echo "<a href='{$post_link}' target='_blank'>Mystery Link #{$post_id}</a>";
} else {
    echo "No posts found.";
}
?>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Post Grid with HTMX and PHP</title>
    <style>
        .grid-container3 {
            display: grid;
            grid-template-columns: repeat(8, 50px);
            grid-gap: 10px;
        }
        .grid-item {
            width: 50px;
            height: 50px;
            background-color: #DDD;
            border: 1px solid #333;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="grid-container3" id="grid-container3">
        <!-- Grid items will be generated here -->
    </div>
    <script src="https://unpkg.com/htmx.org"></script>
    <script>
        function generateGrid() {
            const container3 = document.getElementById('grid-container3');
            for (let i = 0; i < 64; i++) {
                const div = document.createElement('div');
                div.classList.add('grid-item');
                // HTMX AJAX call on click
                div.setAttribute('hx-get', 'https://geekzonehosting.com/fetch-random-post.php');
                div.setAttribute('hx-trigger', 'click');
                container3.appendChild(div);
            }
        }

        generateGrid();
    </script>
</body>
</html>

Above code working


Random Post Grid with HTMX and PHP

Summery of blocks used to make this post

Showing code - Code Pro

Embedding code - Advanced Custom HTML


I truly hope you found these code demos of htmx helpful and educational. Please leave your comments, suggestions and please share.