-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.min-line-height.coffee
68 lines (59 loc) · 2.45 KB
/
jquery.min-line-height.coffee
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
# Min-line-height:
# ===============================================================================
# Created in response to Tim Brown's article Molten Leading
# (http://nicewebtype.com/notes/2012/02/03/molten-leading-or-fluid-line-height/)
#
# Script written by J. Jeffers - for latest please visit repository on github
# (https://github.com/jimjeffers/jQuery-minLineHeight)
#
# Usage:
# ===============================================================================
# Select applicable elements with jQuery and pass an amount:
# $("#content p").minLineHeight(1.3)
#
# The minimum line height can be supplied in the following ways:
# $("#content p").minLineHeight(1.3)
# $("#content p").minLineHeight("1.3rem")
# $("#content p").minLineHeight("13px")
#
# If the amount is passed as a float or any units other than px
# then the script will default to ems.
jQuery.fn.minLineHeight = (amount) ->
# Help parse values from various units.
parseUnits = (value) ->
value: parseFloat value.replace(/[a-zA-Z]/g,"")
units: value.replace(/[^a-zA-Z]/g,"")
# Calculates the line height for a
calculateLineHeight = (element) ->
# Properties
width = element.width()
maxWidth = parseUnits element.css("max-width")
minWidth = parseUnits element.css("min-width")
maxLineHeight = parseUnits element.data("max-line-height")
fontSize = parseUnits element.css("font-size")
# Get proper min line height.
if minLineHeight.units != "px"
minLineHeightPx = minLineHeight.value*fontSize.value
else
minLineHeightPx = minLineHeight.value
# Calculations
widthRange = maxWidth.value - minWidth.value
currentWidthDiff = element.width() - minWidth.value
widthRatio = currentWidthDiff / widthRange
lineHeightRange = maxLineHeight.value - minLineHeightPx
currentLineHeight = minLineHeightPx + lineHeightRange * widthRatio
# Set line height
element.css("line-height","#{currentLineHeight}px")
element
# Set min-line-height
minLineHeight = parseUnits "#{amount}"
# Initial array for applicable elements.
elements = []
@each ->
el = $(this)
if el.css("max-width") != "none" and el.css("min-width") != "none" and el.css("line-height") != "none"
el.attr("data-max-line-height",el.css("line-height"))
elements.push calculateLineHeight el
$(window).resize =>
for element in elements
calculateLineHeight element