KnockoutJS Event Binding

In the last article we started studying form-field bindings. We saw click binding with the help of an example. In this article, we shall study yet another type of form-field binding i.e. knockoutJS event binding. In the click binding article we saw how to bind click event on any DOM element with an event handler which was basically a function in JavaScript view model. However there are several other types of event which can also be handled. KnockoutJS event binding basically handles such events. For instance you may want to execute a specific function when user hover mouse over a DOM element or leaves a DOM element. In such cases event binding comes handy.

KnockoutJS Event Binding Example

Take a look at the following code, here we shall execute functions based on user interaction with DOM elements. We shall handle the mouseover and mouseout events.

If binding Example!

<!DOCTYPE html>
<script src=""></script>
        background: yellow;

    <div class="yellow" data-bind="event: { mouseover: displayDetails, mouseout: hideDetails }">
        Mouse over me
    <div data-bind="visible: messageDetails">
<script type="text/javascript">
    var MessageModel = {
        messageDetails: ko.observable(false),
        displayDetails: function() {
        hideDetails: function() {


Download the code Try the code

Take a look at the html view section first. Here we have a div which uses event binding to bind the mouseover and mouseout events with event handler functions. See how we can use event binding. Simply specify event inside the data-bind attribute, followed by opening and closing curly brackets. Inside the brackets, specify the event and the corresponding even handler separated by a colon. You can specify multiple events and event handler each pair separated by a comma. Next we in the html view we have div that uses visible binding and will be visible if the messageDetails parameters is set to true.

Now, when you hover mouse over the first div, the mouseover event fires which bound to “displayDetails” function. This function sets messageDetails parameter to true hence the it makes second div visible. Similarly, the second event mouseout calls the “hideDetails” function which sets the “messageDetails” parameter to false thus making the second div invisible

If you open the above page in browser and hover mouse over the div with yellow background you shall see a message appear under it. If you take mouse out of the yellow div,the message shall disappear.

<<< KnockoutJS Click BindingKnockoutJS Submit Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .