Scalable Image Map JS - javascript

I've looked at the other posts and have followed various ones, but can't get this to work.
I have an image which I need to turn into an image map (hotspot) that I will then embed into a WordPress post (irrelevant, but here for context).
I used the following site to generate supposedly 'responsive' code for this image map: https://image-map.weebly.com/
The code generated was as follows:
<img src="http://teaching-and-learning.co.uk/wp-content/uploads/2020/01/LessonBuilder.png" id="map-image" style="width: 75%; max-width: 100%; height: auto;" alt="" usemap="#map" />
<map name="map">
<area shape="rect" coords="927, 1870, 1440, 2226" href="https://www.teaching-and-learning.co.uk/lesson-end" target="" alt=" alt="End" title="End" />
<area shape="rect" coords="1460, 1872, 1901, 2227" href="https://www.teaching-and-learning.co.uk/check-understanding" target="_blank" alt="Check Understanding" title="Check Understanding" />
<area shape="poly" coords="716, 1871, 539, 2227, 911, 2227, 910, 1872" href="https://www.teaching-and-learning.co.uk/questioning-feedback" target="_blank" alt="Questioning & Feedback" title="Questioning & Feedback" />
<area shape="poly" coords="248, 1397, 419, 1481, 613, 1582, 617, 1846, 639, 1870, 702, 1871, 523, 2224, 392, 2174, 315, 2096, 267, 2015, 248, 1940, 244, 1831" href="https://www.teaching-and-learning.co.uk/differentiate" target="_blank" alt="Differentiate" title="Differentiate" />
<area shape="poly" coords="582, 1101, 488, 1117, 365, 1180, 290, 1268, 253, 1380, 606, 1554, 1210, 1456, 1211, 1102" href="https://www.teaching-and-learning.co.uk/main-activity" target="_blank" alt="Main Activity" title="Main Activity" />
<area shape="rect" coords="1228, 697, 1676, 1456" href="https://www.teaching-and-learning.co.uk/effective-instructions" target="_blank" alt="Effective Instructions" title="Effective Instructions" />
<area shape="rect" coords="1227, 57, 1675, 686" href="https://www.teaching-and-learning.co.uk/progress-indicators" target="_blank" alt="Progress Indicators" title="Progress Indicators" />
<area shape="rect" coords="463, 57, 1209, 403" href="https://www.teaching-and-learning.co.uk/lesson-template" target="_blank" alt="SMART Lesson Template" title="SMART Lesson Template" />
</map>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="imageMapResizer.js"></script>
<script>$(document).ready(function(e){$("map").imageMapResize();});</script>
I have created the referenced js file in the same directory. If I comment out that imageMapResizer.js file, the image map works as expected when the image is at full size. However, as soon as the js file is enabled, the image map is completely wrong, even when the image is at full size. Changing the width of the image to, for example, 75% doesn't fix the issue either.

The resource you've provided for responsive image maps actually works. I've added the contents of the imageMapResizer.js file and fixed the coordinates of the first area tag, the one for the SMART lesson template. I've tested the responsiveness by changing the width of the main image and it seems to be working just fine.
You have to recalculate and reset the coordinates of the different areas in order to get it working. The coordinate measurement should be done at full scale.
See for yourself and play around with the smart lesson template mapping:
<img src="http://teaching-and-learning.co.uk/wp-content/uploads/2020/01/LessonBuilder.png" id="map-image" style="width: 30%; max-width: 100%; height: auto;" alt="" usemap="#map" />
<map name="map">
<area shape="rect" coords="927, 1870, 1440, 2226" href="https://www.teaching-and-learning.co.uk/lesson-end" target="" alt=" alt="End" title="End" />
<area shape="rect" coords="1460, 1872, 1901, 2227" href="https://www.teaching-and-learning.co.uk/check-understanding" target="_blank" alt="Check Understanding" title="Check Understanding" />
<area shape="poly" coords="716, 1871, 539, 2227, 911, 2227, 910, 1872" href="https://www.teaching-and-learning.co.uk/questioning-feedback" target="_blank" alt="Questioning & Feedback" title="Questioning & Feedback" />
<area shape="poly" coords="248, 1397, 419, 1481, 613, 1582, 617, 1846, 639, 1870, 702, 1871, 523, 2224, 392, 2174, 315, 2096, 267, 2015, 248, 1940, 244, 1831" href="https://www.teaching-and-learning.co.uk/differentiate" target="_blank" alt="Differentiate" title="Differentiate" />
<area shape="poly" coords="582, 1101, 488, 1117, 365, 1180, 290, 1268, 253, 1380, 606, 1554, 1210, 1456, 1211, 1102" href="https://www.teaching-and-learning.co.uk/main-activity" target="_blank" alt="Main Activity" title="Main Activity" />
<area shape="rect" coords="1228, 697, 1676, 1456" href="https://www.teaching-and-learning.co.uk/effective-instructions" target="_blank" alt="Effective Instructions" title="Effective Instructions" />
<area shape="rect" coords="1803, 57, 1975, 686" href="https://www.teaching-and-learning.co.uk/progress-indicators" target="_blank" alt="Progress Indicators" title="Progress Indicators" />
<area shape="rect" coords="674, 81, 1760, 583" href="https://www.teaching-and-learning.co.uk/lesson-template" target="_blank" alt="SMART Lesson Template" title="SMART Lesson Template" />
</map>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
/*! Image Map Resizer (imageMapResizer.min.js ) - v0.5.3 - 2015-01-29
* Desc: Resize HTML imageMap to scaled image.
* Copyright: (c) 2015 David J. Bradshaw - dave#bradshaw.net
* License: MIT
*/
! function() {
"use strict";
function a() {
function a() {
function a(a) {
function c(a) {
return a * b[1 === (d = 1 - d) ? "width" : "height"]
}
var d = 0;
return a.split(",").map(Number).map(c).map(Math.floor).join(",")
}
for (var b = {
width: i.width / j.width,
height: i.height / j.height
}, c = 0; g > c; c++) f[c].coords = a(h[c])
}
function b() {
j.onload = function() {
(i.width !== j.width || i.height !== j.height) && a()
}, j.src = i.src
}
function c() {
function b() {
clearTimeout(k), k = setTimeout(a, 250)
}
window.addEventListener ? window.addEventListener("resize", b, !1) : window.attachEvent && window.attachEvent("onresize", b)
}
function d(a) {
return a.coords.replace(/ *, */g, ",").replace(/ +/g, ",")
}
var e = this,
f = e.getElementsByTagName("area"),
g = f.length,
h = Array.prototype.map.call(f, d),
i = document.querySelector('img[usemap="#' + e.name + '"]'),
j = new Image,
k = null;
b(), c()
}
function b() {
function b(b) {
if (!b.tagName) throw new TypeError("Object is not a valid DOM element");
if ("MAP" !== b.tagName.toUpperCase()) throw new TypeError("Expected <MAP> tag, found <" + b.tagName + ">.");
a.call(b)
}
return function(a) {
switch (typeof a) {
case "undefined":
case "string":
Array.prototype.forEach.call(document.querySelectorAll(a || "map"), b);
break;
case "object":
b(a);
break;
default:
throw new TypeError("Unexpected data type (" + typeof a + ").")
}
}
}
"function" == typeof define && define.amd ? define([], b) : "object" == typeof exports ? module.exports = b() : window.imageMapResize = b(), "jQuery" in window && (jQuery.fn.imageMapResize = function() {
return this.filter("map").each(a).end()
})
}();
//# sourceMappingURL=imageMapResizer.map
</script>
<script>
$(document).ready(function(e) {
$("map").imageMapResize();
});
</script>

Related

Changing img using an event onclick function using javascript -- resolved

I'm having a hard time understanding why my page won't change every time I click on a specific attribute.
I have my html of where my first image is located:
<!-- Face Column Starts -->
<div class="col-md-4">
<div class="float-right" id="face">
<!-- Image size: 587 width x 419 height -->
<img src="../static/images/face.png" alt="" width="350" usemap="#facemap" href="#face" class="face" onlick="changeProduct()">
<map name="facemap">
<div class="blush">
<area shape="circle" coords="260,185,25" href="#blush" alt="blush" onclick="changeProduct()">
<area shape="circle" coords="100,185,25" href="#blush" alt="blush" onclick="changeProduct()">
</div>
<div class="eyeshadow">
<area alt="eyeshadow" id="right" href="#eyeshadow" shape="poly" coords="222,116,230,102,245,90,265,83,286,84,318,100,312,109,290,98,259,100,222,116 " onclick="changeProduct()">
<area alt="eyeshadow" id="left" href="#eyeshadow" shape="poly" coords="133,116,113,106,78,97,45,105,38,104,65,80,89,80,90,81,97,83,105,86,133,116" onclick="changeProduct()">
</div>
<div class="eyeliner">
<area alt="eyeliner" id="right" href="#eyeliner" shape="poly" coords="220,118,259,100,275,100,295,100,305,105,315,110,300,115,275,122,259,124,222,118 " onclick="changeProduct()">
<area alt="eyeliner" id="left" href="#eyeliner" shape="poly" coords="131,118,113,106,78,97,42,107,65,120,89,126,105,124,133,118" onclick="changeProduct()">
</div>
<area class="foundation" shape="rect" coords="0,419,587,0" href="#foundation" alt="foundation" onclick="changeProduct()">
</map>
</div>
</div>
<!-- Face Column Ends -->
I used a map so that I can click on different regions of the face. When I do that, I'd like it to alternate between a different picture.
This is what I used in my javascript file:
var image = document.getElementById("face");
function changeProduct() {
if (image.getAttribute('alt') == "blush") {
image.src = "../images/blush.png";
} else if (image.getAttribute('alt') === "foundation") {
image.src = "../images/foundation.png";
} else if (image.getAttribute('alt') === "eyeshadow") {
image.src = "../images/eyeshadow.png";
} else {
image.src = "../images/eyeliner.png";
}
}
Expected output: When I click on the blush (cheeks) my image goes from face! to blush!
However, I see no change.
Can someone please help clarify what I'm doing wrong?
UPDATE: I tried a different method and got the correct result from what I wanted, I created 4 different variables for each instance and added an event listener click function rather than the HTML onclick. for anyone who may have a similar problem in the future, here is how I solved my error:
var foundationListen = document.querySelectorAll("[alt='foundation']");
for(var i=0; i < foundationListen.length; i++){
foundationListen[i].addEventListener("click", function(){
var image = document.querySelector("div#face img");
image.src = "../static/images/foundation.png";
});
};
Thank you to those in the comments that helped!!
You're changing the div src instead of the image
Change this line
var image = document.getElementById("face");
to select the image element instead as such
var image = document.querySelector("div#face img");
Note: You might need to change the function to have argument instead as #flowtron said, something like
function changeProduct(alt) {
if(!alt) return;
image.src = `../image/${alt}.png`;
}
And use it as below
<area shape="circle" coords="260,185,25" href="#blush" alt="blush" onclick="changeProduct('blush')">
<area shape="circle" coords="100,185,25" href="#blush" alt="blush" onclick="changeProduct('blush')">
<!-- And so on. You get the idea -->
If you use your above function however, you need to call changeProduct(this) and the element in if check needs to be the area element (this) alt attribute
function changeProduct(areaElem){
const alt = areaElem.getAttribute('alt');
if(alt === 'blush'){
image.src = ...
}
// And so on
}
Your selector is img not div.
Please replace the line - var image = document.getElementById("face");
with this one - var image = document.getElementById("face").getElementsByTagName('img')[0];
See the working example below
function changeProduct() {
var image = document.getElementById("face").getElementsByTagName('img').length > 0 ? document.getElementById("face").getElementsByTagName('img')[0] : document.getElementById("face").getElementsByTagName('area')[0];
if (image.getAttribute('alt') == "blush") {
image.src = "../image/blush.png";
} else if (image.getAttribute('alt') === "foundation") {
image.src = "../image/foundation.png";
} else if (image.getAttribute('alt') === "eyeshadow") {
image.src = "../image/eyeshadow.png";
} else {
image.src = "../image/eyeliner.png";
}
}
<!-- Face Column Starts -->
<div class="col-md-4">
<div class="float-right" id="face">
<!-- Image size: 587 width x 419 height -->
<img src="../static/images/face.png" alt="img" width="350" usemap="#facemap" href="#face" class="face" onlick="changeProduct()">
<map name="facemap">
<div class="blush">
<area shape="circle" coords="260,185,25" href="#blush" alt="blush" onclick="changeProduct()">
<area shape="circle" coords="100,185,25" href="#blush" alt="blush" onclick="changeProduct()">
</div>
<div class="eyeshadow">
<area alt="eyeshadow" id="right" href="#eyeshadow" shape="poly" coords="222,116,230,102,245,90,265,83,286,84,318,100,312,109,290,98,259,100,222,116 " onclick="changeProduct()">
<area alt="eyeshadow" id="left" href="#eyeshadow" shape="poly" coords="133,116,113,106,78,97,45,105,38,104,65,80,89,80,90,81,97,83,105,86,133,116" onclick="changeProduct()">
</div>
<div class="eyeliner">
<area alt="eyeliner" id="right" href="#eyeliner" shape="poly" coords="220,118,259,100,275,100,295,100,305,105,315,110,300,115,275,122,259,124,222,118 " onclick="changeProduct()">
<area alt="eyeliner" id="left" href="#eyeliner" shape="poly" coords="131,118,113,106,78,97,42,107,65,120,89,126,105,124,133,118" onclick="changeProduct()">
</div>
<area class="foundation" shape="rect" coords="0,419,587,0" href="#foundation" alt="foundation" onclick="changeProduct()">
</map>
</div>
</div>
<!-- Face Column Ends -->
using the onclick method didn't work for me so I attached click listeners to each attribute I wanted to click on and just changed the image source. here is the code that worked for me!
var foundationListen = document.querySelectorAll("[alt='foundation']");
for(var i=0; i < foundationListen.length; i++){
foundationListen[i].addEventListener("click", function(){
var image = document.querySelector("div#face img");
image.src = "../static/images/foundation.png";
});
};

How to put multiple elements in columns

I'm making a map of the United States where when you click on a state, you have to answer the state capital. I am using 3 columns to keep track of the answers. One column is correct answers, the second is incorrect, and the third is states unanswered. I have it set up so far that when an answer is correct it can go into the first column, and same with the second column. Unfortunately, I don't know how to make all of the state names start in the third "unanswered column". Here is my code so far:
var alts = "";
function loadMap() {
var map = document.getElementById("statemap");
map.addEventListener("click", function(evt) {
var alt = evt.target.alt;
alts = alt;
var id = evt.target.id;
ids = id;
document.getElementById('divIdMessage').innerHTML = "What is the capital of " + evt.target.id + "?";
});
}
function shows() {
document.getElementById("divIdMessage").innerHTML = "Click on a state to get started."
}
function show() {
document.getElementById("text").value = "";
document.getElementById('divIdAnswer').innerHTML = "";
}
function checkAnswer() {
if (!alts) {
document.getElementById("divIdAnswer").innerHTML = "Must click on a state first.";
return;
}
var submittedAnswer = document.getElementById('text').value;
var correctAnswer = alts;
if (submittedAnswer == correctAnswer) {
document.getElementById('divIdAnswer').innerHTML = "Good job, that is correct!";
document.getElementById('divCorrect').innerHTML += ids + "<br>";
} else if (submittedAnswer != correctAnswer) {
document.getElementById('divIdAnswer').innerHTML = "I'm sorry, that is incorrect. The correct answer is: " + alts + ".";
document.getElementById('divIncorrect').innerHTML += ids + "<br>"
}
alts = "";
}
.column {
float: left;
position: relative;
width: 300px;
height: 200px;
border: 0px;
box-sizing: border-box;
}
body {
padding: 10 px;
text-align: center;
background_color: #GF5D89
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
<body onload="loadMap(); shows()">
<h1>Do you know the capitals of each of the United States of America?</h1>
<h2>Use this map to test your knowledge.</h2>
<img src="http://www.conceptdraw.com/How-To-Guide/picture/Geo-Map--USA.png" width="819" height="492" alt="States" usemap="#statemap">
<map id="statemap" name="statemap">
<area shape="rect" coords="30,80,120,130" id="Oregon" alt="Salem" onClick="show()"/>
<area shape="rect" coords="60,70,130,20" id="Washington" alt="Olympia" onClick="show()" />
<area shape="rect" coords="80,170,130,220" id="Nevada" alt="Carson City" onClick="show()" />
<area shape="rect" coords="125,110,185,150" id="Boise" alt="Idaho" onClick="show()" />
<area shape="rect" coords="180,50,260,100" id="Montana" alt="Helena" onClick="show()"/>
<area shape="rect" coords="200,125,280,185" id="Wyoming" alt="Cheyenne" onClick="show()" />
<area shape="rect" coords="50,380,130,430" id="Alaska" alt="Juno" onClick="show()" />
<area shape="rect" coords="140,180,210,250" id="Utah" alt="U" onClick="show()" />
<area shape="rect" coords="130,260,190,330" id="Arizona" alt="A" onClick="show()" />
<area shape="rect" coords="215,195,300,255" id="Colorado" alt="Colorado" onClick="show()" />
<area shape="rect" coords="205,260,280,350" id="New Mexico" alt="New Mexico" onClick="show()" />
<area shape="rect" coords="330,270,410,320" id="Oklahoma" alt="Oklahoma" onClick="show()" />
<area shape="rect" coords="420,275,470,340" id="Arkansas" alt="Arkansas" onClick="show()" />
<area shape="rect" coords="310,220,410,270" id="Kansas" alt="Kansas" onClick="show()" />
<area shape="rect" coords="410,230,470,275" id="Missouri" alt="Missouri" onClick="show()" />
<area shape="rect" coords="310,170,390,220" id="Nebraska" alt="Nebraska" onClick="show()" />
<area shape="rect" coords="290,110,380,160" id="South Dakota" alt="South Dakota" onClick="show()" />
<area shape="rect" coords="390,150,450,200" id="Iowa" alt="Iowa" onClick="show()" />
<area shape="rect" coords="290,50,380,100" id="North Dakota" alt="North Dakota" onClick="show()" />
<area shape="rect" coords="380,60,440,150" id="Minnesota" alt="Minnesota" onClick="show()" />
<area shape="rect" coords="280,320,390,430" id="Texas" alt="Texas" onClick="show()" />
<area shape="rect" coords="420,370,490,400" id="Louisiana" alt="Louisiana" onClick="show()" />
<area shape="rect" coords="195,410,280,490" id="Hawaii" alt="Hawaii" onClick="show()" />
<area shape="rect" coords="20,210,90,250" id="California" alt="California" onClick="show()" />
</map>
<div id="divIdMessage"></div>
<br>
<textarea id="text" style="text-align:center; margin: 0 auto">Type answer here</textarea>
<br>
<br>
<input type="button" id="myBtn" value="Check Answer" style="text-align:center; margin: 0 auto" onClick="checkAnswer()">
<br>
<br>
<div id="divIdAnswer"></div>
<br>
<div class="row">
<div class="column" style="background-color:#aaa;">
<h3>Correct Answers</h3>
<p id="divCorrect"></p>
</div>
<div class="column" style="background-color:#bbb">
<h3>Incorrect Answers</h3>
<p id="divIncorrect"></p>
</div>
<div class="column" style="background-color:#ccc;">
<h3>No Answers</h3>
<p id="divNone"></p>
</div>
<br>
</div>
</body>
You can use a for-loop to iterate through #statesmap's children:
var unansColumn = document.getElementById("divNone");
var states = document.getElementById("statemap").children;
var stateName;
var tmpStateDiv;
for (var i = 0; i < states.length; i++) {
state = states[i];
stateName = state.getAttribute('id');
tmpStateDiv = document.createElement('DIV');
tmpStateDiv.setAttribute('id', 'unanswered' + stateName);
tmpStateDiv.appendChild(document.createTextNode(stateName));
unansColumn.appendChild(tmpStateDiv);
}
An advantage of this approach is that it doesn't just work for the US; if you changed the map to a map of Canada, and updated your #statesmap div to list the Canadian states instead, it should work just fine with no modifications.
var alts = "";
function resetColumns() {
var state;
var stateName;
var tmpStateDiv;
var states = document.getElementById('statemap').children;
var corColumn = document.getElementById('divCorrect');
var incorColumn = document.getElementById('divIncorrect');
var unansColumn = document.getElementById('divNone');
corColumn.innerHTML = '';
incorColumn.innerHTML = '';
for (var i = 0; i < states.length; i++) {
state = states[i];
stateName = state.getAttribute('id');
//unansColumn.innerHTML += "<div id= \"" + state.getAttribute('id') + "\">" + state.getAttribute('id') + "</div>"; <-- bad code, bad bjonnfesk
/*----------------------*/
//instead, do:
tmpStateDiv = document.createElement('DIV'); //create a new element of type div, into which we will put the name of the state we are processing...
tmpStateDiv.setAttribute('id', 'unanswered' + stateName); //set its id to 'unanswered' + name of the state, for instance 'unansweredOregon' (to avoid an id conflict). It needs to have an id so that we can remove it later, when the state is answered.
tmpStateDiv.appendChild(document.createTextNode(stateName)); //write the name of the state to the element
unansColumn.appendChild(tmpStateDiv); //finally, add the entire div element to the list of unanswered states
}
}
function removeFromUnanswered(id) {
var unansweredStates = document.getElementById('divNone');
//unansweredStates.removeChild(unansweredStates.querySelector('#' + id)); <--here a modification is also necessary:
unansweredStates.removeChild(unansweredStates.querySelector('#unanswered' + id)); //otherwise, since we changed the ids of the states in the unanswered column, our querySelector would not match the state when it is time for it to be removed.
}
function loadMap() {
var map = document.getElementById("statemap");
map.addEventListener("click", function(evt) {
var alt = evt.target.alt;
alts = alt;
var id = evt.target.id;
ids = id;
document.getElementById("divIdMessage").innerHTML = "What is the capital of " + evt.target.id + "?";
});
}
function shows() {
document.getElementById("divIdMessage").innerHTML = "Click on a state to get started.";
}
function show() {
document.getElementById("text").value = "";
document.getElementById("divIdAnswer").innerHTML = "";
}
function checkAnswer() {
if (!alts) {
document.getElementById("divIdAnswer").innerHTML = "Must click on a state first.";
return;
}
var submittedAnswer = document.getElementById("text").value;
var correctAnswer = alts;
if (submittedAnswer == correctAnswer) {
document.getElementById("divIdAnswer").innerHTML = "Good job, that is correct!";
document.getElementById("divCorrect").innerHTML += ids + "<br>";
} else if (submittedAnswer != correctAnswer) {
document.getElementById("divIdAnswer").innerHTML = "I'm sorry, that is incorrect. The correct answer is: " + alts + ".";
document.getElementById("divIncorrect").innerHTML += ids + "<br>";
}
alts = "";
removeFromUnanswered(ids);
}
.column {
float: left;
position: relative;
width: 300px;
height: 200px;
border: 0px;
box-sizing: border-box;
}
body {
padding: 10 px;
text-align: center;
background-color: #FF5D89;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body onload="setTimeout(function() {
loadMap();
shows();
resetColumns();
}, 1000);">
<h1>Do you know the capitals of each of the United States of America?</h1>
<h2>Use this map to test your knowledge.</h2>
<img src="http://www.conceptdraw.com/How-To-Guide/picture/Geo-Map--USA.png" width="819" height="492" alt="States" usemap="#statemap">
<map id="statemap" name="statemap">
<area shape="rect" coords="30,80,120,130" id="Oregon" alt="Salem" onClick="show()"/>
<area shape="rect" coords="60,70,130,20" id="Washington" alt="Olympia" onClick="show()" />
<area shape="rect" coords="80,170,130,220" id="Nevada" alt="Carson City" onClick="show()" />
<area shape="rect" coords="125,110,185,150" id="Boise" alt="Idaho" onClick="show()" />
<area shape="rect" coords="180,50,260,100" id="Montana" alt="Helena" onClick="show()"/>
<area shape="rect" coords="200,125,280,185" id="Wyoming" alt="Cheyenne" onClick="show()" />
<area shape="rect" coords="50,380,130,430" id="Alaska" alt="Juno" onClick="show()" />
<area shape="rect" coords="140,180,210,250" id="Utah" alt="U" onClick="show()" />
<area shape="rect" coords="130,260,190,330" id="Arizona" alt="A" onClick="show()" />
<area shape="rect" coords="215,195,300,255" id="Colorado" alt="Colorado" onClick="show()" />
<area shape="rect" coords="205,260,280,350" id="New Mexico" alt="New Mexico" onClick="show()" />
<area shape="rect" coords="330,270,410,320" id="Oklahoma" alt="Oklahoma" onClick="show()" />
<area shape="rect" coords="420,275,470,340" id="Arkansas" alt="Arkansas" onClick="show()" />
<area shape="rect" coords="310,220,410,270" id="Kansas" alt="Kansas" onClick="show()" />
<area shape="rect" coords="410,230,470,275" id="Missouri" alt="Missouri" onClick="show()" />
<area shape="rect" coords="310,170,390,220" id="Nebraska" alt="Nebraska" onClick="show()" />
<area shape="rect" coords="290,110,380,160" id="South Dakota" alt="South Dakota" onClick="show()" />
<area shape="rect" coords="390,150,450,200" id="Iowa" alt="Iowa" onClick="show()" />
<area shape="rect" coords="290,50,380,100" id="North Dakota" alt="North Dakota" onClick="show()" />
<area shape="rect" coords="380,60,440,150" id="Minnesota" alt="Minnesota" onClick="show()" />
<area shape="rect" coords="280,320,390,430" id="Texas" alt="Texas" onClick="show()" />
<area shape="rect" coords="420,370,490,400" id="Louisiana" alt="Louisiana" onClick="show()" />
<area shape="rect" coords="195,410,280,490" id="Hawaii" alt="Hawaii" onClick="show()" />
<area shape="rect" coords="20,210,90,250" id="California" alt="California" onClick="show()" />
</map>
<div id="divIdMessage"> </div>
<br>
<textarea id="text" style="text-align:center; margin: 0 auto">Type answer here</textarea>
<br>
<br>
<input type="button" id="myBtn" value="Check Answer" style="text-align:center; margin: 0 auto" onClick="checkAnswer()">
<br>
<br>
<div id="divIdAnswer"></div>
<br>
<div class="row">
<div class="column" style="background-color:#aaa;">
<h3>Correct Answers</h3>
<p id="divCorrect"></p>
</div>
<div class="column" style="background-color:#bbb">
<h3>Incorrect Answers</h3>
<p id="divIncorrect"></p>
</div>
<div class="column" style="background-color:#ccc;">
<h3>No Answers</h3>
<p id="divNone"></p>
</div>
<br>
</div>
</body>
</html>
I also took the liberty of correcting some other problems in your code, which has, among other things, caused your background-color property (misspelled as background_color) to take effect.
Edit 1: I assume you also wish to have the answered states removed from the unanswered column upon being answered. Add this function to your script, for instance just above loadMap():
function removeFromUnanswered(id) {
var unansweredStates = document.getElementById("divNone");
unansweredStates.removeChild(unansweredStates.querySelector("#unanswered" + id));
}
...and then call that function after checking the answer in checkAnswer:
function checkAnswer() {
...
alts = "";
removeFromUnanswered(ids);
}
Edit 2: Replaced bad code and improved formatting. The new code is explained by comments and is much more readable than the old code.
use a percentage width for the .column instead of a fixed wone
.column{ width : 33.33%; }
var alts = "";
function loadMap() {
var map = document.getElementById("statemap");
map.addEventListener("click", function(evt) {
var alt = evt.target.alt;
alts = alt;
var id = evt.target.id;
ids = id;
document.getElementById('divIdMessage').innerHTML = "What is the capital of " + evt.target.id + "?";
});
}
function shows() {
document.getElementById("divIdMessage").innerHTML = "Click on a state to get started."
}
function show() {
document.getElementById("text").value = "";
document.getElementById('divIdAnswer').innerHTML = "";
}
function checkAnswer() {
if (!alts) {
document.getElementById("divIdAnswer").innerHTML = "Must click on a state first.";
return;
}
var submittedAnswer = document.getElementById('text').value;
var correctAnswer = alts;
if (submittedAnswer == correctAnswer) {
document.getElementById('divIdAnswer').innerHTML = "Good job, that is correct!";
document.getElementById('divCorrect').innerHTML += ids + "<br>";
} else if (submittedAnswer != correctAnswer) {
document.getElementById('divIdAnswer').innerHTML = "I'm sorry, that is incorrect. The correct answer is: " + alts + ".";
document.getElementById('divIncorrect').innerHTML += ids + "<br>"
}
alts = "";
}
.column {
float: left;
position: relative;
width: 33.33%;
height: 200px;
border: 0px;
box-sizing: border-box;
}
body {
padding: 10 px;
text-align: center;
background-color: #GF5D89;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
<body onload="loadMap(); shows()">
<h1>Do you know the capitals of each of the United States of America?</h1>
<h2>Use this map to test your knowledge.</h2>
<img src="http://www.conceptdraw.com/How-To-Guide/picture/Geo-Map--USA.png" width="819" height="492" alt="States" usemap="#statemap">
<map id="statemap" name="statemap">
<area shape="rect" coords="30,80,120,130" id="Oregon" alt="Salem" onClick="show()"/>
<area shape="rect" coords="60,70,130,20" id="Washington" alt="Olympia" onClick="show()" />
<area shape="rect" coords="80,170,130,220" id="Nevada" alt="Carson City" onClick="show()" />
<area shape="rect" coords="125,110,185,150" id="Boise" alt="Idaho" onClick="show()" />
<area shape="rect" coords="180,50,260,100" id="Montana" alt="Helena" onClick="show()"/>
<area shape="rect" coords="200,125,280,185" id="Wyoming" alt="Cheyenne" onClick="show()" />
<area shape="rect" coords="50,380,130,430" id="Alaska" alt="Juno" onClick="show()" />
<area shape="rect" coords="140,180,210,250" id="Utah" alt="U" onClick="show()" />
<area shape="rect" coords="130,260,190,330" id="Arizona" alt="A" onClick="show()" />
<area shape="rect" coords="215,195,300,255" id="Colorado" alt="Colorado" onClick="show()" />
<area shape="rect" coords="205,260,280,350" id="New Mexico" alt="New Mexico" onClick="show()" />
<area shape="rect" coords="330,270,410,320" id="Oklahoma" alt="Oklahoma" onClick="show()" />
<area shape="rect" coords="420,275,470,340" id="Arkansas" alt="Arkansas" onClick="show()" />
<area shape="rect" coords="310,220,410,270" id="Kansas" alt="Kansas" onClick="show()" />
<area shape="rect" coords="410,230,470,275" id="Missouri" alt="Missouri" onClick="show()" />
<area shape="rect" coords="310,170,390,220" id="Nebraska" alt="Nebraska" onClick="show()" />
<area shape="rect" coords="290,110,380,160" id="South Dakota" alt="South Dakota" onClick="show()" />
<area shape="rect" coords="390,150,450,200" id="Iowa" alt="Iowa" onClick="show()" />
<area shape="rect" coords="290,50,380,100" id="North Dakota" alt="North Dakota" onClick="show()" />
<area shape="rect" coords="380,60,440,150" id="Minnesota" alt="Minnesota" onClick="show()" />
<area shape="rect" coords="280,320,390,430" id="Texas" alt="Texas" onClick="show()" />
<area shape="rect" coords="420,370,490,400" id="Louisiana" alt="Louisiana" onClick="show()" />
<area shape="rect" coords="195,410,280,490" id="Hawaii" alt="Hawaii" onClick="show()" />
<area shape="rect" coords="20,210,90,250" id="California" alt="California" onClick="show()" />
</map>
<div id="divIdMessage"></div>
<br>
<textarea id="text" style="text-align:center; margin: 0 auto">Type answer here</textarea>
<br>
<br>
<input type="button" id="myBtn" value="Check Answer" style="text-align:center; margin: 0 auto" onClick="checkAnswer()">
<br>
<br>
<div id="divIdAnswer"></div>
<br>
<div class="row">
<div class="column" style="background-color:#aaa;">
<h3>Correct Answers</h3>
<p id="divCorrect"></p>
</div>
<div class="column" style="background-color:#bbb">
<h3>Incorrect Answers</h3>
<p id="divIncorrect"></p>
</div>
<div class="column" style="background-color:#ccc;">
<h3>No Answers</h3>
<p id="divNone"></p>
</div>
<br>
</div>
</body>
Start by printing out the names of all the states. Do that by creating
an array by iterating your DOM. Print that array. When the user
submits an answer, delete that answer from your array then re-print
the array.
>
> var alts = "";
>
> function loadMap() {
> var map = document.getElementById("statemap");
> map.addEventListener("click", function(evt) {
> var alt = evt.target.alt;
> alts = alt;
> var id = evt.target.id;
> ids = id;
> document.getElementById('divIdMessage').innerHTML = "What is the capital of " + evt.target.id + "?";
> }); } var arrayUnansw=[]; function createArray(){
> var query = document.getElementsByTagName("area");
> for(var i=0;i<query.length;i++){
> arrayUnansw.push(query[i].getAttribute("id"));
> } } function printArray(){ var container = document.getElementById("divNone"); for(var
> i=0;i<arrayUnansw.length;i++){
> container.innerHTML+=arrayUnansw[i]+"<br>"; } } createArray(); printArray(); function shows() {
> document.getElementById("divIdMessage").innerHTML = "Click on a state to get started."
>
> }
>
> function show() {
> document.getElementById("text").value = "";
> document.getElementById('divIdAnswer').innerHTML = ""; }
>
>
> function checkAnswer() {
> if (!alts) {
> document.getElementById("divIdAnswer").innerHTML = "Must click on a state first.";
> return;
> }
> var submittedAnswer = document.getElementById('text').value;
> var correctAnswer = alts;
> if (submittedAnswer == correctAnswer) {
> document.getElementById('divIdAnswer').innerHTML = "Good job, that is correct!";
> document.getElementById('divCorrect').innerHTML += ids + "<br>";
>
> } else if (submittedAnswer != correctAnswer) {
> document.getElementById('divIdAnswer').innerHTML = "I'm sorry, that is incorrect. The correct answer is: " + alts + ".";
> document.getElementById('divIncorrect').innerHTML += ids + "<br>"
> }
> var index = arrayUnansw.indexOf(ids);
> console.log(index);
> if(index!==-1)arrayUnansw.splice(index,1);
> document.getElementById("divNone").innerHTML="";
> printArray();
> alts = "";
>
> }
>
> <style>
> .column {
> float: left;
> position: relative;
> width: 300px;
> height: 200px;
> border: 0px;
> box-sizing: border-box;
> }
>
> body {
> padding: 10 px;
> text-align: center;
> background_color: #GF5D89
> font-family: "Trebuchet MS", Helvetica, sans-serif;
> }
> }
> </style>
>
>
>
> <body onload="loadMap(); shows()">
> <h1>Do you know the capitals of each of the United States of America?</h1>
> <h2>Use this map to test your knowledge.</h2>
> <img src="http://www.conceptdraw.com/How-To-Guide/picture/Geo-Map--USA.png"
> width="819" height="492" alt="States" usemap="#statemap">
>
> <map id="statemap" name="statemap">
> <area shape="rect" coords="30,80,120,130" id="Oregon" alt="Salem" onClick="show()"/>
> <area shape="rect" coords="60,70,130,20" id="Washington" alt="Olympia" onClick="show()" />
> <area shape="rect" coords="80,170,130,220" id="Nevada" alt="Carson City" onClick="show()" />
> <area shape="rect" coords="125,110,185,150" id="Boise" alt="Idaho" onClick="show()" />
> <area shape="rect" coords="180,50,260,100" id="Montana" alt="Helena" onClick="show()"/>
> <area shape="rect" coords="200,125,280,185" id="Wyoming" alt="Cheyenne" onClick="show()" />
> <area shape="rect" coords="50,380,130,430" id="Alaska" alt="Juno" onClick="show()" />
> <area shape="rect" coords="140,180,210,250" id="Utah" alt="U" onClick="show()" />
> <area shape="rect" coords="130,260,190,330" id="Arizona" alt="A" onClick="show()" />
> <area shape="rect" coords="215,195,300,255" id="Colorado" alt="Colorado" onClick="show()" />
> <area shape="rect" coords="205,260,280,350" id="New Mexico" alt="New Mexico" onClick="show()" />
> <area shape="rect" coords="330,270,410,320" id="Oklahoma" alt="Oklahoma" onClick="show()" />
> <area shape="rect" coords="420,275,470,340" id="Arkansas" alt="Arkansas" onClick="show()" />
> <area shape="rect" coords="310,220,410,270" id="Kansas" alt="Kansas" onClick="show()" />
> <area shape="rect" coords="410,230,470,275" id="Missouri" alt="Missouri" onClick="show()" />
> <area shape="rect" coords="310,170,390,220" id="Nebraska" alt="Nebraska" onClick="show()" />
> <area shape="rect" coords="290,110,380,160" id="South Dakota" alt="South Dakota" onClick="show()" />
> <area shape="rect" coords="390,150,450,200" id="Iowa" alt="Iowa" onClick="show()" />
> <area shape="rect" coords="290,50,380,100" id="North Dakota" alt="North Dakota" onClick="show()" />
> <area shape="rect" coords="380,60,440,150" id="Minnesota" alt="Minnesota" onClick="show()" />
> <area shape="rect" coords="280,320,390,430" id="Texas" alt="Texas" onClick="show()" />
> <area shape="rect" coords="420,370,490,400" id="Louisiana" alt="Louisiana" onClick="show()" />
> <area shape="rect" coords="195,410,280,490" id="Hawaii" alt="Hawaii" onClick="show()" />
> <area shape="rect" coords="20,210,90,250" id="California" alt="California" onClick="show()" />
> </map>
> <div id="divIdMessage"></div>
> <br>
> <textarea id="text" style="text-align:center; margin: 0 auto">Type answer here</textarea>
> <br>
> <br>
> <input type="button" id="myBtn" value="Check Answer" style="text-align:center; margin: 0 auto" onClick="checkAnswer()">
> <br>
> <br>
> <div id="divIdAnswer"></div>
> <br>
> <div class="row">
> <div class="column" style="background-color:#aaa;">
> <h3>Correct Answers</h3>
> <p id="divCorrect"></p>
> </div>
> <div class="column" style="background-color:#bbb">
> <h3>Incorrect Answers</h3>
> <p id="divIncorrect"></p>
> </div>
> <div class="column" style="background-color:#ccc;">
> <h3>No Answers</h3>
> <p id="divNone"></p>
> </div>
> <br>
> </div>
> </body>
>
>
Edit: Screwed up the formatting. Sorry! But check it, it works.

Image portion highlight

I have one image which is divided into multiple sections. The requirement is, if user clicks on a particular section, the section should get highlighted. I did some exploration for the same and came across the solution of using <map> and <area> tags, also for the particular area to be highlighted, it uses maphilight feature. So it solved my first hurdle. And then now I have another requirement which says, clicking on a particular section, the color of that particular section should change on every click. Let us suppose, user clicks on section A, on the first click, it should change to red, on the second click, it should change to green and so on till four clicks. On the last click, it should change to white. The problem here is, when I click on section A, it is working as per requirement, but as soon as I click on section B, section A's highlighting gets disappear which should not happen.
Here's what I did for that:
<!Doctype HTML>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="maphighlight.js"></script>
<script type="text/javascript">
var counter = 0;
function abc(){
if(counter == 3){
$('.map').maphilight({ groupBy: 'title',fillColor: 'ffffff',fillOpacity: '0.0',strokeColor: 'ffffff', strokeOpacity: '0.0' });
counter= 0;
}else if(counter == 2){
$('.map').maphilight({ groupBy: 'title',fillColor: '3333ff',fillOpacity: '0.8',strokeColor: '3333ff' });
counter++;
}else if(counter == 1){
$('.map').maphilight({ groupBy: 'title',fillColor: '006600',fillOpacity: '0.8',strokeColor: '006600' });
counter++;
}else{
$('.map').maphilight({ groupBy: 'title',fillColor: 'ff0000',fillOpacity: '0.8',strokeColor: 'ff0000' });
counter++;
}
}
var counter1 = 0;
function abcd(){
if(counter1 == 3){
$('.map').maphilight({ groupBy: 'title',fillColor: 'ffffff',fillOpacity: '0.0',strokeColor: 'ffffff', strokeOpacity: '0.0' });
counter1= 0;
}else if(counter1 == 2){
$('.map').maphilight({ groupBy: 'title',fillColor: '3333ff',fillOpacity: '0.8',strokeColor: '3333ff' });
counter1++;
}else if(counter1 == 1){
$('.map').maphilight({ groupBy: 'title',fillColor: '006600',fillOpacity: '0.8',strokeColor: '006600' });
counter1++;
}else{
$('.map').maphilight({ groupBy: 'title',fillColor: 'ff0000',fillOpacity: '0.8',strokeColor: 'ff0000' });
counter1++;
}
}
</script>
</head>
<body>
<img src="SensorygraphicRight.jpg" alt="Planets" class="map" border="none" usemap="#planetmap" hidefocus="true" style="float:left"/>
<map name="planetmap">
<!-- For A -->
<area id="sensory" alt="" name="A" title="A" onclick="abc();" shape="poly" coords="74,256,72,298,69,336,66,367,66,383,90,386,97,317,100,289,101,255">
<area alt="" title="A" id="sensory1" shape="poly" coords="308,306,303,341,301,380,328,382,322,349,332,309" />
</area>
<!-- For B -->
<area alt="" name="B" title="B" onclick="abcd();" shape="poly" coords="101,254,101,291,97,318,92,341,92,365,91,385,114,385,117,342,123,317,129,288,131,274,132,266,140,256" >
<area alt="" title="B" shape="poly" coords="417,236,415,268,420,304,428,352,439,353,443,309,447,272,449,236" />
</area>
<!-- For C -->
<area alt="" name="C" title="C" data-maphilight='{"fillColor":"FF0000"}' shape="poly" coords="139,253,130,280,129,295,123,322,119,336,116,353,113,367,113,376,114,384,115,388,122,388,126,379,131,356,129,339,135,331,141,321,146,314,148,308,154,296,156,288,160,278,163,271,163,264,166,258,165,255,137,255" >
<area alt="" title="C" href="#" data-maphilight='{"fillColor":"FF0000"}' shape="poly" coords="451,238,440,349,467,350,476,238" />
</area>
<!-- For D -->
<area alt="" name="D" title="D" href="#" data-maphilight='{"fillColor":"FF0000"}' shape="poly" coords="61,384,62,401,56,415,53,432,52,448,53,459,54,473,55,482,62,479,70,479,85,478,82,477,82,479,79,479,84,453,88,424,88,405,90,394,90,386">
<area alt="" title="D" data-maphilight='{"fillColor":"FF0000"}' href="#" shape="poly" coords="299,381,296,423,295,461,322,460,333,427,331,401,326,383" />
</area>
</map>
</body>
</html>
By this code, I am able to change the color of clicked section on every single click, but as soon as I click on another section, previously clicked section gets back to its initial color i.e., white.
How do I achieve it? Is there any way of setting the background color for clicked area?

