Skip to content

Instantly share code, notes, and snippets.

@rajeshpillai
Created April 2, 2023 12:32
Show Gist options
  • Save rajeshpillai/cfce74c066041cfdbe9a10b0877a016a to your computer and use it in GitHub Desktop.
Save rajeshpillai/cfce74c066041cfdbe9a10b0877a016a to your computer and use it in GitHub Desktop.

Revisions

  1. rajeshpillai created this gist Apr 2, 2023.
    72 changes: 72 additions & 0 deletions htmltag.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    console.clear();


    function html(strings, ...values) {
    // Combine the strings and values into a single string
    const combined = strings.reduce((acc, str, i) => acc + str + (values[i] !== undefined ? ${i}§` : ''), '');

    console.log({combined});
    // Create a temporary container to hold the HTML string
    const container = document.createElement('div');
    container.innerHTML = combined;

    // Attach event listeners
    container.querySelectorAll('*').forEach(element => {
    const attributes = [...element.attributes];
    attributes.forEach(attr => {
    if (attr.name.startsWith('@')) {
    let eventName = attr.name.slice(1);
    const index = parseInt(attr.value.slice(1, -1), 10);
    const handler = values[index];

    element.removeAttribute(attr.name);

    // Check if the provided handler is a function
    if (typeof handler === 'function') {
    eventName = eventName.substr(2);
    console.log("function::", element, eventName, handler);
    // This work (event should not have 'on' prefix)
    element.addEventListener(eventName, handler);

    // This works (event Should have 'on' prefix)
    //element[eventName] = handler;

    } else {
    console.error(`EventHandlerError: The provided event handler is not a function.`);
    }
    }
    });
    });


    // Return the first child element
    return container.firstElementChild;
    }



    // Example
    // Example usage: create a button with a click event handler

    const root = document.getElementById('root');

    const onclick = () => {
    alert('Button clicked!');
    };

    const onMouseMove = (e) => {
    console.log("mousemove: (e) ", e.offsetX, e.offsetY);
    }

    const buttonHtml = html`
    <div>
    <h1>Testing DOM and events </h1>
    <button
    @onclick=${onclick}
    @onmousemove=${onMouseMove}>Click me
    </button>
    </div>
    `;

    console.log(buttonHtml);
    document.body.appendChild(buttonHtml);