body:after {
position: absolute;
bottom: 0;
right:0;
}
.call-to-action {
margin: 3em;
padding: 1em;
background: yellow;
border-radius: 5px;
cursor: pointer;
border: 1px solid #ccc;
}
@media screen and (min-width: 0px) and (max-width: 320px) {
body:after {
content: 'less than 320px';
}
}
@media screen and (min-width: 321px) and (max-width: 768px) {
body:after {
content: 'more than 320';
}
}
JavaScript
var cache = [];
/**
* Step 1
*/
var breakpoints = {
bp1: 'screen and (min-width: 0px) and (max-width: 320px)',
bp2: 'screen and (min-width: 321px)'
//etc...
};
/**
* Step 2
*/
for ( var name in breakpoints ){
// need to scope variables in a for loop
!function(breakName, query){
// the callback
function cb(data){
// add class name associated to current breakpoint match
$( '#my-component .inner' ).toggleClass( breakName, data.matches );
// potentially do other stuff if you want...
}
// run the callback on current viewport
cb({
media: query,
matches: matchMedia(query).matches
});
// subscribe to breakpoint changes
var m = matchMedia(query);
m.addListener( cb );
cache.push(m); //fix for firefox, store a reference
}(name, breakpoints[name]);
}
/**
* Step 3
*/
$( '#my-component' )
.on({
//click events
click: function(e){
$(this).html('You clicked');
}
},
//query string to match .call-to-action but only in first breakpoint
'.bp1 .call-to-action'
)
.on({
//mouse events
mouseenter: function(e){
$(this).html('You mouseentered');
},
mouseleave: function(e){
$(this).html('You mouse...left...');
}
},
//query string to match .call-to-action on all EXCEPT first breakpoint
'.bp2 .call-to-action'
);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.