Skip to content

Instantly share code, notes, and snippets.

@apcomplete
Created March 20, 2013 14:53
Show Gist options
  • Save apcomplete/5205282 to your computer and use it in GitHub Desktop.
Save apcomplete/5205282 to your computer and use it in GitHub Desktop.
jquery.hotspot, plugin for scalable overlaying of clickable hotspots on an image
(function( $ ){
var methods = {
init: function(opts){
var opts = $.extend({
scale: 1
}, opts);
return this.each(function() {
var $this = $(this)
, spots = $this.children('div.hotspot')
, image = $this.children('img')
, data = $this.data('hotspot')
;
if ( ! data) {
$this.data('hotspot', {
spots: spots,
image: image,
opts: opts
});
oImg = new Image();
oImg.onload = function(){
image.data({
width: this.width,
height: this.height
});
methods.bindClicks.apply($this);
methods.rescale.apply($this);
};
oImg.src = image.attr('src');
$(window).resize(function(){
methods.rescale.apply($this);
});
if ($(window.location.hash)) {
var that = $(window.location.hash);
methods.changeState.apply(that);
}
}
});
}
, bindClicks: function() {
var spots = $(this).data('hotspot').spots
;
spots.each(function(index, s){
$('a:first',s).click(function(e){
e.preventDefault();
methods.changeState.apply(s);
});
});
}
, changeState: function(){
var $this = $(this)
, infoBox = $('.info-box',this)
;
$('.info-box').not(infoBox).fadeOut('fast');
$('.hotspot').not($this).removeClass('active');
infoBox.fadeToggle('fast');
$this.toggleClass('active');
}
// --------------------------------------------------------------------
, rescale: function(){
var $this = $(this)
, data = $this.data('hotspot')
, curWidth = data.image.width()
, oWidth = data.image.data('width')
;
data.opts.scale = curWidth / oWidth;
$this.hotspot('position');
}
// --------------------------------------------------------------------
, position: function(){
var $this = $(this)
, data = $this.data('hotspot')
;
// position elements in DOM
data.spots.each(function(idx,spot){
var s = $(spot)
, link = $('a:first',$(this))
, scale = data.opts.scale
, xOffset = parseInt(link.css('width'),10)/2
, yOffset = parseInt(link.css('height'),10)/2
, x = scale * s.data('xpos') - xOffset
, y = scale * s.data('ypos') - yOffset
s.css({
'top': y,
'left': x
});
});
}
};
// --------------------------------------------------------------------
$.fn.hotspot = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
}
else {
$.error( 'Method ' + method + ' does not exist on jQuery.hotspot' );
}
};
// --------------------------------------------------------------------
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment