Using Responsive Image Map with no JQuery - javascript

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().

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";
});
};

Scalable Image Map JS

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>

I want to hide all other div's when i click on one div

I am making a software were i need to hide all other div's when i click on another div. what happens now is that the div's just stack on top of each other. and the div only dissapears when i click the same div again.
i already tried some of the JavaScript and jQuery code on this platform but can't quite figure it out myself.
--- THIS IS THE SCRIPT IM USING TO SHOW AND HIDE THE DIV'S ---
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
</head>
<body>
--- THESE ARE MY CLICKABLE AREA'S WHERE THE USER CAN CLICK ON TO SHOW AND HIDE A DIV ---
<div class="div-voog" id=""> <img class="map" src="images/tekening-oog-vrouw-550px.jpg" alt="" usemap="#Map" />
<map name="Map" id="Map">
<area onclick="toggle_visibility('vooglid');" alt="" title="" href="#" shape="poly" coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
<area onclick="toggle_visibility('vwimpers');" alt="" title="" href="#" shape="poly" coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
<area onclick="toggle_visibility('vwenkbrauw');" alt="" title="" href="#" shape="poly" coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
<area onclick="toggle_visibility('vooghoek');" alt="" title="" href="#" shape="poly" coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />
</map>
</div>
--- AND THESE ARE MY DIV'S CONTAINING THE INFORMATION IT HAS TO SHOW AND HIDE ---
<div class="test" id="vooglid"> Symptoom ooglid</div>
<div class="test22" id="vwimpers"> Symptoom wimper</div>
<div class="test33" id="vwenkbrauw"> Symptoom wenkbrauw</div>
<div class="test44" id="vooghoek"> Symptoom ooghoek</div>
</body>
</html>
I want the result to be that when I click one of the areas above, the corresponding div shows and all other divs hide.
You need to first hide all the other elements, so that then you can show the one you want to see. You could change all of them to have the class="test" and then prepend to your script something like this:
var tests = document.getElementsByClassName("test");
for (i = 0; i < tests.length; i++) {
tests[i].style.display = "none";
}
UPDATE
The full script would be something like this:
<script>
function toggle_visibility(el) {
var tests = document.getElementsByClassName("test");
for (i = 0; i < tests.length; i++) {
tests[i].style.display = "none";
}
el.style.display = "block";
}
</script>
And the html:
<div>
<area class="test" onclick="toggle_visibility(this)">A</div>
<area class="test" onclick="toggle_visibility(this)">B</div>
<area class="test" onclick="toggle_visibility(this)">C</div>
<area class="test" onclick="toggle_visibility(this)">D</div>
</div>
Something like that ?
const AlldivTest = document.querySelectorAll('.test');
document.querySelector('#Map').onclick =e=>{
if (!e.target.matches('area')) return;
e.stopPropagation();
AlldivTest.forEach(d=>{
if (d.id===e.target.dataset.elm)
{ d.style.display = (d.style.display==='none') ? 'block' : 'none' }
else
{ d.style.display = 'none' }
})
}
.test { display: none; border:1px solid grey; padding: 5px 10px }
img { width:550px; height:550px }
<div class="div-voog">
<img class="map" src="images/tekening-oog-vrouw-550px.jpg" alt="" usemap="#Map" />
<map name="Map" id="Map">
<area data-elm="vooglid" alt="" title="" href="#" shape="poly"
coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
<area data-elm="vwimpers" alt="" title="" href="#" shape="poly"
coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
<area data-elm="vwenkbrauw" alt="" title="" href="#" shape="poly"
coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
<area data-elm="vooghoek" alt="" title="" href="#" shape="poly"
coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />
</map>
</div>
<div class="test" id="vooglid"> Symptoom ooglid</div>
<div class="test" id="vwimpers"> Symptoom wimper</div>
<div class="test" id="vwenkbrauw"> Symptoom wenkbrauw</div>
<div class="test" id="vooghoek"> Symptoom ooghoek</div>
[edit]
For a quick see of "my" part of code you have to use only one script and it should b: like this
<script>
$(function () {
$('.map').maphilight({
fade: false
});
$('.map').maphilight({
fillColor: '008800'
});
$('#hilightlink')
.mouseover(function (e) { $('#square2').mouseover(); })
.mouseout(function (e) { $('#square2').mouseout(); })
.click(function (e) { e.preventDefault(); });
$('#linkerbeenlink')
.click(function (e) {
e.preventDefault();
var data = $('#linkerbeen').data('maphilight') || {};
data.neverOn = !data.neverOn;
$('#linkerbeen').data('maphilight', data);
});
$('#linkerbeen,#linkerbeenlink2')
.click(function (e) {
e.preventDefault();
var data = $('#linkerbeen').mouseout().data('maphilight') || {};
data.alwaysOn = !data.alwaysOn;
$('#linkerbeen').data('maphilight', data).trigger('alwaysOn.maphilight');
});
$('#vinger2link')
.click(function (e) {
e.preventDefault();
var data = $('#vinger2').data('maphilight') || {};
data.neverOn = !data.neverOn;
$('#vinger2').data('maphilight', data);
});
$('#vinger2,#vinger2link2')
.click(function (e) {
e.preventDefault();
var data = $('#vinger2').mouseout().data('maphilight') || {};
data.alwaysOn = !data.alwaysOn;
$('#vinger2').data('maphilight', data).trigger('alwaysOn.maphilight');
});
const AlldivTest = document.querySelectorAll('.test');
document.querySelector('#Map').onclick =e=>{
if (!e.target.matches('area')) return;
e.stopPropagation();
AlldivTest.forEach(d=>{
if (d.id===e.target.dataset.elm)
{ d.style.display = (d.style.display==='none') ? 'block' : 'none' }
else
{ d.style.display = 'none' }
})
}
});
</script>
use jquery code that will work for hiding all other div when you click on current div
$('a').on('click', function(){
var target = $(this).attr('vooglid');
$("test"+target).show().siblings("div").hide();
});
but you must change your ids for apply that code
Do you already have tried adding all other div's to a CSS class?
Try this code:
function toggle_visibility(var id){
$("#vooglid").addClass("hide_div");
$("#vooghoek").addClass("hide_div");
$("#vwimpers").addClass("hide_div");
$("#id").removeClass("hide_div");
});
CSS:
.hide_div{
display: none;
}
I did this a few months ago and it worked fine.

Placing an element on the area tag position

I'm trying to implement a board game in React. I'm using area/map tags to detect clicks on the board. I want to place a prick/stone on the position of the area tag, when some logic happens. How can I place an img element on the position of the area tag in the board-img element?
I've tried this code, but it dosen't seem to work..
renderBoard() {
const board = this.state.gameState.board;
let positionSyle = {};
let square = this['w1'] ? this['w1'].getBoundingClientRect() : false;
if (square) {
{/**Find square w1 and get position its position */ }
positionSyle = {
top: square.top + 'px',
left: square.left + 'px',
}
}
return (
<React.Fragment>
{/**render board image + insert areas on board(squares) */}
<div>
<img src="board.png" useMap="#image-map" />
<map name="image-map">
<area ref={(c) => this['w1'] = c} target alt="w1" title="w1" coords="387,313,315,244" shape="rect" onClick={() => console.log('w1')} />
<area ref={(c) => this['w2'] = c} target alt="w2" title="w2" href coords="295,317,219,243" shape="rect" onClick={() => console.log('w2')} />
</map>
<img src={"w-stone.png"} style={{ ...positionSyle, position: 'absolute', width: '50px', height: '50px' }} />
</div>
</React.Fragment>
)
}
Screenshot of current code. The stone should be placed on the "w1" square. But it isn't..

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?

Categories