Skip to content

Instantly share code, notes, and snippets.

@guregu
Created October 17, 2017 14:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save guregu/e9f9caaed4b264a9214799bf03a06946 to your computer and use it in GitHub Desktop.
Save guregu/e9f9caaed4b264a9214799bf03a06946 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;
@Raefat
Copy link

Raefat commented May 30, 2022

Thanks so Much :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment