breakpoints.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Breakpoints.js
  3. version 1.0
  4. Creates handy events for your responsive design breakpoints
  5. Copyright 2011 XOXCO, Inc
  6. http://xoxco.com/
  7. Documentation for this plugin lives here:
  8. http://xoxco.com/projects/code/breakpoints
  9. Licensed under the MIT license:
  10. http://www.opensource.org/licenses/mit-license.php
  11. */
  12. (function($) {
  13. var lastSize = 0;
  14. var interval = null;
  15. $.fn.resetBreakpoints = function() {
  16. $(window).unbind('resize');
  17. if (interval) {
  18. clearInterval(interval);
  19. }
  20. lastSize = 0;
  21. };
  22. $.fn.setBreakpoints = function(settings) {
  23. var options = jQuery.extend({
  24. distinct: true,
  25. breakpoints: new Array(320,480,768,1024)
  26. },settings);
  27. interval = setInterval(function() {
  28. var w = $(window).width();
  29. var done = false;
  30. for (var bp in options.breakpoints.sort(function(a,b) { return (b-a) })) {
  31. // fire onEnter when a browser expands into a new breakpoint
  32. // if in distinct mode, remove all other breakpoints first.
  33. if (!done && w >= options.breakpoints[bp] && lastSize < options.breakpoints[bp]) {
  34. if (options.distinct) {
  35. for (var x in options.breakpoints.sort(function(a,b) { return (b-a) })) {
  36. if ($('body').hasClass('breakpoint-' + options.breakpoints[x])) {
  37. $('body').removeClass('breakpoint-' + options.breakpoints[x]);
  38. $(window).trigger('exitBreakpoint' + options.breakpoints[x]);
  39. }
  40. }
  41. done = true;
  42. }
  43. $('body').addClass('breakpoint-' + options.breakpoints[bp]);
  44. $(window).trigger('enterBreakpoint' + options.breakpoints[bp]);
  45. }
  46. // fire onExit when browser contracts out of a larger breakpoint
  47. if (w < options.breakpoints[bp] && lastSize >= options.breakpoints[bp]) {
  48. $('body').removeClass('breakpoint-' + options.breakpoints[bp]);
  49. $(window).trigger('exitBreakpoint' + options.breakpoints[bp]);
  50. }
  51. // if in distinct mode, fire onEnter when browser contracts into a smaller breakpoint
  52. if (
  53. options.distinct && // only one breakpoint at a time
  54. w >= options.breakpoints[bp] && // and we are in this one
  55. w < options.breakpoints[bp-1] && // and smaller than the bigger one
  56. lastSize > w && // and we contracted
  57. lastSize >0 && // and this is not the first time
  58. !$('body').hasClass('breakpoint-' + options.breakpoints[bp]) // and we aren't already in this breakpoint
  59. ) {
  60. $('body').addClass('breakpoint-' + options.breakpoints[bp]);
  61. $(window).trigger('enterBreakpoint' + options.breakpoints[bp]);
  62. }
  63. }
  64. // set up for next call
  65. if (lastSize != w) {
  66. lastSize = w;
  67. }
  68. },250);
  69. };
  70. })(jQuery);