Event Handler

This document provides comprehensive details on the event handler in Prisma PHP. It explains various event attributes and their descriptions, such as onclick, ondblclick, onmousedown, and more. Understanding these event attributes will help you respond to user actions and create interactive web applications.

Event Handler Table

Event Attribute Description
onclick Triggered when the element is clicked.
ondblclick Triggered when the element is double-clicked.
onmousedown Triggered when a mouse button is pressed down on the element.
onmouseup Triggered when a mouse button is released over the element.
onmouseover Triggered when the mouse pointer is moved onto the element.
onmousemove Triggered when the mouse pointer is moving within the element.
onmouseout Triggered when the mouse pointer is moved out of the element.
onwheel Triggered when the mouse wheel is rotated.
onkeypress Triggered when a key is pressed down and released on the element.
onkeydown Triggered when a key is pressed down on the element.
onkeyup Triggered when a key is released on the element.
onfocus Triggered when the element receives focus.
onblur Triggered when the element loses focus.
onchange Triggered when the element's value changes.
oninput Triggered when the element receives user input.
onselect Triggered when text within the element is selected.
onsubmit Triggered when a form is submitted.
onreset Triggered when a form is reset.
onresize Triggered when the element is resized.
onscroll Triggered when the element's scrollbar is scrolled.
onload Triggered when the element has finished loading.
onunload Triggered when the document or a resource is being unloaded.
onabort Triggered when the loading of a resource is aborted.
onerror Triggered when an error occurs.
onbeforeunload Triggered when the window or tab is about to be closed or refreshed.
oncopy Triggered when the content is copied.
oncut Triggered when the content is cut.
onpaste Triggered when the content is pasted.
ondrag Triggered when an element is being dragged.
ondragstart Triggered when dragging starts.
ondragend Triggered when dragging ends.
ondragover Triggered when an element is being dragged over a valid drop target.
ondragenter Triggered when a dragged element enters a valid drop target.
ondragleave Triggered when a dragged element leaves a valid drop target.
ondrop Triggered when a dragged element is dropped on a valid drop target.
oncontextmenu Triggered when the context menu is opened (usually with a right-click).
ontouchstart Triggered when a touch point is placed on the touch surface.
ontouchmove Triggered when a touch point is moved along the touch surface.
ontouchend Triggered when a touch point is removed from the touch surface.
ontouchcancel Triggered when the touch event is canceled.
onpointerdown Triggered when a pointer is placed on the touch surface.
onpointerup Triggered when a pointer is lifted from the touch surface.
onpointermove Triggered when a pointer moves on the touch surface.
onpointerover Triggered when a pointer is moved onto an element.
onpointerout Triggered when a pointer is moved out of an element.
onpointerenter Triggered when a pointer enters an element.
onpointerleave Triggered when a pointer leaves an element.
onpointercancel Triggered when the pointer event is canceled.

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example, if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this case, the button click is an event, and the information box display is the response to the event.

Events can be triggered by various actions, such as user actions (click, double-click, mouse movement), system actions (loading, resizing, scrolling), or data changes (input, selection, submission).

Event handlers are functions that are executed in response to an event. They are used to define the behavior of the system when an event occurs. For example, you can define a function that displays an alert message when a button is clicked or changes the background color of an element when the mouse hovers over it.

Sending Params

Event handlers can receive parameters when they are triggered. These parameters can be used to pass additional information to the event handler function. For example, you can pass the event object itself or custom data to the event handler function. There are three ways to send parameters to an event handler function: by name, by form, or by directly setting them as parameters in the function.

Example Usage

<button onclick="sayHello('param1', 'param1')">Click Me!</button> // sending arguments format
  <button onclick="sayHello({'id': 'yourID'})">Click Me!</button> // sending JSON format
  <input name="user" oninput="searchUser" type="search" placeholder="Search user..."/> // sending with name attribute
  <form onsubmit="createUser"> // sending on submit using inputs with the name attribute
    <input name="user" placeholder="User name"/>
  </form>

Default JavaScript Event execution

When a button is clicked, the JavaScript event handler is executed first. If no matching JavaScript function is found, the event handler will then look for a PHP function with the same name. This mechanism allows you to define the system's behavior upon an event occurrence using either JavaScript or PHP, providing flexibility in handling events.

<?php

  // PHP Function with the name sayHello will not be called from the HTML file because JavaScript function with the same name is called first.
  function sayHello($param1, $param2)
  {
      echo $param1 . ' ' . $param2;
  }
  
  ?>
  
  <button class="bg-blue-500 p-2 rounded-md text-white" onclick="sayHello('param1', 'param1')">Click Me!</button>
  <script>
      function sayHello(param1, param2) {
          alert(param1 + ' ' + param2);
      }
  </script>

Call PHP Function and JavaScript Function

When a button is clicked, the sayHello function is called from the HTML. This function exists in the PHP section and will be executed. By using the pp-after-request attribute, the getSayHelloResponse function will be called after the PHP function completes, allowing you to easily interact with the PHP function and handle its response.

<?php

  function sayHello($data)
  {
      return $data;
  }
  
  ?>
  
  <button class="bg-blue-500 p-2 rounded-md text-white" onclick="sayHello('param1', 'param1')" pp-after-request="getSayHelloResponse">Click Me!</button>
  <script>
      function getSayHelloResponse(data) {
          console.log("🚀 ~ getSayHelloResponse ~ data:", data)
          alert(`${data.response.args[0]}, ${data.response.args[1]}`);
      }
  </script>

Close Dialog Modal and Refresh Page

When the close button is clicked, the dialog will close first, and then the refresh function will be called. This function is defined in the PHP section and will be executed. Currently, the function is empty and does not perform any actions. However, if there is a StateManager to update, this refresh function can be useful for updating the current page state.

<?php

  use Lib\StateManager;
  
  $count = StateManager::getState('count', 0);
  
  function increment()
  {
      global $count;
  
      StateManager::setState('count', ++$count);
  }
  
  function refresh() {}
  
  ?>
  
  <div class="w-screen h-screen grid place-items-center">
      <div class="flex flex-col gap-2">
          <p>Count: <?= $count ?></p>
          <button onclick="welcomeModal.showModal()">Show Dialog</button>
      </div>
  
      <dialog id="welcomeModal" class="rounded-md">
          <div class="bg-white rounded-lg shadow-lg p-6 max-w-md w-full relative">
              <form method="dialog">
                  <button onclick="refresh" class="absolute right-2 top-2 text-gray-500 hover:text-gray-700   focus:outline-none">
                      ✕
                  </button>
              </form>
              <h3 class="text-lg font-bold">Welcome to Prisma PHP!</h3>
            <p class="py-4 text-gray-700">We're thrilled to have you here. Explore the features and enjoy your experience. If you   need any help, don't hesitate to reach out to our support team.</p>
  
            <button onclick="increment" pp-after-request="@close" class="bg-blue-500 text-white px-4 py-2 rounded-md">Increment</button>
          </div>
      </dialog>
  </div>

Receiving Data in Arguments Format PHP Function

Receiving data in arguments format means that when you send data in arguments format, it will be received as an array in the args key. This array will contain all the data that was sent as parameters.

<?php

  function handleArgsParams($data) {
    echo 'param1->value: ' . $data->args[0];
    echo 'param2->value: ' . $data->args[1];
  }

  ?>

  <button onclick="handleArgsParams('param1', 'param2')">Click Me!</button>

Receiving Data in JSON Format

Receiving data in JSON format has the advantage of sending consistent data, and you can use the object type to access the parameters sent. You can access the parameters using the syntax $data->key, which makes it easy to handle the data in the function call.

<?php

  function handleJSONParams($data) {
    echo 'id: ' . $data->id . '<br>';
    echo 'title: ' . $data->title;
  }

  ?>

  <button onclick="handleJSONParams({'id': 'yourID', 'title': 'yourTitle'})">Click Me!</button>

Receiving Input Data with Name Attribute

Receiving data in JSON format with the name attribute is a common practice. When an input has a name attribute, the data will be converted to JSON format with key-value pairs. If the input does not have a name attribute, it will be set with a value key to retrieve the sent data.

<?php

  function handleInputWithNameAttribute($data) {
      echo $data->user;
  }
  
  function handleInputWithoutNameAttribute($data) {
      echo $data->value;
  }
  
  ?>
  
  <input oninput="handleInputWithNameAttribute" name="user" type="search" placeholder="With Name Attribute..." class="mt-2 p-2 border border-gray-300 rounded" />
  <br>
  <input id="maintain-focus" oninput="handleInputWithoutNameAttribute" type="search" placeholder="Without Name Attribute..." class="mt-2 p-2 border border-gray-300 rounded" />

Note: The name attribute is used to identify the input element and is essential for sending data in JSON format. If the input does not have a name attribute, the data will be sent with the value key. Additionally, the id attribute is used to maintain focus on the element.

Handle Checkbox Change

Receiving data in JSON format with the name attribute is a common practice. When an input has a name attribute, and the type is checkbox or radio, the data will be converted to JSON format with key-value pairs. It is recommended to also include the id attribute to uniquely identify the input, and maintain focus on the element.

<?php

  function handleSingleCheckboxChange($data)
  {
    echo 'is checked: ' . $data->completed->checked;
  }

  ?>

  <input type="checkbox" name="completed" onchange="handleSingleCheckboxChange">

Handle Multiple Checkbox Change

Receiving data in JSON format with the name attribute is a common practice. When an input has a name attribute, and the type is checkbox or radio, the data will be converted to JSON format with key-value pairs. It is recommended to also include the id attribute to uniquely identify the input, and maintain focus on the element.

<?php

  $myArray = [
      "Technology" => false,
      "Science" => false,
      "Health" => false,
      "Education" => false,
      "Sports" => false
  ];
  
  function handleMultipleCheckboxChange($data)
  {
      global $myArray;
  
      echo $data->categories->value . ": " . $data->categories->checked . "<br>";
  
      $myArray[$data->categories->value] = $data->categories->checked;
  
      echo json_encode($myArray);
  }
  
  ?>
  
  <h1>Select Categories</h1>
  <div>
      <label>
          <input id="technology" type="checkbox" name="categories" value="Technology" onchange="handleMultipleCheckboxChange">
          Technology
      </label>
      <label>
          <input id="science" type="checkbox" name="categories" value="Science" onchange="handleMultipleCheckboxChange">
          Science
      </label>
      <label>
          <input id="health" type="checkbox" name="categories" value="Health" onchange="handleMultipleCheckboxChange">
          Health
      </label>
      <label>
          <input id="education" type="checkbox" name="categories" value="Education" onchange="handleMultipleCheckboxChange">
          Education
      </label>
      <label>
          <input id="sports" type="checkbox" name="categories" value="Sports" onchange="handleMultipleCheckboxChange">
          Sports
      </label>
  </div>

Handle Radio Change

Receiving data in JSON format with the name attribute is a common practice. When an input has a name attribute, and the type is radio, the data will be converted to JSON format with key-value pairs. It is recommended to also include the id attribute to uniquely identify the input, and maintain focus on the element.

<?php

  function handleRadioChange($data)
  {
    echo 'Selected sport: ' . $data->sport;
  }

  ?>

  <h1>Sport</h1>
  <div>
      <div class="radio-group">
          <input id="sport1" name="sport" onchange="handleRadioChange" type="radio" value="Football" />
          <label for="sport1">Football</label>
      </div>
      <div class="radio-group">
          <input id="sport2" name="sport" onchange="handleRadioChange" type="radio" value="Basketball" />
          <label for="sport2">Basketball</label>
      </div>
      <div class="radio-group">
          <input id="sport3" name="sport" onchange="handleRadioChange" type="radio" value="Tennis" />
          <label for="sport3">Tennis</label>
      </div>
  </div>

Handle Select Change

Receiving data in JSON format with the name attribute is a common practice. When selecting an option from a dropdown, the data will be converted to JSON format with key-value pairs. This allows for easy handling of the selected data in the function.

<?php

  function handleSelectChange($data)
  {
    echo 'Selected sport: ' . $data->sports;
  }

  ?>

  <h1>Sports</h1>
  <select class="border p-2 rounded-md" name="sports" onchange="handleSelectChange">
      <option selected disabled>Select a sport</option>
      <option value="football">Football</option>
      <option value="basketball">Basketball</option>
      <option value="tennis">Tennis</option>
      <option value="volleyball">Volleyball</option>
  </select>

Handle Form Submission

Receiving data in JSON format with the name attribute is a common practice. When using a form and submitting it, all child elements with the name attribute, such as input, select, textarea, and others, will be converted into JSON key-value pairs. This makes it easy to handle the data in the function.

<?php

  function handleFormSubmit($data)
  {
      echo "Name: " . $data->name . "<br>";
      echo "Age: " . $data->age;
  }
  
  ?>
  
  <form onsubmit="handleFormSubmit">
      <input class="border p-2 rounded-md" name="name" placeholder="Name" />
      <input class="border p-2 rounded-md" name="age" type="number" placeholder="age" />
      <button class="p-2 bg-blue-500 rounded-md text-white" type="submit">Submit</button>
  </form>