hub.eb?material_id=383&track_id=426

Binding Custom jQuery Event Handlers


It is typical to use the HTML Element Properties window to bind jQuery events however, this is not the only available option and there may be circumstances in which it is preferable to bind a jQuery event from within a JavaScript Web Resource.

The HTML Element Properties window is suitable for usual jQuery bindings such as .on(‘click’) however there are many other possible binding and unbinding options available in jQuery. The documentation for these can be found here.

E.g. To bind jQuery click events to all hyperlinks in the page body, use the following code:

$("body").on("click", "a", function(){
  alert("Clicked!");
});

Steps


1

Create a form and add a Panel Control. Give the panel a black border, 300px width and 300px height using the Styling Assistant.

Give the panel the id myPanel.

2

Create a new JavaScript Web Resource called customEventBindings with the following code:

// wait until the page is ready
$(function(){
  // bind a click event handler to myPanel
  $("#myPanel").on("click", randomiseColour);

  // function to randomise a background colour
  function randomiseColour(){
    $(this).css("background-color", getRandomColour());
  }
})


function getRandomColour() {
  // An HTML colour is made up of 3 values: red (R), green (G) and blue (B)
  // Each of these values is between 0 and 255
  var colour = Math.floor(Math.random() * (255*255*255));
  // Return the colour in hexadecimal (base 16)
  return '#' + colour.toString(16);
}
3

Attach the customEventBindings file to the form Web Resources.

4

Run the form, trigger the click event and observe the result.

Current Module

Related