Introduction

Installation

Frequently asked questions

Syntax, keywords and built-in functions

Standard distribution

import implementation

Browser interface

Introduction - DOM API
Creating a document
Accessing elements
Attributes and methods

Events
Mouse events
Keyboard events
Focus events
Drag events

Query string

Using Javascript objects and libraries

Brython-specific built-in modules

browser
browser.ajax
browser.html
browser.local_storage
browser.markdown
browser.object_storage
browser.session_storage
browser.svg
browser.template
browser.timer
browser.websocket
browser.webworker

javascript
asyncio
asyncio.fs

Working with Brython

Options of function brython()
Testing and debugging
Deploying an application

Brython for Firefox OS

Introduction
WebApps : design
WebApps : application

Cookbook

Hello world !
Insert content in an element
HTML markup (bold,italic...)
HTML table
Bind and unbind events
Handle options in a SELECT
Drag and drop
Get the content of an element
Read the content of a file
Store objects locally
Example of onmouseover
 

Events

Introduction

Suppose we have in a page a element of type button, like this one :

If you click on it, nothing will happen, because no instruction was given on how to react to a click. For that, the action to take is defined by this syntax :

def show(ev):
    ...

btn.bind("click", show)

btn is a reference to the lement. The arguments of bind are the type of event the button must handle, and the function to call when this event occurs. The following pages give many examples of such events for mouse, keyboard, drag-and-drop, etc.

The callback function takes a single argument, an instance of the class DOMEvent defined in module browser. For instance :

def show(ev):
    print('ok')

btn.bind("click", show)

(remember that to see the results of print the browser console must be open)

Instances of DOMEvent have a number of attributes that depend on the event type. In the case of a click, and more generally for events related to the mouse, the attributes include

  • target : the element the event was dispatched on
  • x, y : position of the mouse relatively to the upper left corner of the window

For instance, to print the button text and the mouse position :

def show(ev):
    print(ev.target.text, ev.x, ev.y)

btn.bind("click", show)

Interface

For events management, the elements of a page have the following methods :

elt.bind(evt_name, handler)

the handler function is called when the event event_name occurs on the element

elt.unbind(evt_name[, handler])

removes the association of function handler to the event named evt_name. If handler is omitted, removes all the associations for the event

elt.events(evt_name)

returns the list of functions that handle the event named evt_name

Using the decorator browser.bind

New in version 3.6.0

The browser module defines a function bind that can be used as a decorator for an event handler. Its syntax is

@bind(target, evt)

If target is a DOMNode instance, the decorated function handles the event evt on this element.

If target is a string, it is interpreted as a CSS selector ; for all the elements in the page that match this selector, the event evt is managed by the decorated function.

Examples:

from browser import document, bind

@bind(document[element_id], "mouseover")
def mouseover(ev):
    ...

@bind("div.foo", "enter") # all the DIV elements with attribute class="foo"
def enter(ev):
    ...

DOMEvent objects

(information by Mozilla Contributors, found at https://developer.mozilla.org/en-US/docs/Web/API/event)

Whatever the event type, instances of class DOMEvent have the following attributes

bubbles
boolean, indicates whether the given event bubbles up through the DOM or not

cancelable
boolean, indicates whether the event is cancelable or not

currentTarget
instance of DOMNode ; identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.

defaultPrevented
boolean indicating whether or not event.preventDefault() was called on the event

eventPhase
integer, indicates which phase of the event flow is currently being evaluated

target
DOMNode instance ; the object the event was dispatched on. It is different than event.currentTarget when the event handler is called in bubbling or capturing phase of the event

timeStamp
integer, the time (in milliseconds since Jan. 1st, 1970 at 0h) at which the event was created

type
string, contains the event type

and the following methods

preventDefault()
prevents the execution of the action associated by default to the event

Example

When a checkbox is clicked on, the default action is to show or hide a tick inside the checkbox :

checkbox (default behaviour)

To disable this behaviour on the checkbox :

from browser import document

def _cancel(ev):
    ev.preventDefault()

document["disabled_cbox"].bind("click",_cancel)

result :

disabled checkbox

stopPropagation()
prevents further propagation of the current event

Example

In the coloured zone below

outer

inner, normal propagation
inner, propagation stopped

the 3 elements (the outer yellow frame and the inner blue and green frames) handle the click event

from browser import document, alert

def show(ev):
    alert("click on %s" %ev.currentTarget.id)

def show_stop(ev):
    alert("clic on %s" %ev.currentTarget.id)
    ev.stopPropagation()

document["yellow"].bind("click",show)
document["blue"].bind("click",show)
document["green"].bind("click",show_stop)

Clicking on the yellow zone triggers the call of function show(), which prints the message "click on yellow".

A click on the blue zone triggers the alert message "click on blue". Then the event propagates to the parent, the yellow frame. Since this frame also handles the event "click", the browser calls the associated action, the same function show(), and shows the message "click on yellow" (notice that the attribute currentTarget is updated when the event propagates).

Clicking on the green zone cause the message "click on green" to pop up. This event is handled by the function show_stop(), which ends in

ev.stopPropagation()

So the event does not propagate to the upper level and the execution exits without an alert box "click on yellow".

Creating and firing an event

If you want to fire an event on an element, first check the Event reference ; for instance, the event "click" uses the DOM interface MouseEvent, available in Brython by window.MouseEvent.

MouseEvent is a constructor, so to create the event object use its attribute new :

event = window.MouseEvent.new("click")

then

element.dispatchEvent(event)

fires the event on the specified element.