Coder Social home page Coder Social logo

response.js's Introduction

Response

Response is an experimental jQuery/Ender/Zepto plugin that gives web designers tools for building responsive websites. It can dynamically swap content based on breakpoints and data attributes. (npm: response.js)

API (0.10)

Breakpoint sets

Response's main feature is its breakpoint sets. They offer the ability to serve different content via breakpoint-based data attributes. They are best applied with a mobile-first approach. Devs can choose custom breakpoints to create exactly data attributes they need. By default none are setup.

Creating breakpoint sets

Sets are created either by calling Response.create(options) directly, or automatically via JSON stored in a body[data-responsejs]. The options can be a plain object or an array of them.

Response.create({
    prop: "width"  // "width" "device-width" "height" "device-height" or "device-pixel-ratio"
  , prefix: "min-width- r src"  // the prefix(es) for your data attributes (aliases are optional)
  , breakpoints: [1281,1025,961,641,481,320,0] // min breakpoints (defaults for width/device-width)
  , lazy: true // optional param - data attr contents lazyload rather than whole page at once
});

OR

<body data-responsejs='{
  "create": [
    { "prop": "width"
    , "prefix": "min-width- r src"
    , "lazy": true
    , "breakpoints": [1281,1025,961,641,481,320,0] }
  ]}'
>
To write markup like
<div data-min-width-481="markup @ 481px+" data-min-width-961="markup @ 961px+">
  default markup for 480px- or no-js
</div>

Extending

Define a custom breakpoint set that uses a custom test

/**
 * @param {string} prop custom property name (or an existing prop to override)
 * @param {Function} test callback to test min breakpoints for the prop
 */
Response.addTest('viewport-area', function(min) {
  return min >= Response.viewportW() * Response.viewportH();
}).create({
    prop: 'viewport-area' // custom prop name
  , breakpoints: [100000, 1000000, 10000000] // custom breakpoints
  , dynamic: true // set this to true if prop needs to be tested on resize
});

Methods from verge

Response.viewportW() // CSS viewport width
Response.viewportH() // CSS viewport height
Response.mq(mediaQuery) // => boolean
Response.inViewport(elem, cushion?) // => boolean
Response.inX(elem, cushion?) // => boolean
Response.inY(elem, cushion?) // => boolean
Response.scrollX() // => number
Response.scrollY() // => number

Device size

Response.deviceW() // device width
Response.deviceH() // device height
Response.deviceMax() // calculated Math.max(deviceW, deviceH)
Response.deviceMin() // calculated Math.min(deviceW, deviceH)

devicePixelRatio

Response.dpr(1.5) // true when device-pixel-ratio is 1.5+
Response.dpr(2) // true when device-pixel-ratio is 2+
Response.dpr() // get device-pixel-ratio - returns integer or float (0 if undetectable)

Viewport size ranges

Response.band(481) // true in viewports 481px wide and up.
Response.band(0, 480) // true in viewports 0-480px wide.
Response.wave(641) // true in viewport 641px high and up.
Response.wave(0, 640) // true in viewports 0-640px high.

Device size ranges

Response.device.band(481) // true for devices 481px wide and up
Response.device.band(0, 480) // true for devices 0-480px wide.
Response.device.wave(641) // true for devices 641px high and up.
Response.device.wave(0, 640) // true for devices 0-640px high.

Events

Call a function on breakpoint set crossovers

Response.crossover('width', function() {
  // runs when 'width' breakpoints are crossed
})

Response.crossover(function() {
  // runs when any defined breakpoint is crossed
})

@deprecated event utils

Response.ready(fn) // call fn on ready
Response.resize(fn) // call fn on resize
Response.action(fn|fns) // call fn(s) on ready *and* on resize

@deprecated dataset utils

Response.dataset(elem, key) // get
Response.dataset(elem, [key]) // get and render (See Response.render)
Response.dataset(elem, key, value) // set
Response.dataset(elem, atts) // set multiple data atts at once
Response.deletes(elem, keys) // delete one or more data atts
Response.dataset(document.body, "pulpFiction", 5) // sets <body data-pulp-fiction="5">
Response.dataset(document.body, "pulpFiction") // -> "5"
Response.dataset(document.body, ["pulpFiction"]) // -> 5

Response.render(str) // convert stringified primitives to correct value e.g. "true" to true
Response.camelize(str) // convert 'pulp-fiction' or 'data-pulp-fiction' to pulpFiction
Response.datatize(str) // convert 'pulpFiction' to 'data-pulp-fiction'
Response.target(keys) // convert keys like "a b c" or ["a","b","c"] to $("[data-a],[data-b],[data-c]")
Response.access(keys) // access an array of dataset values that correspond to an array of dataset keys
Response.store($elems, key, attrToReadFrom?) // store init content of each elem to data key

@deprecated object utils

Response.affix(stack, prefix?, suffix?) // create array w/ prefix|suffix added to each stack value
Response.each(stack, fn, scope?) // call fn for each item in stack
Response.map(stack, fn, scope?) // map stack into a new array
Response.merge(target, source) // merge source's defined values into target
Response.object(parent) // create a new object that inherits parent (via Object.create where possible)
Response.route(stack|other, fn, scope?) // call fn on each stack value or on a non-stack
Response.sift(stack, fn?, scope|invert?) // like _.compact, [].filter, and jQuery.grep

.noConflict()

Re: fetch

// Unmodify window
Response.noConflict()
// Unmodify window and save reference to our Response
let R = Response.noConflict()
Response.noConflict(function(Response) {
  // Unmodify window and get safe reference to our Response in here
})

AMD usage

define(['jquery'], Response.noConflict);  // define module and unmodify window

Resources

Related Modules

  • verge - viewport utilities
  • actual - @media detector
  • dope - dataset abstraction
  • res - resolution utilities

response.js's People

Contributors

ryanve avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

response.js's Issues

Adding "Processors"

I've just looked through the reponse.js docs. It looks very promising and we consider using it in upcoming projects. However, I have a suggestion how the library could be even more flexible, here is a mockup of the basic idea:

The API gets a new method like addProcessor([name], [function])

Response.addProcessor('myprocessor', function(args, context) {
  // Here you have information about the breakpoint triggerd and the
  // arguments passed in

  context.$el.html('some custom content...'); // set the elemnts content
});

In the Markup you can then trigger this Processor with a syntax like:

<div data-min-width-481-myprocessor="some argument">
  default
</div>

The Processor 'myprocessor' gets triggerd and "some argument" passed in through 'args' and 'context' provides information about 'min-with', '481' and the element itself ($el). Instead of a pure string argument we could also think of an object as argument: data-min-width-481-myprocessor="{param1:'my argument',param2:'my argument2'}"

The benefit of this is that we get great flexibility. One real-world example how this could be used: Instead of putting all content inside attributes, pull the content from templates:

Response.addProcessor('template', function(args, context) {
  context.$el.html( $(args).html() );
});
<script id="desktop_content">
  This will be shown to desktop users. We can also use &quot;-Symbols here without
  to worry, since we are not inside an attribute.
</script>
<div data-min-width-980-template="#desktop_content">
  my default content
</div>

Content could also be loaded with ajax requests and so on...

Just some thoughts :-)

Request: size of parent container as an option

Here is a great little script that I have been using that allows me to change the class of an element depending upon the width of the element itself
https://github.com/ahume/selector-queries

Request:
Response.js will allow me to set queries via the width of the vp or the screen itself, it would be nice to also have the ability to have response.js to allow the option of measuring the container element as well.

Reason:
Some of my theme templates have sidebars, others do not. While I can change the content of an element via response for the screen size, there are many instances where I would also want to add/remove elements depending upon whether or not my container div has enough room to make it still look right.

Scenario:
I have a main content area element

and also a sidebar element
. Using response, I can choose to remove the sidebar element if say the screen size is less than >768px.

Same scenario as above, only there is are 2 sidebars. I want to remove one of them if the screen shrinks below a set amount. My choices are to either write more media queries, or to write up a ton of additional css to make the changes. By being able to put a conditional on the size of the parent element with response.js, then it is a simple matter of a couple lines of code. Much cleaner and easier to maintain.

I hope the idea is clear and the benefit is even more obvious.

The script I linked to does a fantastic job of changing the class name, thus allowing me to write custom css for when the element changes sizes, however I do not have the benefit of not displaying the element in the first place like I can with response.

Elements not loading correctly until window resize

I am working on a website(steillustrates.co.uk/) that pulls in and initiates a carousel(http://caroufredsel.dev7studios.com/) at one of the default breakpoints of 1281 within a Response.action function, however when you land on the site(unchached) the carousel loads but isn't loaded correctly until you resize the window, and it only needs to be a slight resize to trigger the carousel to load correctly. If you refresh the page once the site has loaded in it all works correctly.

I have had a look through the methods and such but kind seem to find something that could help with this, is this a known issue?

Cannot suppress default content at higher breakpoint?

Following instructions at #10, I created a custom test using prefix r- and breakpoints named mobile, tablet, and desktop.

Now, this first code worked perfectly as expected:

    <div>
      <div data-r-tablet='Content for tablet and desktop users'></div>
    </div>

But the content in the following div was always displayed, despite the fact that I (intended to) explicitly remove the content at the tablet breakpoint:

        <div data-r-tablet=''>
          Same content but in a different location, for only mobile users
        </div>

How to prevent large images from popping in?

Take a look at the following example, which uses two fairly large images in a div at 300 and 500 pixel breakpoints.

http://jsfiddle.net/9QF4f/1/

When you resize the browser, around the 500 pixel breakpoint, when the images swap, there is some jittery popping of the images when they swap.

Is there any way to prevent this? I know responsejs works great when just loading stuff on a mobile device where you don't ever change the screen size, but when people load my site on desktop I don't want them to see images and layout popping around when they resize their browser.

Multiple breakpoints

How can I control when multiple breakpoints are found by the plugin. I have breakpoints set for width and pixel density. There are cases when both will be true. I'm hoping to get the markup need for when these crossover. For example, maybe it's

img data-pixel-ratio-1="path.1" data-pixel-ratio-1.5="path.2" data-min-width-320="path.320" data-pixel-ratio-min-width="path1and320" /

Does that make sense?
Thanks for your help!

Lazyload offset

Is there a way to add a offset to the lazy parameter? For example to load the content (expecially imgs) 200px before you reach them in your viewport?

Add Names instead of Widths as an option?

Hello,

At the moment Response uses the following syntax:

<img src="lo-fi.png" data-src1025="hi-fi.png" alt="example" />

Imagine that later on I need to change the breakpoint 1025 ro 1020 ...

Then I will be forced to change the data-src1025 in all images.

Wouldn't it be possible to associated breakpoints values to names?

For example:

1025 would be "desktop", 760 would be "Tablet" ...

Then the images would become:

<img src="lo-fi.png" data-srcdesktop="hi-fi.png" alt="example" />

So in Response.Create there would be an option to associate widths to names as an option.

What do you think?

Thank You,
Miguel

swap html and jquery

I'm working on a site where I want to swap out a slideshow and separately an accordion. Both require their own jquery scripts.

I've got responsejs working on images and plain old html, but when I try to swap out the slideshow or the accordion, they don't work. I assume there's some problem with the timing or sequence of the html or the jquery, but honestly I'm just guessing.

I don't see anything in the documentation about this. Can you give me any guidance on how to do this?

Thank you.

How to call function after content changes?

Sorry for my English. For example:

<div id="test" data-min-width-960="Width 960+">
    Content Fallback
</div>

If I load this on large desktop and try to get the content in the div via jQuery, it returns "Content Fallback", not "Width 960+". I also on ready, resize, and action.

Response.ready(function(){
    // it will return "Content Fallback"
    console.log($('#test').html());
});

Response.resize(function(){
    // It will return that content that being changed, it's exactly what I need, 
    // but it can't return content when first load and not resize
    console.log($('#test').html());
});

Response.action(function(){
    // it will return "Content Fallback" on first time load, 
    // and return the content that being changed.
    console.log($('#test').html());
});

So, I think in fact my problem is how to get the correct content when the page loads the first time. Thank you, sorry for my bad English again, hope you can understand what I mean.

position: fixed issue

Scenario:

You have an <img> with position: fixed.

This breaks response.js from serving smaller/larger version of the img at proper viewport breakpoints.

Behavior tested on iPad:

  • on orientation change, when flipping from landscape to portrait, the resulting img is the original one (defined in src attribute).

Removing the css property solves the issue.

I can put online some demos, if you need it.

Event after content changes and loading is complete

I'm trying to run code that fires after the loading is complete on an image I'm bringing in with response.js. If the image was embedded in the html traditionally the following would work...

$(".textonphoto img").one('load', function() {
    // image load function
}).each(function() {
   if(this.complete) {
      // image completely loaded.
   }
});

But this doesn't fire on img elements brought in through response.js

The issue I'm having is that firing the event using .ready or .resize (R.action) works fine, but the image might not be completely loaded. So where I'm asking for the height of the image, it might come back with zero as a result.

There's a little plugin developed to deal with this issue in a traditional image tags... http://desandro.github.io/imagesloaded/ But this wouldn't detect img's in response.js data tags that I'm using

<div
data-min-width-641="<img src='../img/issue01/world-asia.jpg'>"
data-min-width-1025="<img src='../img/issue01/world-asia-big.jpg'>">
</div>

Native version

One of my initial goals with Response was to have it run entirely on native code. But back when I first started the project I didn't know how to handle all of it natively and opted to use jQuery for the rest. There are only a few jQuery methods that Response 0.5 relies on: $ / on / off / trigger / ready / html - basically for querying selectors, handling events, detecting the ready state, and inserting html. I pretty sure that I can work out a version that does all of this stuff natively, supports at least down to IE8, and keeps the overall lib <5k gzipped. By 1.0.0 I definitely think it will be worth it to do thisβ€” what do you think is a better route to take?

Option 1 - 1 version that detects availability of the needed methods, delegates to them if they exist, and otherwise uses native code. (This is consistent with how we done stuff so far.) I think maintainability would be easier this way.

Option 2 - 2 separate versionsβ€”one that requires a jQuery-compatible library and one that is entirely native. This would forego some of the detection and allow each version to be more compact. It might add some initial confusion as far as which version people should to use but I think it could be clearly explained at the top of each file. The public API would be indentical for both.

Modularize Response's methods

Response's methods fit into two categories:

  • response-specific methods only applicable to response.js (.create(), .addTest(), etc.)
  • general-purpose methods that are generally applicable (.dataset(), .viewportW(), etc.) Some of these are better aligned with the "responsive design toolkit" goal than others

The current homepage is focused on the breakpoint-swapping feature. After the 0.3 changes (when several methods were made public) I started working on a new version of the docs here. Yet I hesitated to put that on the homepage in fear of documenting any methods that might soon change.

Putting general-purpose methods public can be useful. But once they're documented then they are expected to be supportedοΏ½β€”regardless of whether or not it is internally needed. In retrospect I might not have made the object utilities or the dataset methods public because they are not internally needed.

In an effort to better modularize the code, I want to better separate the general-purpose methods from the response-specific ones. This will greatly improve maintainability. Support multiple libraries jQuery/Zepto/ender complicates the issue. I'm trying to figure out the most practical way to go about it.

Flattr This Image on Footer not Displaying

When opening http://responsejs.com/ in Chrome on OSX I don't see the Flattr button, only the text link. Is the script broken?
Also I don't get image replacement working:

<script src="/js/jquery-1.9.1.min.js"></script>
<script src="/js/response.min.js"></script>
<script>
    Response.create({
      prop: "width", prefix: "min-width- r src", breakpoints: [1281,1025,961,641,481,320,0], lazy: true
    });
</script>

<img src="http://lorempixel.com/640/200/sports/" data-min-width-641="/img/header2_IMG_2343.jpg" style="width: 100%;" alt="U-Bahn Unterf&uuml;hrung in M&uuml;nchen" />

Do you have any ideas? The network tab in Chrome tells me that an image under "/null" is requested by response.min.js, but not retrieved.

Error: create @fn

Tried to set up some responsive content following the pattern described in #10, but response.js is throwing an error create @fn.

overflowX / overflowY

I've been in the process of improving the docs (beta docs here) and when I got to the overflowX / overflowY methods I was like, whoa these are gonna sound confusing and most people aren't going to use them anyway. We'd had these in there as handlers for inViewport methods, but since version 0.5 we're using getBoundingClientRect and overflowX / overflowY are no longer used internally. IMO it makes sense to depreciate them in 0.6 unless...are there objections? The code is below. It's a native equivalent to $(document).height() - $(window).height() (dims info here) When it's all gzipped the size difference is minimal but still seems like we may as well cut them now rather than support them forever.

function overflowY() {
    // Get the number of pixels that the document width exceeds viewport width.
    var html = document.documentElement
        // document height minus viewport height
      , difference = Math.max(html.offsetHeight, html.scrollHeight, document.body.scrollHeight) - html.clientHeight;
    return 0 < difference ? difference : 0;
}

Programmatically lazy-loading content?

I have a page with a large number of galleries. When the user clicks on a gallery thumbnail, a lightbox with that gallery's images is opened. I'd like to be able to lazy load the gallery contents, but not before the lightbox is opened. Is there a way to do this?

First-timer just needs some help

I apologise if this is not the correct place to post this issue but I have read through all of the documentation and examples but a text page that I have generated as part of my project to create a mobile website for my client, is not working.
I am sure that it is something I have done wrong but I would appreciate some help.

I will post the code that I am using.

New methods for device- and vertical-based tests

In the upcoming version 0.2.9 I'm considering introducing some new methods. Currently we have Response.band(min, max) for testing whether the width of the viewport is in a min/max breakpoint range. I want to name the methods in a way that makes them easy to understand, keeps them in line with existing methods, and keeps them as concise as possible.

Proposed new methods

  • Response.band.vertical(min, max) as a height-based version of Response.band
  • Response.device.band(min, max) as a device-width based version of Response.band
  • Response.device.band.vertical(min, max) as a device-height based version of Response.band

They'd add very little overhead so, and seem like worthwhile additions, right? As for the names, I think the use of .height should be avoided as to avoid confusing it with the native property or with jQuery's .height() method. .vertical and .device both seem pretty understandable (right?) but it also starts to get a bit long. It'd save some bytes if we just use .v as shown below.

Naming scheme 2

  • Response.band.v(min, max) as a height-based version of Response.band
  • Response.device.band(min, max) as a device-width based version of Response.band
  • Response.device.band.v(min, max) as a device-height based version of Response.band

So what's better? .vertical (longer, more semantic) OR .v (shorter, less semantic) OR something different entirely?

Callback when src changes the first time

Is there a callback that fires when the src has changed for the first time? I have a image wrapped with a span, I use this wrapper to display a preloader gif, however I don't know how I should remove the animation once that the full resolution image has finished loading.

Example:

<span class="preloader"><img src="40x40.jpg" data-image-400="400x400.jpg" data-image-800="800x800.jpg" alt="#" /><span>

Version 1.0 Milestones

  1. Refactor the way breakpoint data is created/stored/accessed to best allow for 3–5 below in a way that scales.
  2. Allow for attributes beyond src to be swapped. (#14)
  3. Provide a way for devs to hook into the point where an element's content and/or attributes are changed, such that it would be possible to load content based on ajax requests and/or process the attribute value before applying it. (#13)
  4. Have a way to update breakpoint sets when new content is added to the DOM via Ajax or other means.
  5. Better normalize the behavior of the event methods in regards to the event-providing library.
  6. Reorganize the code such that it is better broken into modular components. Separate the breakpoint sets from general utilties. I've already separated certain components of Response into separate modules (dope, verge). I'm trying to figure the best way to maintain it all and whether those modules should be included in the source of response.js or whether they should be dependencies and require a modular build system.
  7. Update documentation on the website. I'd been working on a new version here but I've been hesitant to document methods that might get nixed. I'm going to get the homepage on github so that its easier to edit / track changes. The readme is ahead of the website docs.

Trigger DOM update on click

Not an issue just a question from a first timer.

I'm using lazy: true and having some difficulty. Some of my imgs are hidden until another object is clicked. The hidden images are not getting a src until I scroll (just a 1px scroll gets it to update). As I continue to click, each img needs a scroll to show. Any ideas?

Can I trigger an update on click? Maybe there's an option to give an offset to the lazy load so the js knows to trigger 200px (or whatever) before the particular img is in view?

Thanks for any help.

Handle Ajax & client-side templating with response.js content?

I am using response.js with its data-* methods of specifying alternative content. It works well, but when I AJAX in content from the same templates, it is always shown in mobile.

Is there any way to hook in response.js during the ajax handling phase?

Response.js Default Media Queries Breakpoints

Hello,

I am working on a responsive web site and using Response.js.

I am trying to set default media queries breakpoints for my projects.

I found that the default Response.js media queries breakpoints are:

0; 320; 481; 641; 961; 1025; 1281

I think they could be described as:

320: Smartphone Portrait
481: Smartphone Landscape
641: ???
961: Desktop and Laptop ???
1025: Wide Screen Desktop and Laptop
1281: Even Wider Screen Desktop and Laptop

I am not sure about where IPAD fits.
And why 641 px? Should not be 768 px for IPAD?

I was reading the following:
http://alpha.responsivedesign.is/develop/media-queries/media-queries-for-common-device-breakpoints

And it seems 768px is used in IPads.

Could someone help me deciding a default list of breakpoints for Response-js?

Thank You,
Miguel

Script element integration

Hello,

I'm trying to use responseJS to integrete advertising script like :

<div 
data-min-width-980='<script language="text/javascript">var my_config_var={play_button:1,show_status:0};</script><script language="text/javascript" src="http://www.example.com/partner.js"></script>'
>
</div>

First Inline script seems to work, but distant javascript call isn't work.

Is-it a bug, or something that else ?

Thanks for your replies.

Response Error Message

When I inspect the site I am working on, I get an error message that says: 'response.js aborted due to missing dependency '

I have been having trouble getting response.js to work on this site and am coming up against a brick wall - any help would be great. (I want it to allow IE8 to see my media queries - which it is not currently)

http://www.ethosep.co.uk.gridhosted.co.uk/environment/

Response.viewportW() evaluates the actual inner width of the page only once, when it's first loaded

Example: if you include response.js in document head and the document is long enough to have a scrollbar, calling Response.viewportW() will always return clientWidth.

, viewportW = docElem['clientWidth'] < win['innerWidth'] ? function() {
    return win['innerWidth'];
} : function() {
    return docElem['clientWidth'];
}

It seems that docElem['clientWidth'] < win['innerWidth'] is evaluated only once - when the browser first loads response.js. For example, if clientWidth and innerWidth are initially equal (i.e. no scrollbar), the comparison (line 94) will evaluate to false, thus setting Response.viewportW() to always return clientWidth. If a scrollbar appears later, nothing changes and clientWidth will still be returned, even though innerWidth is now bigger. Which means on win/chrome the returned value is off by 15px.

Markup not displaying

I'm using response.js for the first time and I'm sorry if the answer to my issue is a simple fix, but I've looked and read everywhere and can't figure out what I'm doing wrong.

I'm building a child theme in Wordpress. I used wp_enqueue_script in my functions.php to add the response.min.js file and it is loading in the site correctly.

I've also placed the data-responsejs in the body tag to set the breakpoints I want:

data-responsejs='{ 
    "create": [
    { "prop": "width"
      , "prefix": "min-width- r src"
      , "lazy": true
      , "breakpoints": [1280,1024,768,640,480,320,0] }
]}' 

However, after writing the code I want to be responsive, nothing displays. The codes I wrote will display inside the first div where I placed it, but will not, no matter what I try, print between the divs. I don't think the display size is the problem as I've tested the page for every size that is set as a breakpoint.

This is the code I wrote

<div data-src320="http://.../wp-content/uploads/2012/04/beach_picnic_250x167.png" data-src640="http://.../wp-content/uploads/2012/04/beach_picnic_600x380.png">
      <!-- default @ <320px and no-js -->   
      <img src="http://.../wp-content/uploads/2012/04/beach_picnic_250x167.png" />
</div>

and this is what happens when the code is processed (as per Firebug)

<div data-src640="http://.../wp-content/uploads/2012/04/beach_picnic_600x380.png" data-src320="http://.../wp-content/uploads/2012/04/beach_picnic_250x167.png" 
data-init-response="&lt;!-- default @ &lt;320px and no-js --&gt; &lt;img src=&quot;http://.../wp-content/uploads/2012/04/beach_picnic_250x167.png&quot;&gt;">
</div>

As you can see, neither image displays. And the default does not display in their place either. So all I have is a blank space where the image should be. (I also know the CSS isn't the problem either).

Is it an issue with Wordpress (running v3.8.1)? I've tried deactivating all the plugins and jQuery scripts I'm running (leaving the jQuery library itself running of course), to test to see if there was any conflict with any other codes or plugins I'm running, but that doesn't appear to be the problem either.

17px difference in the viewport in Mozilla

Hi,
First off all thank you so much for this amazing work. It helps a lot improving my mobile first approach.

I noticed that in Mozilla Firefox, there is a 17px difference between the viewport of a page using response.js and the "real" viewport.

For example if I open the test page (http://responsejs.com/test/) in Mozilla using the adaptive mode (Ctrl + maj + m) and i choose 800 x1280 in the drop down list i will have R.viewportW() 783

After testing a website i'm working on, i found again this 17px difference in the viewport.
I call an image to replace the default text at 641px but the change take place at 658px

The same thing append in IE9, but not in Chrome.

Did you ever noticed something like that, or am I missing something ?

Thank you again for your time

Integrate methods to the $ chain

Currently (version 0.5) none of Response's methods are exposed to the jQuery chain by default. They only get added if Response.chain() is called. Response.chain() is essentially a one-time use function that integrates the chainable versions of inViewport / inX / inY / dataset / deletes into the jQuery chain (or any lib that uses jQuery-compatible syntax). I originally had it like that to avoid potential conflicts, although chose names for those methods that would not conflict with any jQuery core methods. One of the goals of Response is to integrate nicely into any jQuery compatible library. Do you think it makes sense to automatically integrate these methods into the chain by default?

Device orientation change

Hi all, I'm currently using Response.js in conjunction with Backstretch.js. Upon device orientation change it seems that my Backstretch code isn't being re-called and I had to add something like the following to get it to work:

R.action(function() {
  if (R.viewportW() < "640" ) {
    detectOrientation();
      window.onorientationchange = detectOrientation;
      function detectOrientation(){
        if(typeof window.onorientationchange != 'undefined'){
          if ( (orientation >= -90) && ( orientation <= 180) )  {
            $("#selector").backstretch("/images/to-backstretch.jpg");
          }
        }
      }
   }
}

Shouldn't this be part of Response.js?

Thanks in advance.

Response.affix anyone?

Response.affix is an array utility that was used within some of the other methods. But since version 0.2.7 it is no longer needed within the library, so I'm considering removing it in the next version. Any objections? I think we should keep the lib as small as possible, but if you think it would be useful to keep...

Response.affix = function(prefix, array, suffix) {
    if ( !prefix || !$.isArray(array) ) { return false; } // Quit if args are wrong.
    var suffix = suffix || '';
    return $.map( array, function(value) { return prefix + value + suffix; } ) // Affix each value and return array.
};// Response.affix

Image refetched when window is resized

I have a weird issue I can't figure out. I have the following code:

<div class='atv tablet' data-r769="<img src='/img/atv.png'/>"></div>

So when my screen width hits 769px, the atv image is loaded into the div. Works perfectly. However I've noticed that if I resize my browser window, making is smaller then wider, then smaller then wider, etc.... each time the 769px breakpoint is hit, the browser loads the file again. However it's cached, so it doesn't actually download it again, but it still tries to fetch it and gets a 304 not modified response:

You can see the atv.png file loaded multiple times from when I was resizing the window back and forth.

I have yet to be able to recreate this problem on jsfiddle and my current code is on a private server. Any clues as to why this would be happening?

Here is my Response code:

Response.create({
    prop: "width",
    prefix: "r",
    breakpoints: [0, 769, 1025]
});

Using breakpoints measured in ems

It seems pretty standard to define your breakpoints in ems rather than pixels these days. Is this something that response.js will support?

Markup Mode not working

Look at this example:

http://jsfiddle.net/zmU9n/

The markup mode is copy/pasted from responsejs.com. The resulting markup does not show up at all. It has a css height of 0px. Even after manually changing the css height to 100px, there is still no markup showing up.

Am I doing something wrong? Also note: The responsejs breakpoints are added to the body already under the "Fiddle Options" button.

How to configure two sets for one div?

Here are my breakpoints:

<body data-responsejs='{ 
    "create": [
        { "prop":"device-pixel-ratio", "prefix": "density", "breakpoints":[0, 1, 1.5] }
      , { "prop":"width", "breakpoints":[0, 320, 1025] }
    ]}'
>

How to write the html to show images which are retina 1.5 and 1025px?

I can't figure it out!

Denote Variants in JSON

For Response 1.0, I think JSON may a more resilient way to denote variants in the long term, and would alleviate some of the complexity involved in defining breakpoint sets.

<img src="example-default.png" alt="default example" data-response-attr='{
    "src": {"480":"example-medium.png", "1280":"example-huge.png"}
}'>

This could also accommodate attributes other than [src]:

<img src="example-default.png" alt="default example" data-response-attr='{
    "src": {"480":"example-medium.png", "1280":"example-huge.png"}
  , "alt": {"480":"medium example",     "1280":"huge example"}
}'>

For insertions:

<div data-response-html='{"480":"example medium", "1280":"example huge"}'>
    example default
</div>

Non-numeric keys could also be used:

<div data-response-html='{"medium":"example medium", "huge":"example huge"}'>
    example default
</div>

iDangerous swiper + Response + offscreen content ; layout not updated.

I'm using Response to load images inside an iDangerous.swiper carousel. The images that are visible when the page loads are properly displayed based on screen size, but when scrolling to off-screen content, these images' src are always the initial value - they do not get updated to adapt to screen size. Manually resizing the window "fixes" this.

Is there a way to force Response to update or redraw from code? I could put this in iDangerous.swiper's onscroll callback as a workaround. Thanks.

Set other classes/properties at breakpoint?

There is a case where simply swapping a class name or two and maybe setting/unsetting the placeholder property on input elements would sufficiently mobile-ize a form I have.

I do not want to overwrite the DOM/innerHTML of the form, because if the user re-sizes their window while filling out the form, I understand their data would be lost. (Not to mention it’s a ridiculous HTML weight overhead for what I want to achieve).

Is there a way to do this using response.js? As far as I could tell, either of these would work:

  • Ability to declaratively set properties (besides src) on elements for various breakpoints, and add/remove classes
  • Or, ability to run a function when a breakpoint is crossed / on initialization, so I could write script to do this myself

Thoughts?

consistency in the API

In February (version 0.3.0) I added the dimensions to the main API. They're all methods (function calls) with the exception of deviceW, deviceH, deviceMax, and deviceMin properties (all 4 are integers). In retrospect, for consistency, I think I should have made those methods rather than properties (so they would require parens like the others). Since these were recent additions, I'm leaning towards making this change in version 0.5.0. In which case anyone who had used those 4 props in their code would have to update them to include parens. This probably would only affect a few people. I'd rather straighten this out now then wish I did down the line. Does that make sense?

If prefix property ends with a hyphen, script changes src attrib to 'null'

Just using this code:

R.create({
    "prop": "width",
    "prefix": "src- src",
    "breakpoints": [320, 481, 641, 961, 1025, 1281]
});

Where R is within a closure, and alias to Response.

If the prefix property reads "src- src" (to make data-src320 and data-src-320 work for example) it works fine, but if the prefixes are swapped around thus:

R.create({
    "prop": "width",
    "prefix": "src src-",
    "breakpoints": [320, 481, 641, 961, 1025, 1281]
});

The src attributes, when changed by Response, are changed to read 'null'

Just a little thing, and mostly I'm posting this so users can spot this issue if it occurs for them.

Deprecate utils

As of the forthcoming 0.9.0 release, all utility methods deprecated. See #19 for context.

0.9 may be the last release to include all these

  • Response.access
  • Response.action
  • Response.affix
  • Response.camelize
  • Response.datatize
  • Response.dataset
  • Response.deletes
  • Response.each
  • Response.map
  • Response.merge
  • Response.object
  • Response.ready
  • Response.resize
  • Response.render
  • Response.route
  • Response.target
  • Response.sift
  • Response.store

Migration and rationale

  • A few of these may remain in a reduced or different form but won't be in the public API.
  • Dataset utils are available as a separate library called dope.
  • Based on the lack of related issues, most people don't use most of these.
  • Most of these should never have been documented. Removing them will help move forward.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.