Created
June 23, 2014 14:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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