Sunday, June 5, 2016

Change Image Source on Hover using Knockout JS

I found this js fiddle for how to do it using jQuery so I converted it to use a Knockout binding.  Surprisingly, the first page of google didn't have any KO binding to do it.

ko.bindingHandlers.hoverImage = {
  init: function(element, valueAccessor) {
    var options = ko.utils.unwrapObservable(valueAccessor());
    $(element).bind('mouseover', function(event) {
      var $this = $(this);
      if (!$this.data('original-image')) {
          $this.data('original-image', $this.attr('src'));
      }
      $this.attr('src', options);
    })
    .bind('mouseout', function(event) {
       var $this = $(this);
       $this.attr('src', $this.data('original-image'));
    });
  }
};
To use it,
<img src="initialImageSrc.jpg" data-bind="hoverImage: 'hoverImageSrc.jpg'>

No comments:

Post a Comment