-
Notifications
You must be signed in to change notification settings - Fork 2
/
jquery.body-class-swap.js
66 lines (53 loc) · 1.87 KB
/
jquery.body-class-swap.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
// body-class-swap v .01 for jQuery 1.3
// c) 2010 Alex Welch - www.alexwelch.com - me@alexwelch.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function($) {
String.prototype.toLink = function() {
return this.toLowerCase().replace(/ /g,'-').replace(/\./g, '_').replace(/#/g, '');
};
function getTargetClasses(container) {
return $.map($(container), function(a) { return $(a).attr('href').toLink() })
};
$.fn.switchClass = function(container, body_class, target) {
$container = $(this);
var current_class = 'current';
var body_classes = getTargetClasses($(container).find('a')).join(' ');
container.find('a').removeClass(current_class);
target.addClass(current_class);
$container.removeClass(body_classes);
$container.addClass(body_class);
};
$.fn.classSwapper = function(options) {
settings = $.extend({
target_container: 'body'
}, options);
$links_container = $(this);
$target_container = $(settings.target_container);
// check for body_class cookie
if($.cookie) {
cookie_name = $links_container.attr('id');
var body_class = $.cookie(cookie_name);
if(body_class) {
var body_class = body_class
target = $links_container.find('a[href~="#' + body_class + '"]');
var $target = $(target)
$target_container.switchClass($links_container, body_class, $target);
}
}
$links_container.click(function(e) {
var target = e.target
var $target = $(target);
//fixme: do this a better way
var $parent = $target.closest('div');
if(target.nodeName === 'A') {
var body_class = $target.attr('href').toLink();
$target_container.switchClass($parent, body_class, $target);
if($.cookie) {
var cookie_name = $parent.attr('id');
$.cookie(cookie_name, body_class);
}
return false;
}
});
};
}(jQuery));