htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Alternative way to make AJAX, Web Sockets, etc available directly in HTML with only one attribute!

Open mrhdias opened this issue 1 year ago • 0 comments

Instead of using multiple attributes to access AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, is it possible to implement an alternative way to achieve the same purpose but using just one attribute?

My idea is to use the same strategy that is used with the style attribute, to specifies an inline style for an element.

Example for style: <button style="color: blue; text-align: center;">Test</button>

Example from htmx: <button hx-post="/clicked" hx-swap="outerHTML">Click Me</button>

Example of my proposal: <button data-jsox="method: post; action: /clicked; swap: outerHTML;">Click Me</button>

I think the two forms could coexist together. It would just be a more compact alternative to specifying the parameters.

I made an HTML page to test the concept, which can be seen below:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <button data-jsox="action: /test;
        method: get;
        target: this;" style="color: #000;">Test</button>
    <script>

        function dataSet2Obj(data) {
            const parameters = data.replace(/[\r\n] */gm, '').replace(/\;$/, '').split(/\; */);

            var obj = {};
            parameters.forEach(function (keyValuePair) {
                const tup = keyValuePair.split(/\: */);
                if (tup.length != 2) {
                    console.log('wrong data atribute: ' + keyValuePair);
                }
                obj[tup[0]] = tup[1];
            });

            return obj;
        }

        const data = document.querySelectorAll("[data-jsox]");
        const parameters = dataSet2Obj(data[0].dataset.jsox);

        console.log("Parameters:", parameters);
        console.log("Action:", parameters.action);
        console.log("Method:", parameters.method);
        console.log("Target:", parameters.target);

    </script>
</body>
</html>

Output:

Parameters: {action: '/test', method: 'get', target: 'this'}
index.html:30 Action: /test
index.html:31 Method: get
index.html:32 Target: this

Does it make sense to implement this alternative?

mrhdias avatar Dec 13 '23 19:12 mrhdias