Sometimes you want your users to be able to get some context about a resource without actually havng to click on it and navigate away from your page. A nice way to do this is with fancy link images like this:

Hover over me! to see some image fun.

Use the data attribute.

Html elements can store ‘state’ in data attributes. In this case, a link to an image.

<a class='image-link' data-image-link='http://space-facts.com/wp-content/uploads/mars.jpg' href='http://martian.media'>Hover over me!</a>

jQuery & data attributes

jQuery lets you access and manipulate an element’s data attributes on the fly.

Drop this require module into your pipeline and then call bindImageLinks() in your app.

define(function() {
  return {
    bindImageLinks: function bindImageLinks () {
      $('a[data-image-link]').hover(function(e) {
        $(this).data('old-html', $(this).html());
        $(this).append('<div class="image-link-div"><img class="image-link-image" src="'+$(this).data('image-link')+'"/></div>');
      }, function(e){
        $('img.image-link-image').remove();
        $(this).html( $(this).data('old-html') );
      });
    }
  };
});

Positioning with CSS

We use a wrapper div around the img tag, this allows us to get around the limitation that img tags inside inline elements do not resize beyond the dimensions of their container ( in this case, the link ).

.image-link {
  position: relative;
}
.image-link-div {
  display: inline;
  width: 200px;
  position: absolute;
  top: 20px;
  left: 0px;
  background-color: white;
}

Edge detection

You could get a lot more technical with edge detection and whatnot, but for now I’m not going to worry.