Web Development

KnockoutJS’s event binding is awesome.

Markup

<div class='image-holder' data-bind="event: { mouseover: enableDetails, mouseout: disableDetails}">
  <img src="http://placekitten.com/g/300/300" alt="...">
  <div class='image-caption image-caption-big' data-bind="css: {'dark': imageCaption}">Some Text</div>
</div>

Javascript

function HoverModel() {
    var self = this;
    self.imageCaption = ko.observable(false);
    self.enableDetails = function() {
       self.imageCaption(true);
    }
    self.disableDetails = function() {
       self.imageCaption(false);
    }
}
ko.applyBindings(new HoverModel());

make observable

One of the first things to do is to make things observable .

 self.imageCaption = ko.observable(false);

This tells KnockOut that the class, dark shouldn’t be applied yet. It is false .

Apply bindings

enableDetails and disableDetails will run whenever a mouseover and mouseout event is registered, respectively.

<div class='image-holder' data-bind="event: { mouseover: enableDetails, mouseout: disableDetails}">
  <img src="http://placekitten.com/g/300/300" alt="...">
  <div class='image-caption image-caption-big' data-bind="css: {'dark': imageCaption}">Some Text</div>
</div>

Javascript

enableDetails now updates our observable , imageCaption to true. This will apply the class to the div is was bound

disableDetails now updates our observable , imageCaption to false. This will apply the class to the div is was bound

self.enableDetails = function() {
   self.imageCaption(true);
}
self.disableDetails = function() {
   self.imageCaption(false);
}

Try It!

Try this out on JSFiddle