Using Events

You can associate JavaScript code with appropriate HTML constructs using the :events keyword.

The :events keyword takes a list of event definitions of the form:

((event . :JavaScript)  javascript-code)

where event is a keyword such as :mouse-click to define the action that should trigger the event, and javascript-code is the code to run when the event is triggered. This should either be a string, or a function which will be called with the stream as a parameter.

Creating a modal dialog

As a simple example of using the :events parameter here's a simple application to create a JavaScript modal dialog:

(defparameter *overlay*
(defparameter *dialog*
 "width:300px;margin:60px auto;background-color:white;border:2px solid;text-align:center;")
(defun write-events-demo (url stream)
  (declare (ignore url))
  (with-page (url stream "Events Demo")
    (with-paragraph (:stream stream)
      (note-anchor "Click to show dialog" :reference "#"
                   :events '(((:mouse-click . :java-script)
                   :stream stream))
    (with-division (:id "overlay" :style *overlay* :stream stream)
      (with-division (:style *dialog* :stream stream)
        (with-paragraph (:stream stream)
          (write-string "Warning - save before closing!" stream))
          (note-anchor "Hide" :reference "#"
                   :events '(((:mouse-click . :java-script)
                   :stream stream)))))

Here's hthe definition of the URL:

(export-url "http://localhost:8000/events.html"
            :response-function 'write-events-demo)

Going to this page displays a link:


Clicking on the link shows the modal dialog:


Using with-event-handlers

CL-HTTP includes a procedure with-event-handlers to help you define lists of event definitions for use as the parameter to the :events keyword.

In its simplest version with-event-handlers can take a string defining the JavaScript you want to emit. So you could define the show-event in the above example as follows:

      (show-event (:java-script :mouse-click 
    (with-page (url stream "Events Demo")
      (with-paragraph (:stream stream)
        (note-anchor "Click to show dialog" :reference "#" :events show-event :stream stream))

blog comments powered by Disqus