Using Responsive Image Map with no JQuery

I have latelly been wondering how to make a responsive image map. Sounds impossible, but I did find a way to do it http://home.comcast.net/~urbanjost/IMG/resizeimg.html
If you look at the source, you can see everything. This has no attached JQuery or Ruby, or whatever plugins people recomend to do this.
However, when I tried implementing this JS to my code, it just didn't work. I've been searching day and night but can't find a thing.
Here is the original code:
JS:
GLOBAL_COUNT = 0;
GLOBAL_AREAS = new Array();
GLOBAL_WIDTH = 1;
function scaleXY(elementid, scale) {
// avoid problems with 0 scales and image becoming so small it does not change size
// I think something breaks in firefox(1) when you shrink so much that all values in an coords= become 0
// I think something breaks in iexplore(1) when you shrink so much that all values in an coords= become 0
myscale = Math.max(0, scale);
oldwidth = document.getElementById(elementid).width
oldheight = document.getElementById(elementid).height
newwidth = Math.round(Math.max(oldwidth * myscale, 1));
newheight = Math.round(Math.max(oldheight * myscale, 1));
if(oldwidth == newwidth) newwidth =+ 1;
if(oldheight == newheight) newheight =+ 1;
document.getElementById(elementid).width = newwidth;
document.getElementById(elementid).height = newheight;
scaleArea();
}
// Assuming one image map in document.
// Assuming coordinates are comma-delimited in AREA COORDS= string.
// Assuming the same zoom factor for the height as for the width of the image.
function getglobal() { // place original AREA coordinate strings into a global array, called at load
var arrayAreas = document.body.getElementsByTagName("AREA");
GLOBAL_WIDTH = document.getElementById("myimage").width; // get original width
for(var i = 0; i < arrayAreas.length; i++) {
GLOBAL_AREAS[i]= arrayAreas[i].coords;
}
GLOBAL_COUNT++;
}
function scaleArea() { // using values stored at load, recalculate new values for the current size
var arrayAreas = document.body.getElementsByTagName("AREA");
for(var i = 0; i < arrayAreas.length; i++) {
ii = i+1;
rescale = document.getElementById("myimage").width/GLOBAL_WIDTH ;
sarray = GLOBAL_AREAS[i].split(","); // convert coordinates to a numeric array assuming comma-delimited values
var rarray =new Array();
for(var j = 0; j < sarray.length; j++) {
rarray[j] = parseInt(sarray[j])*rescale; // rescale the values
rarray[j] = Math.round(rarray[j]);
} //alert( "GLOBAL " + GLOBAL_AREAS[i] + ":" + sarray.length + " SPLIT=" + sarray +rarray.length);
arrayAreas[i].coords = rarray.join(","); // put the values back into a string
}
showArea();
}
HTML:
<body onload="getglobal();" >
<form>
<input type="button" onclick="scaleXY('myimage',1.0/1.13);" value="scaled smaller" />
<input type="button" onclick="scaleXY('myimage',1.13);" value="scaled bigger" />
</form>
<div>
<img id="myimage" src="hcopy.gif" alt="Round buttons" usemap="#circles" height="839" width="586" />
<map id="circles" name="circles" >
<area target="_blank" title="CYAN AREA" alt="CYAN" shape="circle" coords="50,50,20" href="#CYAN" />
<area target="_blank" title="BLUE AREA" alt="BLUE" shape="circle" coords="25,25,20" href="#BLUE" />
<area target="_blank" title="RED AREA" alt="RED" shape="circle" coords="25,75,20" href="#RED" />
<area target="_blank" title="MAGENTA AREA" alt="MAGENTA" shape="circle" coords="75,25,20" href="#MAGENTA" />
<area target="_blank" title="GREEN AREA" alt="GREEN" shape="circle" coords="75,75,20" href="#GREEN" />
<area target="_blank" title="YELLOW AREA" alt="YELLOW" shape="rect" coords="0,0,100,100" href="#YELLOW" />
</map>
</div>
<body>
Again, I didn't make this code. I have trouble understanding it. But the biggest problem comes when I try implementing this code to my image, then, it stopes working.
The code:
HTML:
<form onload="getglobal()">
<input type="button" onclick="scaleImageDown()" value="scaled smaller" />
<input type="button" onclick="scaleImageUp()" value="scaled bigger" />
</form>
<div>
<img src="http://www.astro-galaxy.com/sys_files/sys_view/CL1296246121697.jpg" usemap="#circles" id="myimage" width="839" height"586" >
<map name="circles" id="circles">
<area shape="circle" coords="-264,320,442" href="" title="Sun">
<area shape="circle" coords="244,79,13" href="" title="Mercury">
<area shape="circle" coords="307,122,24" href="" title="Venus">
<area shape="circle" coords="382,187,29" href="" title="Earth">
<area shape="circle" coords="414,149,14" href="" title="The Moon">
<area shape="circle" coords="432,232,16" href="" title="Mars">
<area shape="circle" coords="408,249,8" href="" title="Deimos">
<area shape="circle" coords="456,217,8" href="" title="Phobos">
<area shape="rect" coords="413,261,486,292" href="" title="Asteroids">
<area shape="circle" coords="563,337,85" href="" title="Jupiter">
<area shape="circle" coords="430,421,14" href="" title="Europa">
<area shape="circle" coords="463,395,18" href="" title="Ganymede">
<area shape="circle" coords="653,245,17" href="" title="Callisto">
<area shape="circle" coords="690,220,13" href="" title="Io">
<area shape="circle" coords="668,431,41" href="" title="Saturn">
<area shape="circle" coords="727,397,11" href="" title="Titan">
<area shape="circle" coords="734,487,21" href="" title="Uranus">
<area shape="circle" coords="684,525,10" href="" title="Umbriel">
<area shape="circle" coords="702,512,10" href="" title="Miranda">
<area shape="circle" coords="769,460,10" href="" title="Ariel">
<area shape="circle" coords="785,445,10" href="" title="Titania">
<area shape="circle" coords="802,430,10" href="" title="Oberon">
<area shape="circle" coords="784,536,27" href="" title="Neptune">
<area shape="circle" coords="757,565,10" href="" title="Triton">
<area shape="circle" coords="816,574,10" href="" title="Pluto">
</map>
</div>
JS:
GLOBAL_COUNT = 0;
GLOBAL_AREAS = new Array();
GLOBAL_WIDTH = 1;
eid = "myimage";
function scaleImageDown() {
// avoid problems with 0 scales and image becoming so small it does not change size
// I think something breaks in firefox(1) when you shrink so much that all values in an coords= become 0
// I think something breaks in iexplore(1) when you shrink so much that all values in an coords= become 0
var myscale = 0.5;
var oldwidth = document.getElementById(eid).width;
var oldheight = document.getElementById(eid).height;
var newwidth = oldwidth * myscale;
var newheight = oldheight * myscale;
if(oldwidth == newwidth) {
newwidth =+ 1
}
if(oldheight == newheight) {
newheight =+ 1
}
document.getElementById(eid).width = newwidth;
document.getElementById(eid).height = newheight;
scaleArea();
}
function scaleImageUp() {
var myscale = 2;
var oldwidth = document.getElementById(eid).width;
var oldheight = document.getElementById(eid).height;
var newwidth = oldwidth * myscale;
var newheight = oldheight * myscale;
if(oldwidth == newwidth) {
newwidth =+ 1
}
if(oldheight == newheight) {
newheight =+ 1
}
document.getElementById(eid).width = newwidth;
document.getElementById(eid).height = newheight;
scaleArea();
}
// Assuming one image map in document.
// Assuming coordinates are comma-delimited in AREA COORDS= string.
// Assuming the same zoom factor for the height as for the width of the image.
function getglobal(){ // place original AREA coordinate strings into a global array, called at load
var arrayAreas = document.body.getElementsByTagName("area");
GLOBAL_WIDTH = document.getElementById(eid).width; // get original width
for(var i = 0; i < arrayAreas.length; i++) {
GLOBAL_AREAS[i]= arrayAreas[i].coords;
}
GLOBAL_COUNT++;
}
function scaleArea() { // using values stored at load, recalculate new values for the current size
var arrayAreas = document.body.getElementsByTagName("area");
for(var i = 0; i < arrayAreas.length; i++) {
var ii = i + 1;
var rescale = document.getElementById(eid).width/GLOBAL_WIDTH ;
var sarray = GLOBAL_AREAS[i].split(","); // convert coordinates to a numeric array assuming comma-delimited values
var rarray = new Array();
for(var j = 0; j < sarray.length; j++) {
rarray[j] = parseInt(sarray[j]) * rescale; // rescale the values
rarray[j] = Math.round(rarray[j]);
} //alert( "GLOBAL " + GLOBAL_AREAS[i] + ":" + sarray.length + " SPLIT=" + sarray +rarray.length);
arrayAreas[i].coords=rarray.join(","); // put the values back into a string
}
showArea();
}
As you can see, they are pretty much the same. The only difference is that the top onw works, and the bottom one doesn't. Please help. And thank you for any explanation of how it works(Other than the basics, of course). Thanx!
A <form>element doesn't have a naturally occurring 'load' event, therefore getglobal() is not called in your version of the code.
Try reinstating <body onload="getglobal();">
Alternatively, find some other way to cause getglobal() to be called - eg in response to some user event.
How does the code work?
First, the HTML causes the DOM to be populated with :
a <form> element containing two buttons
an <img> element
an <map> element containing a number of areas
The document's <body> element has getglobal() attached to it as its onload handler, which causes several global variables to be set :
GLOBAL_WIDTH: the <img> element's initial width.
GLOBAL_AREAS: an array of the image map's initial area coords, "-264,320,442" etc.
GLOBAL_COUNT: which is set but not used.
By setting these global vars once, there's a lot less to do every time the image and its map are rescaled.
The two form buttons are each given a 'click' action by attaching onclick handlers :
"scaled smaller" - onclick="scaleImageDown()"
"scaled bigger" - onclick="scaleImageUp()"
The two functions scaleImageDown() and scaleImageUp() :
rescale the image by a factor of 0.5 or 2.
loop through the GLOBAL_AREAS array and manipulate the area nodes' coords attribute such that each of the coordinates is either divided or multiplied by 2. This has the desired effect of rescaling the entire map.
The utility function scaleArea() exists to avoid repetition of code in scaleImageDown() and scaleImageUp().

Changing img src folder from javascript imagemap

I've made an imagemap with 9 areas, using mapster. Clicking an area now results in displaying some text above the imagemap. I would like to display images from several folders instead, depending on the area that is selected. When area 'kamer1' is selected on the imagemap, I would like all images from the folder '/kamer1' to be displayed above the imagemap.
It is my first time working with JavaScript, so expect it is a simple problem for someone out there.
I've made a JSFIDDLE: http://jsfiddle.net/BTnV2/7/
HTML:
<div style="clear: both; width: 900px; height: 450px;" id="details"></div>
<img id="layout" src="http://i61.tinypic.com/2yl4spc.png" usemap="#usa" style="width:900px;height:800px;">
<map id="usa_image_map" name="usa">
<area href="#" room="kamer1" full="B&B" shape="rect" coords="50,764,143,635">
<area href="#" room="kamer2" full="B&B" shape="rect" coords="146,764,238,669">
<area href="#" room="kamer3" full="B&B" shape="rect" coords="241,764,326,669">
<area href="#" room="hal" full="B&B" shape="rect" coords="146,666,326,635">
<area href="#" room="badkamer" full="B&B" shape="rect" coords="234,632,326,574">
<area href="#" room="keuken" full="B&B" shape="poly" coords="50,632,229,632,229,570,303,570,303,508,150,508,150,540,50,540">
<area href="#" room="boven" full="B&B" shape="rect" coords="50,540,150,508">
<area href="#" room="kamer4" full="B&B" shape="rect" coords="50,505,217,392">
<area href="#" room="kamer5" full="B&B" shape="rect" coords="220,505,392,392">
</map>
JS:
var xref = {
kamer1: "<b>FOTO's van kamer 1</b>",
kamer2: "<b>FOTO's van kamer 2</b>",
kamer3: "<b>FOTO's van kamer 3</b>",
hal: "<b>FOTO's van hal</b>",
badkamer: "<b>FOTO's van badkamer</b>",
keuken: "<b>FOTO's van keuken</b>",
boven: "<b>FOTO's van boven kamer</b>",
kamer4: "<b>FOTO's van kamer 4</b>",
kamer5: "<b>FOTO's van kamer 5</b>"
};
var image = $('#layout');
image.mapster({
fillOpacity: 0.5,
fillColor: "c20000",
stroke: true,
strokeColor: "c20000",
strokeOpacity: 0.8,
strokeWidth: 3,
singleSelect: true,
mapKey: 'room',
listKey: 'room',
clickNavigate: true,
fade: false,
fadeDuration: 50,
showToolTip: true,
toolTipContainer: '<div style="clear: both; align: center;"></div>',
areas: [{
key: "kamer1",
toolTip: "Groepsaccommodatie <br> kamer 1"
}, {
key: "kamer2",
toolTip: "Groepsaccommodatie <br> kamer 2"
}, {
key: "kamer3",
toolTip: "Groepsaccommodatie <br> kamer 3"
}, {
key: "hal",
toolTip: "Groepsaccommodatie <br> hal"
}, {
key: "badkamer",
toolTip: "Groepsaccommodatie <br> badkamer"
}, {
key: "keuken",
toolTip: "Keuken en eetkamer"
}, {
key: "boven",
toolTip: "Recreatieruimte"
}, {
key: "kamer4",
toolTip: "Bed & Breakfast <br> kamer 1"
}, {
key: "kamer5",
toolTip: "Bed & Breakfast <br> kamer 2"
}],
onClick: function (e) {
$('#details').html(xref[e.key]);
}
});
var xref = {
kamer1: {
"desc":"FOTO's van kamer 1",
"images":["stoel.jpg","tafel.jpg"]
},
kamer2: {
"desc":"FOTO's van kamer 2",
"images":["image1.jpg","image2.jpg"]
}
};
// note the lack of comma on the last room
onClick: function (e) {
e.preventDefault();
var room = xref[e.key];
var html = '<b>'+room.desc+'</b><br/>';
for (var i=0;i<room.images.length;i++)
html += '<img src="'+images[i]+'" alt="image #'+(i+1)+'" />';
$('#details').html(html);
}
If you do NOT know the number or name of the images you can try this:
var xref = {
kamer1: "FOTO's van kamer 1",
kamer2: "FOTO's van kamer 2",
kamer3: "FOTO's van kamer 3"
}
onClick: function (e) {
e.preventDefault();
var html = '<b>'+xref[e.key]+'</b><br/>';
var imagePath = e.key+"/"+e.key+"_";
for (var i=1;i<=5;i++) {
html += '<img src="'+imagePath+i+'" alt="image #'+(i+1)+'"'+
' onerror="this.parentNode.removeChild(this)" />';
}
$('#details').html(html);
}

Categories