-
Notifications
You must be signed in to change notification settings - Fork 0
/
highlightable.js
82 lines (71 loc) · 2.24 KB
/
highlightable.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
/*global jQuery:false */
/*!
* Highlightable v0.0.1
* https://github.com/sunliwen/highlightable
*
* Copyright 2013 Sun Liwen
* Released under the MIT license
*/
(function($) {
'use strict';
$.fn.highlightable = function() {
var $elem = $(this);
// class name of the highlightable wrapper
var jsHighlightable = "js-highlightable";
var jsHighlighted = "js-highlighted";
var jsHovered = "js-hovered";
var reg = /\b(\w+)\b/g;
var wrapper = "<span class='" + jsHighlightable + "'>$1</span>";
var color = "rgb(255, 242, 168)"; // yellow
var clickColor = "rgb(168, 209, 255)"; // blue
this.each(function(){
var $self = $(this);
$self.html($self.text().replace(reg, wrapper));
});
$('.' + jsHighlightable, $elem).hover(
function () {
var $self = $(this);
if($self.css('background-color') != clickColor){
$self.css('background-color', color);
}
},
function () {
var $self = $(this);
if($self.css('background-color') === color){
$self.css('background-color', '');
}
}
);
$('.' + jsHighlightable, $elem).click(
function () {
var $self = $(this);
// if click an element already highlighted, de-highlight it
if($self.hasClass(jsHighlighted)) {
$self.css('background-color', '');
$self.removeClass(jsHighlighted);
} else {
var highlighteds = $("." + jsHighlighted);
var prev = $($self.prev()[0]);
var next = $($self.next()[0]);
if(next.text() != $(highlighteds[0]).text() && prev.text() != $(highlighteds[highlighteds.length-1]).text()){
highlighteds.each(function() {
$(this).css('background-color', '');
$(this).removeClass(jsHighlighted);
});
}
$self.css('background-color', clickColor);
$self.addClass(jsHighlighted);
}
// send highlighted event
var event = $.Event("highlighted");
var words = [];
$("." + jsHighlighted, $elem).each(function() {
words.push($(this).text());
})
event.words = words;
$elem.trigger(event);
}
);
return this;
};
})(jQuery);