-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.convertToBackground.js
86 lines (80 loc) · 2.55 KB
/
jquery.convertToBackground.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
/**
* Convert To Background
*
* Version: 1.1.0
* Author: Zeshan Ahmed
* Website: https://zeshanahmed.com/
* Github: https://github.com/zeshanshani/jquery-convert-to-background/
*/
(function($){
$.fn.convertToBackground = function( options ) {
// Settings.
var settings = $.extend({
repeat: 'no-repeat',
position: 'center center',
size: 'cover',
attachment: '',
fallbackSrc: '',
width: '',
height: '',
responsive: false
}, options);
var $els = $(this);
$els.each(function(i, el) {
var $thisEl = $(this),
$firstImage = $thisEl.find('img').eq(0),
firstImageSrc = $firstImage.attr('src'),
isResponsive = ( settings.responsive === true ? true : false ),
width = settings.width,
maxWidth = ( width ? '100%' : '' ),
height = settings.height,
$responsiveImg = $('<div></div>'),
paddingBottom = '';
if ( isResponsive && width & height ) {
$thisEl.append( $responsiveImg );
height = 0;
paddingBottom = ( ( settings.height * 100 ) / settings.width ) + '%';
}
if ( isResponsive && $thisEl.find( $responsiveImg ) ) {
// Add the image as background to the targeted element.
$responsiveImg.css({
backgroundRepeat: settings.repeat,
backgroundPosition: settings.position,
backgroundSize: settings.size,
backgroundAttachment: settings.attachment,
backgroundImage: 'url(' + ( firstImageSrc ? firstImageSrc : settings.fallbackSrc ) + ')',
height: height,
width: '100%',
paddingBottom: paddingBottom
});
} else {
// Add the image as background to the targeted element.
$thisEl.css({
backgroundRepeat: settings.repeat,
backgroundPosition: settings.position,
backgroundSize: settings.size,
backgroundAttachment: settings.attachment,
backgroundImage: 'url(' + ( firstImageSrc ? firstImageSrc : settings.fallbackSrc ) + ')',
height: height,
paddingBottom: paddingBottom
});
}
// Add the image as background to the targeted element.
$thisEl.css({
width: width,
maxWidth: maxWidth,
});
// Visually hide the image.
$firstImage.css({
position: 'absolute',
width: '1px',
height: '1px',
padding: '0',
overflow: 'hidden',
clip: 'rect(0,0,0,0)',
whiteSpace: 'nowrap',
border: '0',
});
});
}
}( jQuery ));