felixaburg felixaburg - 7 months ago 9
Javascript Question

how to call different jquery actions in responsive design

I'm at the point to convert my project into an responsive design.

What is the most handy and universal solution do you suggest to implement different jQuery-blocks for each breakpoint?

I want to keep all scripts in one file cause of number of http-requests.

That's what I've found:


  • breakpoint.js -> define all breakpoints doubled in CSS & JS

  • http://responsejs.com/ -> define breakpoints in body data-attr

  • OnMediaQuery -> define human-readable names for the breakpoints (IMHO better, cause you're not bound to pixels)



My problem is, they all define callbacks, but I don't know how to bind or cancel any jQuery event-listeners in these cases.

e.g. I have:

$('#selector').click( function() {
alert('selector clicked');
});


but that should only happen if in max-width of 320px.
In screen-sizes above that the click should return false or perform any other action

at the moment, I don't have a clue how to accomplish this.

Answer

You can just create your own breakpoints in JS. Something like this. Adjust to your needs.

var isBreakPoint = function (bp) {
    var bps = [320, 480, 768, 1024],
        w = $(window).width(),
        min, max
    for (var i = 0, l = bps.length; i < l; i++) {
      if (bps[i] === bp) {
        min = bps[i-1] || 0
        max = bps[i]
        break
      }
    }
    return w > min && w <= max
}

// Usage
if (isBreakPoint(480)) { ... } // Breakpoint between 320 and 480