This repository has been archived by the owner on Mar 31, 2021. It is now read-only.
forked from stowball/jQuery-rwdImageMaps
/
jquery.rwdImageMaps.js
110 lines (99 loc) · 3 KB
/
jquery.rwdImageMaps.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* rwdImageMaps jQuery plugin v1.5
*
* Allows image maps to be used in a responsive design by recalculating the area coordinates to match the actual image size on load and window.resize
*
* Copyright (c) 2013 Matt Stow
* https://github.com/stowball/jQuery-rwdImageMaps
* http://mattstow.com
* Licensed under the MIT license
* Usage:
* Without debounce
* $('img[usemap]').rwdImageMaps();
*
* Disable.
* $('img[usemap]').rwdImageMaps('off');
*
* With debounce on at 500ms
* $('img[usemap]').rwdImageMaps({
* debounce: true,
* timeout: 500
* });
*/
;(function($) {
$.fn.rwdImageMaps = function(options) {
var $img = this,
defaults = {
debounce: false,
timeout: 300
},
// If options is an object, overwrite defaults with options.
opts = $.extend(defaults, typeof options === 'object' ? options : {}),
action;
// If options is a string, use it as the action.
if (typeof options === 'string') {
action = options;
}
var rwdImageMap = function() {
$img.each(function() {
if (typeof($(this).attr('usemap')) == 'undefined')
return;
var that = this,
$that = $(that);
// Since WebKit doesn't know the height until after the image has loaded, perform everything in an onload copy
$('<img />').load(function() {
var attrW = 'width',
attrH = 'height',
w = $that.attr(attrW),
h = $that.attr(attrH);
if (!w || !h) {
var temp = new Image();
temp.src = $that.attr('src');
if (!w)
w = temp.width;
if (!h)
h = temp.height;
}
var wPercent = $that.width()/100,
hPercent = $that.height()/100,
map = $that.attr('usemap').replace('#', ''),
c = 'coords';
$('map[name="' + map + '"]').find('area').each(function() {
var $this = $(this);
if (!$this.data(c))
$this.data(c, $this.attr(c));
var coords = $this.data(c).split(','),
coordsPercent = new Array(coords.length);
for (var i = 0; i < coordsPercent.length; ++i) {
if (i % 2 === 0)
coordsPercent[i] = parseInt(((coords[i]/w)*100)*wPercent);
else
coordsPercent[i] = parseInt(((coords[i]/h)*100)*hPercent);
}
$this.attr(c, coordsPercent.toString());
});
}).attr('src', $that.attr('src'));
});
};
var debounce = function (fun, mil) {
var timer;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
fun();
}, mil);
};
};
if (action === 'off') {
$img.off('resize.rwdImageMaps');
} else {
rwdImageMap();
if (opts.debounce) {
$(window).on('resize.rwdImageMaps', debounce(rwdImageMap, opts.timeout));
} else {
$(window).on('resize.rwdImageMaps', rwdImageMap);
}
}
return this;
};
})(jQuery);