-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.elemedia.js
65 lines (43 loc) · 1.75 KB
/
jquery.elemedia.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
(function($, window, undefined){
$.fn.extend({
//plugin name
elemedia: function(mediaQuery, threshold) {
/* REQUIRED ARGUMENTS
/*------------------------------------------------------------------------------------------------//
mediaQuery: [str] 'min-width': apply class when element is >= threshold
'max-width': apply class when element is <= threshold
threshold: [int] Width in pixels that will add/remove custom class name
*/
return this.each(function() {
var $this = $(this);
var className = 'mq-' + mediaQuery + '-' + threshold;
var checkWidth = function() {
// min-width behavior
//----------------------------------------------------------------------------------//
if (mediaQuery == 'min-width') {
if ($this.width() >= threshold && !$this.hasClass(className)) {
$this.addClass(className);
}
if ($this.hasClass(className) && $this.width() < threshold) {
$this.removeClass(className);
}
}
// max-width behavior
//----------------------------------------------------------------------------------//
if (mediaQuery == 'max-width') {
if ($this.width() <= threshold && !$this.hasClass(className)) {
$this.addClass(className);
}
if ($this.hasClass(className) && $this.width() > threshold) {
$this.removeClass(className);
}
}
}
// Call once to set
checkWidth();
// Call on resize.
$(window).on('resize', checkWidth);
});
}
});
})(jQuery, window);