Skip to content

Instantly share code, notes, and snippets.

@terkel
Created June 23, 2014 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terkel/a093696931fa38f55ae6 to your computer and use it in GitHub Desktop.
Save terkel/a093696931fa38f55ae6 to your computer and use it in GitHub Desktop.
Show/hide icon labels using media queries. Demo: http://terkel.jp/demo/responsive-icon-label/demo.html
/**
* Show/hide icon labels using media queries.
*
* @param {Object} images NodeList of icon images
* @param {String} mqString Media query string
* @param {Boolean} [fallback] Show label text for no-media-queries browsers
* @example
* var navIcons = document.querySelectorAll('nav img');
* responsiveIconLabel(navIcons, '(min-width: 801px)', true);
*/
function responsiveIconLabel (images, mqString, fallback) {
var mqSupported = window.matchMedia && window.matchMedia('only all').matches,
textTemplate = document.createElement('span'),
mql,
mqListeners = [],
i,
len;
textTemplate.className = 'text';
for (i = 0, len = images.length; i < len; i++) {
(function (img) {
var alt = img.alt,
txt = textTemplate.cloneNode(false);
img.parentNode.insertBefore(txt, img.nextSibling);
if (mqSupported) {
mqListeners.push(swapAltText);
} else if (fallback) {
swapAltText(true);
}
function swapAltText (match) {
if (match) {
img.alt = '';
txt.innerHTML = alt;
} else {
img.alt = alt;
txt.innerHTML = '';
}
}
})(images[i]);
}
if (mqSupported) {
mql = window.matchMedia(mqString);
mql.addListener(updateIconLabel);
updateIconLabel(mql);
}
function updateIconLabel (mql) {
var i,
len,
match = mql.matches;
for (i = 0, len = images.length; i < len; i++) {
mqListeners[i](match);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment