forked from nutritionix/nutrition-label
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nutritionLabel.js
1419 lines (1207 loc) · 58 KB
/
nutritionLabel.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
******************************************************************************************************************+
* NUTRITIONIX.com |
* |
* This plugin allows you to create a fully customizable nutrition label |
* |
* @authors majin22 (js) and genesis23rd (css and html) |
* @copyright Copyright (c) 2012 Nutritionix. |
* @license This Nutritionix jQuery Nutrition Label is dual licensed under the MIT and GPL licenses. |
* @link http://www.nutritionix.com |
* @github http://github.com/nutritionix/nutrition-label |
* @current version 6.0.4 |
* @stable version 6.0.2 |
* @supported browser Firefox, Chrome, IE8+ |
* |
******************************************************************************************************************+
*/
;(function($){
$.fn.nutritionLabel = function(option, settings){
if (typeof option === 'object'){
settings = option;
init( settings, $(this) );
}else if (typeof option === 'string' && option !== ''){
//destroys the nutrition label's html code
if (option === 'destroy')
new NutritionLabel().destroy( $(this) );
//allows the user to hide the nutrition value
else if (option === 'hide')
new NutritionLabel().hide( $(this) );
//allows the user to show the nutrition value
else if (option === 'show')
new NutritionLabel().show( $(this) );
else{
var values = [];
var elements = this.each(function(){
var data = $(this).data('_nutritionLabel');
if (data){
if ($.fn.nutritionLabel.defaultSettings[option] !== undefined){
if (settings !== undefined){
//set the option and create the nutrition label
data.settings[option] = settings;
init( data.settings, $(this) );
}else
//return the value of a setting - can only be used after the label is created / initiated
values.push(data.settings[option]);
}
}else if ($.fn.nutritionLabel.defaultSettings[option] !== undefined)
//set the option and create the nutrition label
//this is a special case so the single value setting will still work even if the label hasn't been initiated yet
if (settings !== undefined){
$.fn.nutritionLabel.defaultSettings[option] = settings;
init( null, $(this) );
}
});
//return the value of a setting
if (values.length === 1)
return values[0];
//return the setting values or the elements
return values.length > 0 ? values : elements;
}
}else if (typeof option === 'undefined' || option === '')
//if no value / option is supplied, simply create the label using the default values
init( settings, $(this) );
};
$.fn.nutritionLabel.defaultSettings = {
//default fixedWidth of the nutrition label
width : 260,
//to allow custom width - usually needed for mobile sites
allowCustomWidth : false,
widthCustom : 'auto',
//to allow the label to have no border
allowNoBorder : false,
//to enable rounding of the nutritional values based on the FDA rounding rules
//http://goo.gl/RMD2O
allowFDARounding : false,
//when set to true, this will hide the values if they are not applicable
hideNotAppicableValues : false,
//the brand name of the item for this label (eg. just salad)
brandName : 'Brand where this item belongs to',
//to scroll the ingredients if the innerheight is > scrollHeightComparison
scrollLongIngredients : false,
scrollHeightComparison : 100,
//the height in px of the ingredients div
scrollHeightPixel : 95,
//this is to set how many decimal places will be shown on the nutrition values (calories, fat, protein, vitamin a, iron, etc)
decimalPlacesForNutrition : 1,
//this is to set how many decimal places will be shown for the "% daily values*"
decimalPlacesForDailyValues : 0,
//this is to set how many decimal places will be shown for the serving unit quantity textbox
decimalPlacesForQuantityTextbox : 1,
//to scroll the item name if the jQuery.height() is > scrollLongItemNamePixel
scrollLongItemName : true,
scrollLongItemNamePixel : 36,
//show the customizable link at the bottom
showBottomLink : false,
//url for the customizable link at the bottom
urlBottomLink : 'http://www.nutritionix.com',
//link name for the customizable link at the bottom
nameBottomLink : 'Nutritionix',
//this value can be changed and the value of the nutritions will be affected directly
//the computation is "current nutrition value" * "serving unit quantity value" = "final nutrition value"
//this can't be less than zero, all values less than zero is converted to zero
//the textbox to change this value is visible / enabled by default
//if the initial value of the serving size unit quantity is less than or equal to zero, it is converted to 1.0
//when enabled, user can change this value by clicking the arrow or changing the value on the textbox and
//pressing enter. the value on the label will be updated automatically
//different scenarios and the result if this feature is enabled
//NOTE 1: [ ] => means a textbox will be shown
//NOTE 2: on all cases below showServingUnitQuantityTextbox == true AND showServingUnitQuantity == true
//if showServingUnitQuantity == false, the values that should be on the 'serving size div' are empty or null
//CASE 1a: valueServingSizeUnit != '' (AND NOT null) && valueServingUnitQuantity >= 0
//RESULT: textServingSize [valueServingUnitQuantity] valueServingSizeUnit
//NOTE 3: on all cases below showServingUnitQuantityTextbox == true AND showItemName == true
//if showItemName == false, the values that should be on the 'item name div' are empty or null
//CASE 1b: valueServingSizeUnit != '' (AND NOT null) && valueServingUnitQuantity <= 0
//RESULT: [valueServingUnitQuantity default to 1.0] itemName
//CASE 3a: valueServingSizeUnit == '' (OR null) && valueServingUnitQuantity > 0
//RESULT: [valueServingUnitQuantity] itemName
//CASE 3b: valueServingSizeUnit == '' (OR null) && valueServingUnitQuantity <= 0
//RESULT: [valueServingUnitQuantity default to 1.0] itemName
//NOTE 4: to see the different resulting labels, check the html/demo-texbox-case*.html files
valueServingUnitQuantity : 1.0,
valueServingSizeUnit : '',
showServingUnitQuantityTextbox : true,
//the name of the item for this label (eg. cheese burger or mayonnaise)
itemName : 'Item / Ingredient Name',
showServingUnitQuantity : true,
//allow hiding of the textbox arrows
hideTextboxArrows : false,
//these 2 settings are used internally.
//this is just added here instead of a global variable to prevent a bug when there are multiple instances of the plugin like on the demo pages
originalServingUnitQuantity : 0,
//this is used to fix the computation issue on the textbox
nutritionValueMultiplier : 1,
//this is used for the computation of the servings per container
totalContainerQuantity : 1,
//default calorie intake
calorieIntake : 2000,
//these are the recommended daily intake values
dailyValueTotalFat : 65,
dailyValueSatFat : 20,
dailyValueCholesterol : 300,
dailyValueSodium : 2400,
dailyValueCarb : 300,
dailyValueFiber : 25,
//these values can be change to hide some nutrition values
showCalories : true,
showFatCalories : true,
showTotalFat : true,
showSatFat : true,
showTransFat : true,
showPolyFat : true,
showMonoFat : true,
showCholesterol : true,
showSodium : true,
showTotalCarb : true,
showFibers : true,
showSugars : true,
showProteins : true,
showVitaminA : true,
showVitaminC : true,
showCalcium : true,
showIron : true,
//to show the 'amount per serving' text
showAmountPerServing : true,
//to show the 'servings per container' data and replace the default 'Serving Size' value (without unit and servings per container text and value)
showServingsPerContainer : false,
//to show the item name. there are special cases where the item name is replaced with 'servings per container' value
showItemName : true,
//show the brand where this item belongs to
showBrandName : false,
//to show the ingredients value or not
showIngredients : true,
//to show the calorie diet info at the bottom of the label
showCalorieDiet : false,
//to show the customizable footer which can contain html and js codes
showCustomFooter : false,
//to show the disclaimer text or not
showDisclaimer : false,
//the height in px of the disclaimer div
scrollDisclaimerHeightComparison : 100,
scrollDisclaimer : 95,
valueDisclaimer : 'Please note that these nutrition values are estimated based on our standard serving portions. As food servings may have a slight variance each time you visit, please expect these values to be with in 10% +/- of your actual meal. If you have any questions about our nutrition calculator, please contact Nutritionix.', ingredientLabel : 'INGREDIENTS:',
valueCustomFooter : '',
//the are to set some values as 'not applicable'. this means that the nutrition label will appear but the value will be a 'gray dash'
naCalories : false,
naFatCalories : false,
naTotalFat : false,
naSatFat : false,
naTransFat : false,
naPolyFat : false,
naMonoFat : false,
naCholesterol : false,
naSodium : false,
naTotalCarb : false,
naFibers : false,
naSugars : false,
naProteins : false,
naVitaminA : false,
naVitaminC : false,
naCalcium : false,
naIron : false,
//these are the default values for the nutrition info
valueServingWeightGrams : 0,
valueServingPerContainer : 1,
valueCalories : 0,
valueFatCalories : 0,
valueTotalFat : 0,
valueSatFat : 0,
valueTransFat : 0,
valuePolyFat : 0,
valueMonoFat : 0,
valueCholesterol : 0,
valueSodium : 0,
valueTotalCarb : 0,
valueFibers : 0,
valueSugars : 0,
valueProteins : 0,
valueVitaminA : 0,
valueVitaminC : 0,
valueCalcium : 0,
valueIron : 0,
//customizable units for the values
unitCalories : '',
unitFatCalories : '',
unitTotalFat : 'g',
unitSatFat : 'g',
unitTransFat : 'g',
unitPolyFat : 'g',
unitMonoFat : 'g',
unitCholesterol : 'mg',
unitSodium : 'mg',
unitTotalCarb : 'g',
unitFibers : 'g',
unitSugars : 'g',
unitProteins : 'g',
unitVitaminA : '%',
unitVitaminC : '%',
unitCalcium : '%',
unitIron : '%',
//these are the values for the optional calorie diet
valueCol1CalorieDiet : 2000,
valueCol2CalorieDiet : 2500,
valueCol1DietaryTotalFat : 0,
valueCol2DietaryTotalFat : 0,
valueCol1DietarySatFat : 0,
valueCol2DietarySatFat : 0,
valueCol1DietaryCholesterol : 0,
valueCol2DietaryCholesterol : 0,
valueCol1DietarySodium : 0,
valueCol2DietarySodium : 0,
valueCol1DietaryTotalCarb : 0,
valueCol2DietaryTotalCarb : 0,
valueCol1Dietary : 0,
valueCol2Dietary : 0,
//these text settings is so you can create nutrition labels in different languages or to simply change them to your need
textNutritionFacts : 'Nutrition Facts',
textDailyValues : 'Daily Value',
textServingSize : 'Serving Size:',
textServingsPerContainer : 'Servings Per Container',
textAmountPerServing : 'Amount Per Serving',
textCalories : 'Calories',
textFatCalories : 'Calories from Fat',
textTotalFat : 'Total Fat',
textSatFat : 'Saturated Fat',
textTransFat : '<i>Trans</i> Fat',
textPolyFat : 'Polyunsaturated Fat',
textMonoFat : 'Monounsaturated Fat',
textCholesterol : 'Cholesterol',
textSodium : 'Sodium',
textTotalCarb : 'Total Carbohydrates',
textFibers : 'Dietary Fiber',
textSugars : 'Sugars',
textProteins : 'Protein',
textVitaminA : 'Vitamin A',
textVitaminC : 'Vitamin C',
textCalcium : 'Calcium',
textIron : 'Iron',
ingredientList : 'None',
textPercentDailyPart1 : 'Percent Daily Values are based on a',
textPercentDailyPart2 : 'calorie diet'
};
//this will store the unique individual properties for each instance of the plugin
function NutritionLabel(settings, $elem){
this.nutritionLabel = null;
this.settings = settings;
this.$elem = $elem;
return this;
}
function cleanSettings(settings){
var numericIndex = [
'width','scrollHeightComparison','scrollHeightPixel','decimalPlacesForNutrition','decimalPlacesForDailyValues',
'calorieIntake','dailyValueTotalFat','dailyValueSatFat','dailyValueCholesterol','dailyValueSodium','dailyValueCarb',
'dailyValueFiber','valueServingSize','valueServingWeightGrams','valueServingPerContainer','valueCalories',
'valueFatCalories','valueTotalFat','valueSatFat','valueTransFat','valuePolyFat','valueMonoFat','valueCholesterol',
'valueSodium','valueTotalCarb','valueFibers','valueSugars','valueProteins','valueVitaminA','valueVitaminC',
'valueCalcium','valueIron','valueCol1CalorieDiet','valueCol2CalorieDiet','valueCol1DietaryTotalFat',
'valueCol2DietaryTotalFat','valueCol1DietarySatFat','valueCol2DietarySatFat','valueCol1DietaryCholesterol',
'valueCol2DietaryCholesterol','valueCol1DietarySodium','valueCol2DietarySodium','valueCol1DietaryTotalCarb',
'valueCol2DietaryTotalCarb','valueCol1Dietary','valueCol2Dietary', 'valueServingUnitQuantity',
'scrollLongItemNamePixel, decimalPlacesForQuantityTextbox'
];
$.each(settings, function(index, value){
if (jQuery.inArray(index, numericIndex) !== -1){
settings[index] = parseFloat(settings[index]);
if (isNaN(settings[index]) || settings[index] === undefined)
settings[index] = 0;
}
});
if (settings['valueServingUnitQuantity'] < 0)
settings['valueServingUnitQuantity'] = 0;
return settings;
}
function UpdateNutritionValueWithMultiplier(settings){
var nutritionIndex = [
'valueCalories','valueFatCalories','valueTotalFat','valueSatFat','valueTransFat','valuePolyFat','valueMonoFat',
'valueCholesterol','valueSodium','valueTotalCarb','valueFibers','valueSugars','valueProteins','valueVitaminA',
'valueVitaminC','valueCalcium','valueIron'
];
$.each(settings, function(index, value){
if (jQuery.inArray(index, nutritionIndex) !== -1){
settings[index] = parseFloat(settings[index]);
if (isNaN(settings[index]) || settings[index] === undefined)
settings[index] = 0;
settings[index] = parseFloat(settings[index]) * parseFloat(settings['valueServingUnitQuantity']) * parseFloat(settings['nutritionValueMultiplier']);
}
});
if (parseFloat(settings['valueServingUnitQuantity']) == 0)
settings['valueServingPerContainer'] = 0;
else if (!isNaN(settings['valueServingPerContainer']) && settings['valueServingPerContainer'] != undefined)
settings['valueServingPerContainer'] = parseFloat(settings.totalContainerQuantity) / parseFloat(settings['valueServingUnitQuantity']);
return settings;
}
function init(settings, $elem){
//merge the default settins with the user supplied settings
var $settings = $.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} );
$settings.totalContainerQuantity = parseFloat($settings.valueServingPerContainer) * parseFloat($settings['valueServingUnitQuantity']);
var $originalCleanSettings = cleanSettings($.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} ));
$originalCleanSettings.totalContainerQuantity = parseFloat($originalCleanSettings.valueServingPerContainer) * parseFloat($originalCleanSettings['valueServingUnitQuantity']);
//clean the settings and make sure that all numeric settings are really numeric, if not, force them to be
$settings = cleanSettings($settings);
$originalCleanSettings = cleanSettings($originalCleanSettings);
$settings.nutritionValueMultiplier = $settings.valueServingUnitQuantity <= 0 ? 1 : 1 / $settings.valueServingUnitQuantity;
//update the nutrition values with the multiplier
var $updatedsettings = UpdateNutritionValueWithMultiplier($settings);
$settings.originalServingUnitQuantity = $updatedsettings.valueServingUnitQuantity;
//if the original value is <= 0, set it to 1.0
if ($updatedsettings.valueServingUnitQuantity <= 0){
$originalCleanSettings.valueServingUnitQuantity = 1;
$updatedsettings = UpdateNutritionValueWithMultiplier($originalCleanSettings);
$updatedsettings.valueServingUnitQuantity = 1;
}
//initalize the nutrition label and create / recreate it
var nutritionLabel = new NutritionLabel($updatedsettings, $elem);
$elem.html( nutritionLabel.generate() );
//scroll the ingredients of the innerheight is > $settings.scrollHeightComparison
//and the settings showIngredients and scrollLongIngredients are true
if ($settings.showIngredients && $settings.scrollLongIngredients)
updateScrollingFeature($elem, $settings);
//scroll the disclaimer if the height of the disclaimer div is greater than scrollDisclaimerHeightComparison
if ($settings.showDisclaimer)
updateScrollingFeatureDisclaimer($elem, $settings);
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
notApplicableHover($elem);
//add a scroll on long item names
if ($settings.scrollLongItemName)
addScrollToItemDiv($elem, $settings);
//if the text box for the unit quantity is shown
if ($settings.showServingUnitQuantityTextbox){
//increase the unit quantity by clicking the up arrow
$('#'+$elem.attr('id')).on('click', '.unitQuantityUp', function(e){
e.preventDefault();
$settingsHolder = $.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} );
$settingsHolder.totalContainerQuantity = $settings.totalContainerQuantity;
$settingsHolder.originalServingUnitQuantity = $settings.originalServingUnitQuantity;
$settingsHolder.nutritionValueMultiplier = $settingsHolder.valueServingUnitQuantity <= 0 ? 1 : 1 / $settingsHolder.valueServingUnitQuantity;
changeQuantityByArrow($(this), 1, $settingsHolder, nutritionLabel, $elem);
});
//decrease the unit quantity by clicking the down arrow
$('#'+$elem.attr('id')).on('click', '.unitQuantityDown', function(e){
e.preventDefault();
$settingsHolder = $.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} );
$settingsHolder.originalServingUnitQuantity = $settings.originalServingUnitQuantity;
$settingsHolder.totalContainerQuantity = $settings.totalContainerQuantity;
$settingsHolder.nutritionValueMultiplier = $settingsHolder.valueServingUnitQuantity <= 0 ? 1 : 1 / $settingsHolder.valueServingUnitQuantity;
changeQuantityByArrow($(this), -1, $settingsHolder, nutritionLabel, $elem);
});
//the textbox unit quantity value is changed
$('#'+$elem.attr('id')).on('change', '.unitQuantityBox', function(e){
e.preventDefault();
$settingsHolder = $.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} );
$settingsHolder.originalServingUnitQuantity = $settings.originalServingUnitQuantity;
$settingsHolder.totalContainerQuantity = $settings.totalContainerQuantity;
$settingsHolder.nutritionValueMultiplier = $settingsHolder.valueServingUnitQuantity <= 0 ? 1 : 1 / $settingsHolder.valueServingUnitQuantity;
changeQuantityTextbox($(this), $settingsHolder, nutritionLabel, $elem);
});
//the textbox unit quantity value is changed
$('#'+$elem.attr('id')).on('keydown', '.unitQuantityBox', function(e){
if (e.keyCode == 13){
e.preventDefault();
$settingsHolder = $.extend( {}, $.fn.nutritionLabel.defaultSettings, settings || {} );
$settingsHolder.originalServingUnitQuantity = $settings.originalServingUnitQuantity;
$settingsHolder.totalContainerQuantity = $settings.totalContainerQuantity;
$settingsHolder.nutritionValueMultiplier = $settingsHolder.valueServingUnitQuantity <= 0 ? 1 : 1 / $settingsHolder.valueServingUnitQuantity;
changeQuantityTextbox($(this), $settingsHolder, nutritionLabel, $elem);
}
});
}
//store the object for later reference
$elem.data('_nutritionLabel', nutritionLabel);
}
function addScrollToItemDiv($elem, $settings){
if ( $('#'+$elem.attr('id')+' .name.inline').val() != undefined ){
if ( $('#'+$elem.attr('id')+' .name.inline').height() > ( parseInt($settings.scrollLongItemNamePixel) + 1 ) )
$('#'+$elem.attr('id')+' .name.inline').css({
'margin-left' : '3.90em',
'height' : parseInt($settings.scrollLongItemNamePixel)+'px',
'overflow-y' : 'auto'
});
}else{
if ( $('#'+$elem.attr('id')+' .name').height() > ( parseInt($settings.scrollLongItemNamePixel) + 1 ) )
$('#'+$elem.attr('id')+' .name').css({
'height' : parseInt($settings.scrollLongItemNamePixel)+'px',
'overflow-y' : 'auto'
});
}
}
function notApplicableHover($elem){
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
if ($elem.attr('id') !== undefined && $elem.attr('id') !== '')
$('#'+$elem.attr('id')+' .notApplicable').hover(
function(){
$('#'+$elem.attr('id')+' .naTooltip')
.css({
'top' : $(this).position().top+'px',
'left' : $(this).position().left+ 10 +'px'
}).show();
},
function(){
$('#'+$elem.attr('id')+' .naTooltip').hide();
}
);
else
$('#'+$elem.attr('id')+' .notApplicable').hover(
function(){
$('.naTooltip')
.css({
'top' : $(this).position().top+'px',
'left' : $(this).position().left+ 10 +'px'
}).show();
},
function(){
$('.naTooltip').hide();
}
);
}
function updateScrollingFeature($elem, $settings){
if ($elem.attr('id') !== undefined && $elem.attr('id') !== '')
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
$ingredientListParent = $('#'+$elem.attr('id')+' #ingredientList').parent();
else
$ingredientListParent = $('#ingredientList').parent();
if ($ingredientListParent.innerHeight() > $settings.scrollHeightComparison)
$ingredientListParent.addClass('scroll').css({
'height' : $settings.scrollHeightPixel+'px'
});
}
function updateScrollingFeatureDisclaimer($elem, $settings){
if ($elem.attr('id') !== undefined && $elem.attr('id') !== '')
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
$disclaimerParent = $('#'+$elem.attr('id')+' #calcDisclaimerText').parent();
else
$disclaimerParent = $('#calcDisclaimerText').parent();
if ($disclaimerParent.innerHeight() > $settings.scrollDisclaimerHeightComparison)
$disclaimerParent.addClass('scroll').css({
'height' : $settings.scrollDisclaimer+'px'
});
}
function changeQuantityTextbox($thisTextbox, $originalSettings, nutritionLabel, $elem){
var textBoxValue = parseFloat( $thisTextbox.val() );
textBoxValue = isNaN(textBoxValue) ? 1.0 : textBoxValue;
$thisTextbox.val( textBoxValue.toFixed(1) );
$originalSettings.valueServingUnitQuantity = textBoxValue;
$originalSettings = UpdateNutritionValueWithMultiplier($originalSettings);
nutritionLabel = new NutritionLabel($originalSettings, $elem);
$elem.html( nutritionLabel.generate() );
//scroll the ingredients of the innerheight is > $settings.scrollHeightComparison
//and the settings showIngredients and scrollLongIngredients are true
if ($originalSettings.showIngredients && $originalSettings.scrollLongIngredients)
updateScrollingFeature($elem, $originalSettings);
//scroll the disclaimer if the height of the disclaimer div is greater than scrollDisclaimerHeightComparison
if ($originalSettings.showDisclaimer)
updateScrollingFeatureDisclaimer($elem, $originalSettings);
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
notApplicableHover($elem);
//add a scroll on long item names
if ($originalSettings.scrollLongItemName)
addScrollToItemDiv($elem, $originalSettings);
}
function changeQuantityByArrow($thisQuantity, changeValueBy, $settings, nutritionLabel, $elem){
//get the current user quantity of the item
var currentQuantity = parseFloat( $thisQuantity.parent().parent().find('input.unitQuantityBox').val() );
if ( isNaN(currentQuantity) )
currentQuantity = 1.0;
//see https://github.com/nutritionix/nutrition-label/issues/14 for an explanation on this part
if (currentQuantity <= 1 && changeValueBy == -1){
changeValueBy = -0.5;
currentQuantity += changeValueBy;
}else if (currentQuantity < 1 && changeValueBy == 1){
changeValueBy = 0.5;
currentQuantity += changeValueBy;
}else if (currentQuantity <= 2 && currentQuantity > 1 && changeValueBy == -1)
currentQuantity = 1;
else
currentQuantity += changeValueBy;
if (currentQuantity < 0)
currentQuantity = 0;
$thisQuantity.parent().parent().find('input.unitQuantityBox').val( currentQuantity.toFixed(1) );
$settings.valueServingUnitQuantity = currentQuantity;
$settings = UpdateNutritionValueWithMultiplier($settings);
nutritionLabel = new NutritionLabel($settings, $elem);
$elem.html( nutritionLabel.generate() );
//scroll the ingredients of the innerheight is > $settings.scrollHeightComparison
//and the settings showIngredients and scrollLongIngredients are true
if ($settings.showIngredients && $settings.scrollLongIngredients)
updateScrollingFeature($elem, $settings);
//scroll the disclaimer if the height of the disclaimer div is greater than scrollDisclaimerHeightComparison
if ($settings.showDisclaimer)
updateScrollingFeatureDisclaimer($elem, $settings);
//this code is for pages with multiple nutrition labels generated by the plugin like the demo page
notApplicableHover($elem);
//add a scroll on long item names
if ($settings.scrollLongItemName)
addScrollToItemDiv($elem, $settings);
}
//round the value to the nearest number
function roundToNearestNum(input, nearest){
if (nearest < 0)
return Math.round(input*nearest)/nearest;
else
return Math.round(input/nearest)*nearest;
}
function roundCalories(toRound, decimalPlace){
toRound = roundCaloriesRule(toRound);
if (toRound > 0)
toRound = parseFloat( toRound.toFixed(decimalPlace) );
return toRound;
}
function roundFat(toRound, decimalPlace){
toRound = roundFatRule(toRound);
if (toRound > 0)
toRound = parseFloat( toRound.toFixed(decimalPlace) );
return toRound;
}
function roundSodium(toRound, decimalPlace){
toRound = roundSodiumRule(toRound);
if (toRound > 0)
toRound = parseFloat( toRound.toFixed(decimalPlace) );
return toRound;
}
function roundCholesterol(toRound, decimalPlace){
var normalVersion = true;
var roundResult = roundCholesterolRule(toRound);
if (roundResult === false)
normalVersion = false;
else
toRound = roundResult;
if (normalVersion){
if (toRound > 0)
toRound = parseFloat( toRound.toFixed(decimalPlace) );
}else
toRound = '< 5';
return toRound;
}
function roundCarbFiberSugarProtein(toRound, decimalPlace){
var normalVersion = true;
var roundResult = roundCarbFiberSugarProteinRule(toRound);
if (roundResult === false)
normalVersion = false;
else
toRound = roundResult;
if (normalVersion){
if (toRound > 0)
toRound = parseFloat( toRound.toFixed(decimalPlace) );
}else
toRound = '< 1';
return toRound;
}
//Calories and Calories from Fat rounding rule
function roundCaloriesRule(toRound){
if (toRound < 5)
return 0;
else if (toRound <= 50)
//50 cal - express to nearest 5 cal increment
return roundToNearestNum(toRound, 5);
else
//> 50 cal - express to nearest 10 cal increment
return roundToNearestNum(toRound, 10);
}
//Total Fat, Saturated Fat, Polyunsaturated Fat and Monounsaturated Fat rounding rule
function roundFatRule(toRound){
if (toRound < .5)
return 0;
else if (toRound < 5)
//< 5 g - express to nearest .5g increment
return roundToNearestNum(toRound, .5);
else
//>= 5 g - express to nearest 1 g increment
return roundToNearestNum(toRound, 1);
}
//Sodium rounding rule
function roundSodiumRule(toRound){
if (toRound < 5)
return 0;
else if (toRound <= 140)
//5 - 140 mg - express to nearest 5 mg increment
return roundToNearestNum(toRound, 5);
else
//>= 5 g - express to nearest 10 g increment
return roundToNearestNum(toRound, 10);
}
//Cholesterol rounding rule
function roundCholesterolRule(toRound){
if (toRound < 2)
return 0;
else if (toRound <= 5)
return false;
else
//> 5 mg - express to nearest 5 mg increment
return roundToNearestNum(toRound, 5);
}
//Total Carbohydrate, Dietary Fiber, Sugar and Protein rounding rule
function roundCarbFiberSugarProteinRule(toRound){
if (toRound < .5)
return 0;
else if (toRound < 1)
//< 1 g - express as "Contains less than 1g" or "less than 1g"
return false;
else
//> 1 mg - express to nearest 1 g increment
return roundToNearestNum(toRound, 1);
}
//Total Carbohydrate, Dietary Fiber, Sugar and Protein rounding rule
function roundVitaminsCalciumIron(toRound){
if (toRound > 0){
if (toRound < 10)
//< 10 - round to nearest even number
return roundToNearestNum(toRound, 2);
else if (toRound < 50)
//between 10 and 50, round to the nearest 5 increment
return roundToNearestNum(toRound, 5);
else
//else, round to the nearest 10 increment
return roundToNearestNum(toRound, 10);
}else
return 0;
}
NutritionLabel.prototype = {
generate: function(){
//this is the function that returns the html code for the nutrition label based on the settings that is supplied by the user
var $this = this;
//return the plugin incase it has already been created
if ($this.nutritionLabel)
return $this.nutritionLabel;
if ($this.settings.hideNotAppicableValues){
$this.settings.showCalories = $this.settings.naCalories ? false : $this.settings.showCalories;
$this.settings.showFatCalories = $this.settings.naFatCalories ? false : $this.settings.showFatCalories;
$this.settings.showTotalFat = $this.settings.naTotalFat ? false : $this.settings.showTotalFat;
$this.settings.showSatFat = $this.settings.naSatFat ? false : $this.settings.showSatFat;
$this.settings.showTransFat = $this.settings.naTransFat ? false : $this.settings.showTransFat;
$this.settings.showPolyFat = $this.settings.naPolyFat ? false : $this.settings.showPolyFat;
$this.settings.showMonoFat = $this.settings.naMonoFat ? false : $this.settings.showMonoFat;
$this.settings.showCholesterol = $this.settings.naCholesterol ? false : $this.settings.showCholesterol;
$this.settings.showSodium = $this.settings.naSodium ? false : $this.settings.showSodium;
$this.settings.showTotalCarb = $this.settings.naTotalCarb ? false : $this.settings.showTotalCarb;
$this.settings.showFibers = $this.settings.naFibers ? false : $this.settings.showFibers;
$this.settings.showSugars = $this.settings.naSugars ? false : $this.settings.showSugars;
$this.settings.showProteins = $this.settings.naProteins ? false : $this.settings.showProteins;
$this.settings.showVitaminA = $this.settings.naVitaminA ? false : $this.settings.showVitaminA;
$this.settings.showVitaminC = $this.settings.naVitaminC ? false : $this.settings.showVitaminC;
$this.settings.showCalcium = $this.settings.naCalcium ? false : $this.settings.showCalcium;
$this.settings.showIron = $this.settings.naIron ? false : $this.settings.showIron;
}
//initializing the tab variables
//tab variables are used to make the printing of the html code readable when you copy the code using
//firebug => inspect => copy innerhtml
//for debugging and editing purposes
for (x = 1; x < 9; x++){
var tab = '';
for (y = 1; y <= x; y++)
tab += '\t';
eval('var tab' + x + ' = "' + tab + '";');
}
//initialize the not applicable image icon in case we need to use it
var naValue = '<font class="notApplicable">- </font>';
var calorieIntakeMod = (parseFloat($this.settings.calorieIntake) / 2000).toFixed(2);
var borderCSS = '';
if ($this.settings.allowNoBorder)
borderCSS = 'border: 0;';
//creates the html code for the label based on the settings
var nutritionLabel = '';
if (!$this.settings.allowCustomWidth)
nutritionLabel += '<div class="nutritionLabel" style="' + borderCSS + ' width: '+ $this.settings.width + 'px;">\n';
else
nutritionLabel += '<div class="nutritionLabel" style="' + borderCSS + ' width: '+ $this.settings.widthCustom + ';">\n';
nutritionLabel += tab1 + '<div class="title">' + $this.settings.textNutritionFacts + '</div>\n';
if ($this.settings.showItemName){
var tabTemp = tab1;
var itemNameClass = '';
if ($this.settings.showServingUnitQuantityTextbox){
if (
($this.settings.valueServingSizeUnit == null || $this.settings.valueServingSizeUnit == '') ||
($this.settings.valueServingSizeUnit !== '' && $this.settings.valueServingSizeUnit !== null &&
$this.settings.originalServingUnitQuantity <= 0)
){
nutritionLabel += tab1 + '<div class="cf">\n';
nutritionLabel += tab2 + '<div class="rel servingSizeField">\n';
var textboxClass = 'unitQuantityBox';
if (!$this.settings.hideTextboxArrows){
nutritionLabel += tab3 + '<div class="setter">\n';
nutritionLabel += tab4 + '<a href="Increase the quantity" class="unitQuantityUp" rel="nofollow"></a>\n';
nutritionLabel += tab4 + '<a href="Decrease the quantity" class="unitQuantityDown" rel="nofollow"></a>\n';
nutritionLabel += tab3 + '</div><!-- closing class="setter" -->\n';
}else
textboxClass = 'unitQuantityBox arrowsAreHidden';
nutritionLabel += tab3 + '<input type="text" value="'+ parseFloat( $this.settings.valueServingUnitQuantity.toFixed($this.settings.decimalPlacesForQuantityTextbox) ) +'" ';
nutritionLabel += 'class="'+textboxClass+'">\n';
nutritionLabel += tab2 + '</div><!-- closing class="servingSizeField" -->\n';
tabTemp = tab2;
var itemNameClass = 'inline';
}
}//end of => if ($this.settings.showServingUnitQuantityTextbox){
nutritionLabel += tabTemp + '<div class="name '+ itemNameClass +'">';
nutritionLabel += $this.settings.itemName;
if ($this.settings.showBrandName && $this.settings.brandName != null && $this.settings.brandName != '')
nutritionLabel += ' - ' + $this.settings.brandName;
nutritionLabel += '</div>\n';
if ($this.settings.showServingUnitQuantityTextbox)
if (
($this.settings.valueServingSizeUnit == null || $this.settings.valueServingSizeUnit == '') ||
($this.settings.valueServingSizeUnit !== '' && $this.settings.valueServingSizeUnit !== null &&
$this.settings.originalServingUnitQuantity <= 0)
)
nutritionLabel += tab1 + '</div><!-- closing class="cf" -->\n';
}//end of => if ($this.settings.showItemName)
var servingSizeIsHidden = false;
var servingContainerIsHidden = false;
var servingSizeTextClass = '';
if ($this.settings.showServingUnitQuantity){
nutritionLabel += tab1 + '<div class="serving">\n';
if ($this.settings.originalServingUnitQuantity > 0){
nutritionLabel += tab2 + '<div class="cf">\n';
nutritionLabel += tab3 + '<div class="servingSizeText fl">' + $this.settings.textServingSize + '</div>\n';
nutritionLabel += $this.settings.showServingUnitQuantityTextbox ?
'' : tab3 + '<div class="servingUnitQuantity fl">' + parseFloat( $this.settings.originalServingUnitQuantity.toFixed($this.settings.decimalPlacesForNutrition) ) + '</div>\n';
var unitAddedClass = '';
var gramsAddedClass = '';
if ($this.settings.valueServingSizeUnit !== '' && $this.settings.valueServingSizeUnit !== null){
if ($this.settings.showServingUnitQuantityTextbox && $this.settings.valueServingSizeUnit != null &&
$this.settings.valueServingSizeUnit != ''){
unitAddedClass = 'unitHasTextbox';
gramsAddedClass = 'gramsHasTextbox';
nutritionLabel += tab3 + '<div class="rel servingSizeField fl">\n';
var textboxClass = 'unitQuantityBox';
if (!$this.settings.hideTextboxArrows){
nutritionLabel += tab4 + '<div class="setter">\n';
nutritionLabel += tab5 + '<a href="Increase the quantity" class="unitQuantityUp" rel="nofollow"></a>\n';
nutritionLabel += tab5 + '<a href="Decrease the quantity" class="unitQuantityDown" rel="nofollow"></a>\n';
nutritionLabel += tab4 + '</div><!-- closing class="setter" -->\n';
}else
textboxClass = 'unitQuantityBox arrowsAreHidden';
nutritionLabel += tab4 + '<input type="text" value="'+ parseFloat( $this.settings.valueServingUnitQuantity.toFixed($this.settings.decimalPlacesForQuantityTextbox) ) +'" ';
nutritionLabel += 'class="'+textboxClass+'">\n';
nutritionLabel += tab3 + '</div><!-- closing class="servingSizeField" -->\n';
}else if ($this.settings.originalServingUnitQuantity > 0 && $this.settings.showServingUnitQuantityTextbox)
nutritionLabel += tab3 + '<div class="servingUnitQuantity">' + parseFloat( $this.settings.originalServingUnitQuantity.toFixed($this.settings.decimalPlacesForNutrition) ) + '</div>\n';
nutritionLabel += tab3 + '<div class="servingUnit fl '+unitAddedClass+'">'+ $this.settings.valueServingSizeUnit + '</div>\n';
}else if ($this.settings.originalServingUnitQuantity > 0 && $this.settings.showServingUnitQuantityTextbox)
nutritionLabel += tab3 + '<div class="servingUnitQuantity fl">' + parseFloat( $this.settings.originalServingUnitQuantity.toFixed($this.settings.decimalPlacesForNutrition) ) + '</div>\n';
//end of => if ($this.settings.valueServingSizeUnit !== '' && $this.settings.valueServingSizeUnit !== null){
if ($this.settings.valueServingWeightGrams > 0)
nutritionLabel += tab3 + '<div class="servingWeightGrams fl '+gramsAddedClass+'">('+
parseFloat( $this.settings.valueServingWeightGrams.toFixed($this.settings.decimalPlacesForNutrition) )
+ 'g)</div>\n';
nutritionLabel += tab2 + '</div><!-- closing class="cf" -->\n';
}else
servingSizeIsHidden = true;
//end of => if ($this.settings.originalServingUnitQuantity > 0){
if ($this.settings.showServingsPerContainer){
//Serving per container
if ($this.settings.valueServingPerContainer > 0){
nutritionLabel += tab2 + '<div>' + $this.settings.textServingsPerContainer + ' ';
nutritionLabel += parseFloat(
$this.settings.valueServingPerContainer.toFixed($this.settings.decimalPlacesForNutrition)
);
nutritionLabel += '</div>\n';
}else
servingContainerIsHidden = true;
}else
servingContainerIsHidden = true;
nutritionLabel += tab1 + '</div><!-- closing class="serving" -->\n';
}//end of => if ($this.settings.showServingUnitQuantity)
if ( (!$this.settings.showItemName && !$this.settings.showServingUnitQuantity) ||
(!$this.settings.showItemName && servingSizeIsHidden && servingContainerIsHidden) )
nutritionLabel += tab1 + '<div class="headerSpacer"></div>\n';
nutritionLabel += tab1 + '<div class="bar1"></div>\n';
if ($this.settings.showAmountPerServing){
nutritionLabel += tab1 + '<div class="line m">';
nutritionLabel += '<b>' + $this.settings.textAmountPerServing + '</b>';
nutritionLabel += '</div>\n';
}
nutritionLabel += tab1 + '<div class="line">\n';
if ($this.settings.showFatCalories){
nutritionLabel += tab2 + '<div class="fr">';
nutritionLabel += $this.settings.textFatCalories + ' ';
nutritionLabel += $this.settings.naFatCalories ?
naValue :
(
$this.settings.allowFDARounding ?
roundCalories($this.settings.valueFatCalories, $this.settings.decimalPlacesForNutrition) :
parseFloat( $this.settings.valueFatCalories.toFixed($this.settings.decimalPlacesForNutrition) )
) + $this.settings.unitFatCalories;
nutritionLabel += '</div>\n';
}
if ($this.settings.showCalories){
nutritionLabel += tab2 + '<div>';
nutritionLabel += '<b>' + $this.settings.textCalories + '</b> ';
nutritionLabel += $this.settings.naCalories ?
naValue :
(
$this.settings.allowFDARounding ?
roundCalories($this.settings.valueCalories, $this.settings.decimalPlacesForNutrition) :
parseFloat( $this.settings.valueCalories.toFixed($this.settings.decimalPlacesForNutrition) )
) + $this.settings.unitCalories;
nutritionLabel += '</div>\n';
}else if ($this.settings.showFatCalories)
nutritionLabel += tab2 + '<div> </div>\n';
nutritionLabel += tab1 + '</div>\n';
nutritionLabel += tab1 + '<div class="bar2"></div>\n';
nutritionLabel += tab1 + '<div class="line ar">';
nutritionLabel += '<b>% ' + $this.settings.textDailyValues + '<sup>*</sup></b>';
nutritionLabel += '</div>\n';