Using Scripts

In the previous topic, Using Events, we included JavaScript routines as explicit strings within the Lisp code to generate a Web page.

CL-HTTP provides several routines to allow you to work with foreign-language scripts, such as JavaScript, in a more streamlined way:

define-script allows you to specify a script, with the JavaScript to be emitted in the head of the page to define the script, and the JavaScript to be emitted in the body of the page to call the script. In each case you can specify parameters, to pass values from Lisp to the JavaScript being emitted.

intern-script is used to register the script.

declare-script or write-script emit the definition of the script to the stream.

These are each explained in more detail in the following sections.

Defining a script - define-script

The define-script procedure has the format:

(define-script name (:JavaScript) :script script :caller caller )

where name is a name used to refer to the script.

The :script parameter defines the JavaScript to be written out in the head of the page, typically used to for JavaScript function definitions.

The :caller parameter is used to define the JavaScript to call the JavaScript routine.

Each parameter can either be a string, or a function of stream to write the script to the stream.

Creating a JavaScript popup

As an example of using define-script, here is a JavaScript routine to show or hide a popup:

(define-script toggle-dialog (:Java-Script)
               ((script stream state)
                (fast-format stream "\"document.getElementById('popup').style.visibility='~a'\"" state)))

Here's the definition of the page that uses it:

(defun write-script-demo (url stream)
  (declare (ignore url))
  (let ((script (intern-script :toggle-dialog :java-script)))
        (events (:java-script :mouse-over (event-caller script "visible"))
                (:java-script :mouse-out (event-caller script "hidden")))
      (with-page (url stream "Script Demo")
        (with-paragraph (:stream stream)
          (note-anchor "Reset" :reference "#" :events events :stream stream)
          (with-division (:inline-p t :id "popup" :style "visibility:hidden;" :stream stream)
            (write-string "<- Click to reset your settings" stream)))))))

Here's the code to export the URL:

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

When the user moves the mouse over the link the visibility of the popup message is set to visible:


Moving the mouse pointer off the link sets the visibility back to hidden.

blog comments powered by Disqus