Dynamic Image Maps
by Manask Sharma
HTML
<!-- Header -->
<div class="header">
<h1>TITLE</h1>
<p>Click on the buttons to change the grid view.</p>
<button onclick="two()">2</button>
<button onclick="four()">4</button>
<button onclick="eight()">8</button>
<button onclick="sixteen()">16</button>
</div>
<div id="container">
</div>
CSS
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.imgcontainer {
width: 24%;
position: relative;
}
img {
width: 100%;
top: 0;
}
.header {
text-align: center;
padding: 32px;
position: sticky;
top: 0;
background-color: white;
}
#container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
align-content: space-between;
}
JavaScript
// Create images
var images_names = [
"https://freesvg.org/img/hitch-hike.png",
"https://freesvg.org/img/1598541745text-abstract-page-svg.png?w=150&h=150&fit=fill",
"https://cdn.pixabay.com/photo/2016/03/09/09/21/snowflake-1245748__340.jpg",
"https://cdn.pixabay.com/photo/2016/03/09/09/22/workplace-1245776__340.jpg",
"https://cdn.pixabay.com/photo/2015/03/26/09/47/sky-690293__340.jpg",
"https://cdn.pixabay.com/photo/2016/03/09/09/21/snowflake-1245748__340.jpg",
"https://cdn.pixabay.com/photo/2016/03/09/09/22/workplace-1245776__340.jpg",
"https://cdn.pixabay.com/photo/2016/03/09/09/21/snowflake-1245748__340.jpg",
"https://cdn.pixabay.com/photo/2016/03/09/09/22/workplace-1245776__340.jpg"
];
for (var i = 0; i < images_names.length; i++) {
var imgcontainer = document.createElement("div");
imgcontainer.setAttribute("class", "imgcontainer");
document.getElementById('container').appendChild(imgcontainer);
var img = document.createElement('img');
img.src = images_names[i];
img.setAttribute("usemap", `#imgmap${i}`);
imgcontainer.appendChild(img);
}
window.onload = function () {
createMaps();
}
// Create Maps
function createMaps() {
var elem = document.getElementsByClassName("imgcontainer");
for (var i = 0; i < elem.length; i++) {
var img = elem[i].children[0];
var xCord = img.width * 25 / 100;
var yCord = img.height * 25 / 100;
var radius = 10;
var imap = document.createElement("map");
imap.setAttribute("name", `imgmap${i}`);
elem[i].appendChild(imap);
var area = document.createElement("area");
area.setAttribute("shape", `circle`);
area.setAttribute("title", `Click me`);
area.setAttribute("href", `javascript:alert(1);`);
area.setAttribute("coords", `${xCord},${yCord},${radius}`);
imap.appendChild(area);
}
}
// Geometry functions
function two() {
var i;
var elements =...