Skip to content

Instantly share code, notes, and snippets.

@MollsAndHersh
Forked from guregu/fix-image-maps.js
Created October 8, 2021 20:48
Show Gist options
  • Select an option

  • Save MollsAndHersh/cf0ba75d1de02052cc6bda7029121e64 to your computer and use it in GitHub Desktop.

Select an option

Save MollsAndHersh/cf0ba75d1de02052cc6bda7029121e64 to your computer and use it in GitHub Desktop.
Responsive image maps (vanilla JS)
function fixImageMaps(force) {
var imgs = document.querySelectorAll("img[usemap]");
[].forEach.call(imgs, function(img) {
if (!img.naturalHeight) { return; }
var h = img.height / img.naturalHeight;
var w = img.width / img.naturalWidth;
var map = document.getElementsByName(img.useMap.slice(1))[0];
if (!map) { return; }
for (var i = 0; i < map.children.length; i++) {
var area = map.children[i];
if (!area.coords) { continue; }
var coords = area.coords;
if (!area.originalCoords) {
area.originalCoords = coords;
} else {
coords = area.originalCoords;
}
var split = coords.split(",")
var fixed = "";
split.forEach(function(coord, n) {
if (n != 0) { fixed += ","; }
fixed += n % 2 == 0 ? Number(coord) * w : Number(coord) * h;
})
area.coords = fixed;
}
});
}
window.onresize = fixImageMaps;
window.onload = fixImageMaps;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment