2 * imgAreaSelect jQuery plugin
3 * version 0.9.10-monkey
5 * Copyright (c) 2008-2013 Michal Wojciechowski (odyniec.net)
7 * Dual licensed under the MIT (MIT-LICENSE.txt)
8 * and GPL (GPL-LICENSE.txt) licenses.
10 * http://odyniec.net/projects/imgareaselect/
17 * Math functions will be used extensively, so it's convenient to make a few
26 * Create a new HTML div element
28 * @return A jQuery object representing the new element
35 * imgAreaSelect initialization
38 * A HTML image element to attach the plugin to
42 $.imgAreaSelect = function (img, options) {
44 /* jQuery object representing the image */
47 /* Has the image finished loading? */
56 /* Border (four divs) */
57 $border = div().add(div()).add(div()).add(div()),
58 /* Outer area (four divs) */
59 $outer = div().add(div()).add(div()).add(div()),
60 /* Handles (empty by default, initialized in setOptions()) */
64 * Additional element to work around a cursor problem in Opera
69 /* Image position (relative to viewport) */
72 /* Image offset (as returned by .offset()) */
73 imgOfs = { left: 0, top: 0 },
75 /* Image dimensions (as returned by .width() and .height()) */
79 * jQuery object representing the parent element that the plugin
80 * elements are appended to
84 /* Parent element offset (as returned by .offset()) */
85 parOfs = { left: 0, top: 0 },
87 /* Base z-index for plugin elements */
90 /* Plugin elements position */
91 position = 'absolute',
93 /* X/Y coordinates of the starting point for move/resize operations */
96 /* Horizontal and vertical scaling factors */
99 /* Current resize mode ("nw", "se", etc.) */
102 /* Selection area constraints */
103 minWidth, minHeight, maxWidth, maxHeight,
105 /* Aspect ratio to maintain (floating point number) */
108 /* Are the plugin elements currently displayed? */
111 /* Current selection (relative to parent element) */
114 /* Current selection (relative to scaled image) */
115 selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
117 /* Document element */
118 docElem = document.documentElement,
121 ua = navigator.userAgent,
123 /* Various helper variables used throughout the code */
124 $p, d, i, o, w, h, adjusted;
127 * Translate selection coordinates (relative to scaled image) to viewport
128 * coordinates (relative to parent element)
132 * Translate selection X to viewport X
139 return x + imgOfs.left - parOfs.left;
143 * Translate selection Y to viewport Y
150 return y + imgOfs.top - parOfs.top;
154 * Translate viewport coordinates to selection coordinates
158 * Translate viewport X to selection X
162 * @return Selection X
165 return x - imgOfs.left + parOfs.left;
169 * Translate viewport Y to selection Y
173 * @return Selection Y
176 return y - imgOfs.top + parOfs.top;
180 * Translate event coordinates (relative to document) to viewport
185 * Get event X and translate it to viewport X
191 function evX(event) {
192 return max(event.pageX || 0, touchCoords(event).x) - parOfs.left;
196 * Get event Y and translate it to viewport Y
202 function evY(event) {
203 return max(event.pageY || 0, touchCoords(event).y) - parOfs.top;
207 * Get X and Y coordinates of a touch event
211 * @return Coordinates object
213 function touchCoords(event) {
214 var oev = event.originalEvent || {};
216 if (oev.touches && oev.touches.length)
217 return { x: oev.touches[0].pageX, y: oev.touches[0].pageY };
219 return { x: 0, y: 0 };
223 * Get the current selection
226 * If set to <code>true</code>, scaling is not applied to the
228 * @return Selection object
230 function getSelection(noScale) {
231 var sx = noScale || scaleX, sy = noScale || scaleY;
233 return { x1: round(selection.x1 * sx),
234 y1: round(selection.y1 * sy),
235 x2: round(selection.x2 * sx),
236 y2: round(selection.y2 * sy),
237 width: round(selection.x2 * sx) - round(selection.x1 * sx),
238 height: round(selection.y2 * sy) - round(selection.y1 * sy) };
242 * Set the current selection
245 * X coordinate of the upper left corner of the selection area
247 * Y coordinate of the upper left corner of the selection area
249 * X coordinate of the lower right corner of the selection area
251 * Y coordinate of the lower right corner of the selection area
253 * If set to <code>true</code>, scaling is not applied to the
256 function setSelection(x1, y1, x2, y2, noScale) {
257 var sx = noScale || scaleX, sy = noScale || scaleY;
260 x1: round(x1 / sx || 0),
261 y1: round(y1 / sy || 0),
262 x2: round(x2 / sx || 0),
263 y2: round(y2 / sy || 0)
266 selection.width = selection.x2 - selection.x1;
267 selection.height = selection.y2 - selection.y1;
271 * Recalculate image and parent offsets
275 * Do not adjust if image has not yet loaded or if width is not a
276 * positive number. The latter might happen when imgAreaSelect is put
277 * on a parent element which is then hidden.
279 if (!imgLoaded || !$img.width())
283 * Get image offset. The .offset() method returns float values, so they
284 * need to be rounded.
286 imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
288 /* Get image dimensions */
289 imgWidth = $img.innerWidth();
290 imgHeight = $img.innerHeight();
292 imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
293 imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
295 /* Set minimum and maximum selection area dimensions */
296 minWidth = round(options.minWidth / scaleX) || 0;
297 minHeight = round(options.minHeight / scaleY) || 0;
298 maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth));
299 maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight));
302 * Workaround for jQuery 1.3.2 incorrect offset calculation, originally
303 * observed in Safari 3. Firefox 2 is also affected.
305 if ($().jquery == '1.3.2' && position == 'fixed' &&
306 !docElem['getBoundingClientRect'])
308 imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
309 imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
312 /* Determine parent element offset */
313 parOfs = /absolute|relative/.test($parent.css('position')) ?
314 { left: round($parent.offset().left) - $parent.scrollLeft(),
315 top: round($parent.offset().top) - $parent.scrollTop() } :
316 position == 'fixed' ?
317 { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
324 * Check if selection area is within image boundaries, adjust if
327 if (selection.x2 > imgWidth || selection.y2 > imgHeight)
332 * Update plugin elements
334 * @param resetKeyPress
335 * If set to <code>false</code>, this instance's keypress
336 * event handler is not activated
338 function update(resetKeyPress) {
339 /* If plugin elements are hidden, do nothing */
343 * Set the position and size of the container box and the selection area
346 $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
347 .add($area).width(w = selection.width).height(h = selection.height);
350 * Reset the position of selection area, borders, and handles (IE6/IE7
351 * position them incorrectly if we don't do this)
353 $area.add($border).add($handles).css({ left: 0, top: 0 });
355 /* Set border dimensions */
357 .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
358 .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
360 /* Arrange the outer area elements */
361 $($outer[0]).css({ left: left, top: top,
362 width: selection.x1, height: imgHeight });
363 $($outer[1]).css({ left: left + selection.x1, top: top,
364 width: w, height: selection.y1 });
365 $($outer[2]).css({ left: left + selection.x2, top: top,
366 width: imgWidth - selection.x2, height: imgHeight });
367 $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
368 width: w, height: imgHeight - selection.y2 });
370 w -= $handles.outerWidth();
371 h -= $handles.outerHeight();
373 /* Arrange handles */
374 switch ($handles.length) {
376 $($handles[4]).css({ left: w >> 1 });
377 $($handles[5]).css({ left: w, top: h >> 1 });
378 $($handles[6]).css({ left: w >> 1, top: h });
379 $($handles[7]).css({ top: h >> 1 });
381 $handles.slice(1,3).css({ left: w });
382 $handles.slice(2,4).css({ top: h });
385 if (resetKeyPress !== false) {
387 * Need to reset the document keypress event handler -- unbind the
390 if ($.imgAreaSelect.onKeyPress != docKeyPress)
391 $(document).unbind($.imgAreaSelect.keyPress,
392 $.imgAreaSelect.onKeyPress);
396 * Set the document keypress event handler to this instance's
397 * docKeyPress() function
399 $(document)[$.imgAreaSelect.keyPress](
400 $.imgAreaSelect.onKeyPress = docKeyPress);
404 * Internet Explorer displays 1px-wide dashed borders incorrectly by
405 * filling the spaces between dashes with white. Toggling the margin
406 * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still
407 * broken). This workaround is not perfect, as it requires setTimeout()
408 * and thus causes the border to flicker a bit, but I haven't found a
411 * Note: This only happens with CSS borders, set with the borderWidth,
412 * borderOpacity, borderColor1, and borderColor2 options (which are now
413 * deprecated). Borders created with GIF background images are fine.
415 if (msie && $border.outerWidth() - $border.innerWidth() == 2) {
416 $border.css('margin', 0);
417 setTimeout(function () { $border.css('margin', 'auto'); }, 0);
422 * Do the complete update sequence: recalculate offsets, update the
423 * elements, and set the correct values of x1, y1, x2, and y2.
425 * @param resetKeyPress
426 * If set to <code>false</code>, this instance's keypress
427 * event handler is not activated
429 function doUpdate(resetKeyPress) {
431 update(resetKeyPress);
432 x1 = viewX(selection.x1); y1 = viewY(selection.y1);
433 x2 = viewX(selection.x2); y2 = viewY(selection.y2);
437 * Hide or fade out an element (or multiple elements)
440 * A jQuery object containing the element(s) to hide/fade out
442 * Callback function to be called when fadeOut() completes
444 function hide($elem, fn) {
445 options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
449 * Selection area mousemove event handler
454 function areaMouseMove(event) {
455 var x = selX(evX(event)) - selection.x1,
456 y = selY(evY(event)) - selection.y1;
462 $box.one('mouseout', function () { adjusted = false; });
465 /* Clear the resize mode */
468 if (options.resizable) {
470 * Check if the mouse pointer is over the resize margin area and set
471 * the resize mode accordingly
473 if (y <= options.resizeMargin)
475 else if (y >= selection.height - options.resizeMargin)
477 if (x <= options.resizeMargin)
479 else if (x >= selection.width - options.resizeMargin)
483 $box.css('cursor', resize ? resize + '-resize' :
484 options.movable ? 'move' : '');
490 * Document mouseup event handler
495 function docMouseUp(event) {
496 /* Set back the default cursor */
497 $('body').css('cursor', '');
499 * If autoHide is enabled, or if the selection has zero width/height,
500 * hide the selection and the outer area
502 if (options.autoHide || selection.width * selection.height == 0)
503 hide($box.add($outer), function () { $(this).hide(); });
505 $(document).off('mousemove touchmove', selectingMouseMove);
506 $box.on('mousemove touchmove', areaMouseMove);
508 options.onSelectEnd(img, getSelection());
512 * Selection area mousedown event handler
518 function areaMouseDown(event) {
519 if (event.type == 'mousedown' && event.which != 1) return false;
522 * With mobile browsers, there is no "moving the pointer over" action,
523 * so we need to simulate one mousemove event happening prior to
524 * mousedown/touchstart.
526 areaMouseMove(event);
531 /* Resize mode is in effect */
532 $('body').css('cursor', resize + '-resize');
534 x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
535 y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
537 $(document).on('mousemove touchmove', selectingMouseMove)
538 .one('mouseup touchend', docMouseUp);
539 $box.off('mousemove touchmove', areaMouseMove);
541 else if (options.movable) {
542 startX = left + selection.x1 - evX(event);
543 startY = top + selection.y1 - evY(event);
545 $box.off('mousemove touchmove', areaMouseMove);
547 $(document).on('mousemove touchmove', movingMouseMove)
548 .one('mouseup touchend', function () {
549 options.onSelectEnd(img, getSelection());
551 $(document).off('mousemove touchmove', movingMouseMove);
552 $box.on('mousemove touchmove', areaMouseMove);
556 $img.mousedown(event);
562 * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined)
565 * If set to <code>true</code>, calculate x2 first. Otherwise,
566 * calculate y2 first.
568 function fixAspectRatio(xFirst) {
571 x2 = max(left, min(left + imgWidth,
572 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
573 y2 = round(max(top, min(top + imgHeight,
574 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
578 y2 = max(top, min(top + imgHeight,
579 y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
580 x2 = round(max(left, min(left + imgWidth,
581 x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
587 * Resize the selection area respecting the minimum/maximum dimensions and
590 function doResize() {
592 * Make sure the top left corner of the selection area stays within
593 * image boundaries (it might not if the image source was dynamically
596 x1 = min(x1, left + imgWidth);
597 y1 = min(y1, top + imgHeight);
599 if (abs(x2 - x1) < minWidth) {
600 /* Selection width is smaller than minWidth */
601 x2 = x1 - minWidth * (x2 < x1 || -1);
604 x1 = left + minWidth;
605 else if (x2 > left + imgWidth)
606 x1 = left + imgWidth - minWidth;
609 if (abs(y2 - y1) < minHeight) {
610 /* Selection height is smaller than minHeight */
611 y2 = y1 - minHeight * (y2 < y1 || -1);
614 y1 = top + minHeight;
615 else if (y2 > top + imgHeight)
616 y1 = top + imgHeight - minHeight;
619 x2 = max(left, min(x2, left + imgWidth));
620 y2 = max(top, min(y2, top + imgHeight));
622 fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
624 if (abs(x2 - x1) > maxWidth) {
625 /* Selection width is greater than maxWidth */
626 x2 = x1 - maxWidth * (x2 < x1 || -1);
630 if (abs(y2 - y1) > maxHeight) {
631 /* Selection height is greater than maxHeight */
632 y2 = y1 - maxHeight * (y2 < y1 || -1);
633 fixAspectRatio(true);
636 selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
637 y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
638 width: abs(x2 - x1), height: abs(y2 - y1) };
642 options.onSelectChange(img, getSelection());
646 * Mousemove event handler triggered when the user is selecting an area
652 function selectingMouseMove(event) {
653 x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
654 y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
662 * Move the selection area
669 function doMove(newX1, newY1) {
670 x2 = (x1 = newX1) + selection.width;
671 y2 = (y1 = newY1) + selection.height;
673 $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
678 options.onSelectChange(img, getSelection());
682 * Mousemove event handler triggered when the selection area is being moved
688 function movingMouseMove(event) {
689 x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
690 y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
694 event.preventDefault();
701 function startSelection() {
702 $(document).off('mousemove touchmove', startSelection);
711 if (!$outer.is(':visible'))
712 /* Show the plugin elements */
713 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
717 $(document).off('mouseup touchend', cancelSelection)
718 .on('mousemove touchmove', selectingMouseMove)
719 .one('mouseup touchend', docMouseUp);
720 $box.off('mousemove touchmove', areaMouseMove);
722 options.onSelectStart(img, getSelection());
728 function cancelSelection() {
729 $(document).off('mousemove touchmove', startSelection)
730 .off('mouseup touchend', cancelSelection);
731 hide($box.add($outer));
733 setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
735 /* If this is an API call, callback functions should not be triggered */
736 if (!(this instanceof $.imgAreaSelect)) {
737 options.onSelectChange(img, getSelection());
738 options.onSelectEnd(img, getSelection());
743 * Image mousedown event handler
749 function imgMouseDown(event) {
750 /* Ignore the event if animation is in progress */
751 if (event.which != 1 || $outer.is(':animated')) return false;
754 startX = x1 = evX(event);
755 startY = y1 = evY(event);
757 /* Selection will start when the mouse is moved */
758 $(document).on({ 'mousemove touchmove': startSelection,
759 'mouseup touchend': cancelSelection });
765 * Window resize event handler
767 function windowResize() {
772 * Image load event handler. This is the final part of the initialization
779 setOptions(options = $.extend({
780 classPrefix: 'imgareaselect',
785 onInit: function () {},
786 onSelectStart: function () {},
787 onSelectChange: function () {},
788 onSelectEnd: function () {}
791 $box.add($outer).css({ visibility: '' });
797 $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
801 * Call the onInit callback. The setTimeout() call is used to ensure
802 * that the plugin has been fully initialized and the object instance is
803 * available (so that it can be obtained in the callback).
805 setTimeout(function () { options.onInit(img, getSelection()); }, 0);
809 * Document keypress event handler
815 var docKeyPress = function(event) {
816 var k = options.keys, d, t, key = event.keyCode;
818 d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
819 !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
820 !isNaN(k.shift) && event.shiftKey ? k.shift :
821 !isNaN(k.arrows) ? k.arrows : 10;
823 if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
824 (k.ctrl == 'resize' && event.ctrlKey) ||
825 (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
827 /* Resize selection */
848 fixAspectRatio(true);
865 doMove(max(x1 - d, left), y1);
869 doMove(x1, max(y1 - d, top));
873 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
877 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
888 * Apply style options to plugin element (or multiple elements)
891 * A jQuery object representing the element(s) to style
893 * An object that maps option names to corresponding CSS
896 function styleOptions($elem, props) {
897 for (var option in props)
898 if (options[option] !== undefined)
899 $elem.css(props[option], options[option]);
906 * The new options object
908 function setOptions(newOptions) {
909 if (newOptions.parent)
910 ($parent = $(newOptions.parent)).append($box.add($outer));
912 /* Merge the new options with the existing ones */
913 $.extend(options, newOptions);
917 if (newOptions.handles != null) {
918 /* Recreate selection area handles */
922 i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
925 $handles = $handles.add(div());
927 /* Add a class to handles and set the CSS properties */
928 $handles.addClass(options.classPrefix + '-handle').css({
929 position: 'absolute',
931 * The font-size property needs to be set to zero, otherwise
932 * Internet Explorer makes the handles too large
935 zIndex: zIndex + 1 || 1
939 * If handle width/height has not been set with CSS rules, set the
942 if (!parseInt($handles.css('width')) >= 0)
943 $handles.width(5).height(5);
946 * If the borderWidth option is in use, add a solid border to
949 if (o = options.borderWidth)
950 $handles.css({ borderWidth: o, borderStyle: 'solid' });
952 /* Apply other style options */
953 styleOptions($handles, { borderColor1: 'border-color',
954 borderColor2: 'background-color',
955 borderOpacity: 'opacity' });
958 /* Calculate scale factors */
959 scaleX = options.imageWidth / imgWidth || 1;
960 scaleY = options.imageHeight / imgHeight || 1;
963 if (newOptions.x1 != null) {
964 setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
966 newOptions.show = !newOptions.hide;
970 /* Enable keyboard support */
971 options.keys = $.extend({ shift: 1, ctrl: 'resize' },
974 /* Add classes to plugin elements */
975 $outer.addClass(options.classPrefix + '-outer');
976 $area.addClass(options.classPrefix + '-selection');
977 for (i = 0; i++ < 4;)
978 $($border[i-1]).addClass(options.classPrefix + '-border' + i);
980 /* Apply style options */
981 styleOptions($area, { selectionColor: 'background-color',
982 selectionOpacity: 'opacity' });
983 styleOptions($border, { borderOpacity: 'opacity',
984 borderWidth: 'border-width' });
985 styleOptions($outer, { outerColor: 'background-color',
986 outerOpacity: 'opacity' });
987 if (o = options.borderColor1)
988 $($border[0]).css({ borderStyle: 'solid', borderColor: o });
989 if (o = options.borderColor2)
990 $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
992 /* Append all the selection area elements to the container box */
993 $box.append($area.add($border).add($areaOpera)).append($handles);
996 if (o = ($outer.css('filter')||'').match(/opacity=(\d+)/))
997 $outer.css('opacity', o[1]/100);
998 if (o = ($border.css('filter')||'').match(/opacity=(\d+)/))
999 $border.css('opacity', o[1]/100);
1002 if (newOptions.hide)
1003 hide($box.add($outer));
1004 else if (newOptions.show && imgLoaded) {
1006 $box.add($outer).fadeIn(options.fadeSpeed||0);
1010 /* Calculate the aspect ratio factor */
1011 aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
1013 $img.add($outer).unbind('mousedown', imgMouseDown);
1015 if (options.disable || options.enable === false) {
1016 /* Disable the plugin */
1017 $box.off({ 'mousemove touchmove': areaMouseMove,
1018 'mousedown touchstart': areaMouseDown });
1019 $(window).off('resize', windowResize);
1022 if (options.enable || options.disable === false) {
1023 /* Enable the plugin */
1024 if (options.resizable || options.movable)
1025 $box.on({ 'mousemove touchmove': areaMouseMove,
1026 'mousedown touchstart': areaMouseDown });
1028 $(window).resize(windowResize);
1031 if (!options.persistent)
1032 $img.add($outer).on('mousedown touchstart', imgMouseDown);
1035 options.enable = options.disable = undefined;
1039 * Remove plugin completely
1041 this.remove = function () {
1043 * Call setOptions with { disable: true } to unbind the event handlers
1045 setOptions({ disable: true });
1046 $box.add($outer).remove();
1054 * Get current options
1056 * @return An object containing the set of options currently in use
1058 this.getOptions = function () { return options; };
1061 * Set plugin options
1064 * The new options object
1066 this.setOptions = setOptions;
1069 * Get the current selection
1072 * If set to <code>true</code>, scaling is not applied to the
1073 * returned selection
1074 * @return Selection object
1076 this.getSelection = getSelection;
1079 * Set the current selection
1082 * X coordinate of the upper left corner of the selection area
1084 * Y coordinate of the upper left corner of the selection area
1086 * X coordinate of the lower right corner of the selection area
1088 * Y coordinate of the lower right corner of the selection area
1090 * If set to <code>true</code>, scaling is not applied to the
1093 this.setSelection = setSelection;
1098 this.cancelSelection = cancelSelection;
1101 * Update plugin elements
1103 * @param resetKeyPress
1104 * If set to <code>false</code>, this instance's keypress
1105 * event handler is not activated
1107 this.update = doUpdate;
1109 /* Do the dreaded browser detection */
1110 var msie = (/msie ([\w.]+)/i.exec(ua)||[])[1],
1111 opera = /opera/i.test(ua),
1112 safari = /webkit/i.test(ua) && !/chrome/i.test(ua);
1115 * Traverse the image's parent elements (up to <body>) and find the
1121 zIndex = max(zIndex,
1122 !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
1123 /* Also check if any of the ancestor elements has fixed position */
1124 if ($p.css('position') == 'fixed')
1127 $p = $p.parent(':not(body)');
1131 * If z-index is given as an option, it overrides the one found by the
1134 zIndex = options.zIndex || zIndex;
1137 $img.attr('unselectable', 'on');
1140 * In MSIE and WebKit, we need to use the keydown event instead of keypress
1142 $.imgAreaSelect.keyPress = msie || safari ? 'keydown' : 'keypress';
1145 * There is a bug affecting the CSS cursor property in Opera (observed in
1146 * versions up to 10.00) that prevents the cursor from being updated unless
1147 * the mouse leaves and enters the element again. To trigger the mouseover
1148 * event, we're adding an additional div to $box and we're going to toggle
1149 * it when mouse moves inside the selection area.
1152 $areaOpera = div().css({ width: '100%', height: '100%',
1153 position: 'absolute', zIndex: zIndex + 2 || 2 });
1156 * We initially set visibility to "hidden" as a workaround for a weird
1157 * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally
1158 * we would just set display to "none", but, for some reason, if we do so
1159 * then Chrome refuses to later display the element with .show() or
1162 $box.add($outer).css({ visibility: 'hidden', position: position,
1163 overflow: 'hidden', zIndex: zIndex || '0' });
1164 $box.css({ zIndex: zIndex + 2 || 2 });
1165 $area.add($border).css({ position: 'absolute', fontSize: 0 });
1168 * If the image has been fully loaded, or if it is not really an image (eg.
1169 * a div), call imgLoad() immediately; otherwise, bind it to be called once
1170 * on image load event.
1172 img.complete || img.readyState == 'complete' || !$img.is('img') ?
1173 imgLoad() : $img.one('load', imgLoad);
1176 * MSIE 9.0 doesn't always fire the image load event -- resetting the src
1177 * attribute seems to trigger it. The check is for version 7 and above to
1178 * accommodate for MSIE 9 running in compatibility mode.
1180 if (!imgLoaded && msie && msie >= 7)
1185 * Invoke imgAreaSelect on a jQuery object containing the image(s)
1189 * @return The jQuery object or a reference to imgAreaSelect instance (if the
1190 * <code>instance</code> option was specified)
1192 $.fn.imgAreaSelect = function (options) {
1193 options = options || {};
1195 this.each(function () {
1196 /* Is there already an imgAreaSelect instance bound to this element? */
1197 if ($(this).data('imgAreaSelect')) {
1198 /* Yes there is -- is it supposed to be removed? */
1199 if (options.remove) {
1200 /* Remove the plugin */
1201 $(this).data('imgAreaSelect').remove();
1202 $(this).removeData('imgAreaSelect');
1206 $(this).data('imgAreaSelect').setOptions(options);
1208 else if (!options.remove) {
1209 /* No exising instance -- create a new one */
1212 * If neither the "enable" nor the "disable" option is present, add
1213 * "enable" as the default
1215 if (options.enable === undefined && options.disable === undefined)
1216 options.enable = true;
1218 $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
1222 if (options.instance)
1224 * Return the imgAreaSelect instance bound to the first element in the
1227 return $(this).data('imgAreaSelect');