JavaScript

The JavaScript element in Mition allows you to add custom scripts to enhance the functionality and interactivity of your website.

This element is ideal for embedding dynamic features that go beyond standard HTML and CSS.

There is a section for javascript and a HTML section where you can add <script> and <style> tags for your own html for that page.

If you want this script to run on everypage, use this control on the homepage and add the class "wholesite" which will add it automatically to every webpage, we use this for additional footer controls.


WARNING: the script might run before the HTML elements are present, so to ensure the elements are there when the script runs, we suggest to create a function that checks for the id or classname of the HTML component before running, see the sample javascript below. For simple <script and <style tags these will load when the site loads as usual.

Key Features
  1. Custom Interactivity: Add behaviours like pop-ups.
  2. Event Handling: Respond to user actions (e.g., clicks, scrolls, or keypresses).
  3. Third-Party Integrations: Embed external tools or widgets, like chatbots or analytics.


Examples
  1. Interactive Forms: Validate user input in real time or provide instant feedback as users fill out forms.
  2. Dynamic Content: Use JavaScript to load content dynamically without reloading the page, like filtering products on an e-commerce site.

    You can get AI to help you write functions too.

write a sample javascript function that keeps looking for an id of an element and adds a listener to it that says alert('clicked'), wait 1 second before retrying, console.log('not found: ' + count) each time it is not found and if count reaches > 10 abort.



This is the code in this example:

Javascript

function waitForElementAndAddClickListener(elementId, maxRetries = 10) {
  let retries = 0;

  function checkForElement() {
    const targetElement = document.getElementById(elementId);

    if (targetElement) {
      // Element found! Add a click event listener.
      targetElement.addEventListener('click', () => {
        alert('Clicked!');
      });
    } else {
      // Element not found.
      retries++;
      console.log(`Element with ID "${elementId}" not found. Retries: ${retries}`);

      if (retries >= maxRetries) {
        console.log(`Aborting after ${maxRetries} retries.`);
        return;
      }

      // Retry after 1 second.
      setTimeout(checkForElement, 1000);
    }
  }

  // Start checking for the element.
  checkForElement();
}

// Usage example:
waitForElementAndAddClickListener('ExampleButton');

This is in the HTML (note you have to add HTML as source code see the </> button in the test editor

<button id="ExampleButton" class="btn btn-primary">Click Me</button>


Linked Web Component

How to find your component. Search for it: When selecting a linked web component, it will list every webpage / component in order of pages and component. The fastest way to find a Web Component: go and find the Copy Anchor on the component wanting to...

Read More

Certainly! Here is an AI prompt designed to instruct an AI Agent on how to create a Hello World Mition Javascript Web Component with styles embedded in HTML and the script provided separately:


---


# AI Prompt for AI Agent: Create a Hello World Mition Javascript Web Component


## Objective


Develop a small, reusable Mition Javascript Web Component that:


- Displays "Hello, Mition World!" with styled text and fade-in animation.

- Includes a button that calls the Mition backend API `/api/login/isAuthenticated`.

- Shows the authentication result below the button.

- Uses inline styles embedded inside a `<style>` tag in the HTML section.

- Provides the JavaScript separately to enable clean code separation and reuse.

- Follows Mition development best practices: no global namespace pollution, polling for DOM element, safe to initialise multiple times.


## Deliverables


### 1. HTML with inline styles and placeholder div


```html

<div id="hello-world"></div>


<style>

 #hello-world {

    font-family: Arial, sans-serif;

    padding: 10px;

    background: linear-gradient(90deg, #006cc, #00ccff);

    color: white;

    text-align: center;

    border-radius: 8px;

    animation: fadeIn 2s ease-in-out;

  }

  @keyframes fadeIn {

    from { opacity: 0; }

    to { opacity: 1; }

  }

  #hello-world button {

    margin-top: 10px;

    padding: 8px 16px;

    font-size: 16px;

    border: none;

    border-radius: 5px;

    cursor: pointer;

    background-color: #004080;

    color: white;

    transition: background-color 0.3s;

  }

  #hello-world button:hover {

    background-color: #003060;

  }

</style>

```


### 2. JavaScript Component Script (Separate file or inline script)


```js

(function() {

  const selector = '#hello-world';

  const pollInterval = 100;

  let attempts = 0;

  const maxAttempts = 50;


  const pollDOM = setInterval(() => {

    const element = document.querySelector(selector);

    if (element) {

      clearInterval(pollDOM);

      initComponent(element);

    } else if (++attempts >= maxAttempts) {

      clearInterval(pollDOM);

    }

  }, pollInterval);


  function initComponent(el) {

    if (el.dataset.mitionHelloInit) return;


    el.innerHTML = `

      <div>Hello, Mition World!</div>

      <button id="check-auth">Check if Authenticated</button>

      <div id="auth-result" style="margin-top:10px; font-weight:bold;"></div>

    `;


    const button = el.querySelector('#check-auth');

    const resultDiv = el.querySelector('#auth-result');


    button.addEventListener('click', () => {

      fetch('/api/login/isAuthenticated')

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

        .then(data => {

          if (data.isAuthenticated) {

            resultDiv.textContent = 'User is authenticated!';

          } else {

            resultDiv.textContent = 'User is NOT authenticated.';

          }

        })

        .catch(error => {

          resultDiv.textContent = 'Error checking authentication.';

          console.error('API error:', error);

        });

    });


    el.dataset.mitionHelloInit = 'true';

  }

})();

```


## Usage Instructions


1. Add the provided HTML snippet including the `<div id="hello-world"></div>` and `<style>` tags to your Mition page where you want the component to appear.


2. Include the JavaScript code either as a separate script file or embedded inline, ensuring it runs on the page.


3. The component will poll for the target element and initialise once found.


4. Users can click the button to check authentication status from Mition’s backend.


---


If you want, I can help generate code files or assist with integration steps for this component. Would you like that?

This webpage was built with Mition