Javascript OuterHTML: How to work with a string literal? - javascript

First some HTML code:
<div id="content_4" class="content" style="background:url(pic1.gif)"></div>
<div id="content_4_a" class="content" style="background:url(pic2.gif);
display:none"></div>
This is the JS code:
function getOuterHMTL(element){
return element.outerHTML;
}
function switchDisplayOuter(elementToHide, elementToShow, stringly){
document.getElementsByName(elementToShow).outerHTML=stringly;
document.getElementById(elementToHide).style.display="none";
document.getElementsByName(elementToShow)[0].style.display="";
}
Now this HTML code works (when I click on it, the div switches and the picture changes):
<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter(
'content_4', 'content_4_a', getOuterHMTL('content_4_a) )">
But not this one:
<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter(
'content_4', 'content_4_a', '<div id="content_4_a" class="content"
style="background:url(pic2.gif); display:none"></div>' )">
It only gets me an error code while debugging in Firefox:
Error: SyntaxError: unterminated string literal
'<div id=
Somebody who knows the right code without using the function getOuterHMTL(element) but with "plain" string literal?

You need to replace your " inside the onMouseOver attribute value with \':
<area shape="rect" coords="0,252,98,337" onMouseOver="switchDisplayOuter('content_4', 'content_4_a', '<div id=\'content_4_a\' class=\'content\' style=\'background:url(pic2.gif); display:none\'></div>' )">
This is because your area tag's onMouseOver attribute's value is enclosed with ".

Related

How to write text center of the area using imagemap?

I used map and area attr and for styling them , i used maphighlight.js which is jquery. When i hover , it shows borders and color fillings etc.
Now i want to put text center of each areas which are determined with coordinates. When page loads , i want to see texts on center of areas "without hover" and after hover i wanna see borders ,color etc. Thanks for your helps.
Here's my code. 1)Maphilight
$(document).ready(function(){
$('.map').maphilight();
});
2)I tried to write text but not works properly
$(function() {
$('area').each(function(){
var txt=$(this).data('name');
var coor=$(this).attr('coords');
var coorA=coor.split(',');
var left=coorA[0];
var top=coorA[1];
var $span=$('<span class="map_title">'+txt+'</span>');
$span.css({top: top+'px', left: left+'px', position:'absolute'});
$span.appendTo('.content');
})
})
This is mapping
<div class="content">
<img src="ozak.jpg" alt="" class="map" width="2000" height="2000" border="0" usemap="#demo">
</div>
<map name="demo">
<area id="51" alt="D1" class ="tooltip" title="3+1 150 m² Deniz Manzaralı " href="javascript: alert('Daire 5127 Satılmıştır!')" coords="588,271,816,369" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire1">
<area alt="" title="" href="javascript: alert('Daire 5287 Satılıktır!')" coords="1251,278,1374,367" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"00BD06","fillOpacity":0.7}' data-name="Daire2">
<area alt="" title="" href="javascript: alert('Daire 8692 Satılmıştır!')" coords="600,469,807,554" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire3">
</map>
CSS
#map {
position:relative
}
.map_title {
position:absolute;
}
First thing is that I have used my own image.
How coords="588,271,816,369" works:
Here it is x1,y1,x2,y2 where x1,y1 is for top-left corner of area and x2,y2 is bottom-right corner.
Second thing is that you need to parse these cordinates to integer to calculate top/left attribute of your text.
Now, you can calculate left attribute by using this formula. parseInt(coorA[0])+((parseInt(coorA[2])-parseInt(coorA[0]))/2). And same for top
Please note, here the point I calculated is the exact center of your rect but it is appearing sligh the right side as it is starting from the exact center point. You can apply some more mathematics to get it exactly center aligned.
EDIT
You can calculate the width of your span and get its width. After that, divide by 2 will give you the pixes you need subtract to get your labels accurately in the center. Here, I assume some pixels are being utilized in the border so I have back 9 pixels to it as an adjustment. It can be removed if you feel it's working fine.
$(function() {
$('.map').maphilight();
$('area').each(function(){
var txt=$(this).data('name');
var coor=$(this).attr('coords');
var coorA=coor.split(',');
var left=parseInt(coorA[0])+((parseInt(coorA[2])-parseInt(coorA[0]))/2);
var top=parseInt(coorA[1])+((parseInt(coorA[3])-parseInt(coorA[1]))/2)
var $span=$('<span class="map_title">'+txt+'</span>');
$span.css({top: top+'px', left: left+'px', position:'absolute'});
$span.appendTo('.content');
$span.css({left:(left-Math.ceil($span.width()/2)+9)+'px'})
})
});
#map {
position:relative
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maphilight/1.4.0/jquery.maphilight.min.js" integrity="sha256-nUK4JHJVwdj7H1SYkkMcuE2unpjH5vYOe3mGEVu/69Q=" crossorigin="anonymous"></script>
<div class="content">
<img src="https://i.picsum.photos/id/372/200/300.jpg" alt="" class="map" width="2000" height="2000" border="0" usemap="#demo">
</div>
<map name="demo">
<area id="51" alt="D1" class ="tooltip" title="3+1 150 m² Deniz Manzaralı " href="javascript: alert('Daire 5127 Satılmıştır!')" coords="588,271,816,369" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire1">
<area alt="" title="" href="javascript: alert('Daire 5287 Satılıktır!')" coords="1251,278,1374,367" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"00BD06","fillOpacity":0.7}' data-name="Daire2">
<area alt="" title="" href="javascript: alert('Daire 8692 Satılmıştır!')" coords="600,469,807,554" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire3">
</map>

image Map with Bootstrap Tooltips not showing in correct spot

I have an image map and I would like to use the built-in tooltips provided by Bootstrap when a user hovers over a specific part of that image.
The issue I'm having is that the tooltip does not show up in the right place. Right now it shows at the top left corner of the image for all areas of the image map.
How can I move the tooltips under their respective areas without having to reposition each tooltip individually? It should automatically be within the rec defined.
Here is the map code I am using:
<img id="Image-Maps-Com-process-map" src="images/osh drawing.png" border="0" width="600" height="600" orgWidth="600" orgHeight="600" usemap="#process-map" alt="" />
<map name="process-map" id="ImageMapsCom-process-map">
<area alt="" title="Wood Burning Stove" href="#" class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="478,186,572,296" style="outline:none;" target="_self" />
<area alt="" title="Rough Cut Lumber" href="#" class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="184,1,395,148" style="outline:none;" target="_self" />
<area alt="This is the description maybe" title="Distributing" href="#"class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="45,398,304,577" style="outline:none;" target="_self" />
<area alt="" title="Shipping Materials" href="#"class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="9,52,141,183" style="outline:none;" target="_self" />
<area alt="" title="Sawdust" href="#"class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="302,311,410,385" style="outline:none;" target="_self" />
<area alt="" title="Electricity" href="#"class="tooltip-bot" data-original-title="Title text here" shape="rect" coords="430,0,570,113" style="outline:none;" target="_self" />
<area alt="manufacturing" title="Manufacturing" href="#"class="tooltip-bot" data-original-title="Title text here" shape="poly" coords="348,193,213,197,188,313,221,368,296,362,300,310,357,302,363,193" style="outline:none;" target="_self" />
</map>
I'm no expert but I feel like this is because the area elements have no actual heights or widths. Their boundaries are established using the coords attribute which likely is not looked at by bootstrap.
There may be a better way to do this, but a simple fix would be to add the below code to your page.This will position the tooltip a fixed distance from the pointer itself.
Here is a working jsFiddle
$(document).mousemove( function(e) {
var mouseX = e.pageX - $('#Image-Maps-Com-process-map').offset().left - 40;
var mouseY = e.pageY - $('#Image-Maps-Com-process-map').offset().top + 20;
$('.tooltip').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
I know that this is a fairly old and answered question, but I figured I would throw this in as I ran into the same issue and couldn't find an exact answer elsewhere. I have a site that uses an older asp.net chart control that draws image maps over the graphs so that tooltips can be displayed. To use tooltips on its area attributes and get them in the right places, I used the code below. Note that I still had to use offset amounts, but it worked fairly well. ".maparea" is a class that is dynamically applied to all of the map area attributes. I also used mouseover as I did not need the tooltip to move around constantly.
$('.maparea').mouseover(function (e) {
var position = $(this).attr('coords').split(',');
x = +position[0];
y = +position[1];
$('.tooltip').css({ 'top': y + 60, 'left': x - 83 }).fadeIn('slow');
$('.tooltip-arrow').css({ 'left': '50%' });
});
Edit:
I had to put in the tooltip-arrow line because Google Chrome was messing up the alignment of the tooltip arrow. Don't think this will happen in all scenarios but since my page has menus that can be collapsed that will resize the page on their own, they were throwing the alignment off.
My solution for popovers (basing on mouse click position):
var clickTop,clickLeft=0;
$(document).click(function(e){
clickTop =e.pageY;
clickLeft =e.pageX;
});
$().ready(function(){
var popovers=$('[data-toggle="popover"]');
popovers.popover({
placement: 'bottom center',
html:true,
trigger:'focus'
}).on("shown.bs.popover", function(e){
$('.popover').css({top:clickTop,left:clickLeft-100});
})
});
I've adopted #Big EMPin solution (right area tooltips), so it works for me at last:
<div style="position: relative;display: inline-block">
<img style="max-width: 100%" src="../static/img/JavaPyramid.jpg" usemap="#courses">
</div>
<map name="courses">
<area shape="rect" coords="120,10,200,85" href="/view/startjava" data-toggle="tooltip" data-placement="right" title="StartJava" class="maparea">
<area shape="rect" coords="85,100,165,175" href="/view/basejava" data-toggle="tooltip" data-placement="right" title="BaseJava" class="maparea">
<area shape="rect" coords="50,190,130,265" href="/view/topjava" data-toggle="tooltip" data-placement="right" title="TopJava" class="maparea">
<area shape="rect" coords="20,280,100,355" href="/view/masterjava" data-toggle="tooltip" data-placement="right" title="MasterJava" class="maparea">
</map>
<script>
$('.maparea').mousemove(function (e) {
var pos = $(this).attr('coords').split(',');
$('.tooltip').css({'left': parseInt(pos[2]) + 5, 'top': parseInt(pos[1]) + 35}).fadeIn('slow');
});
</script>
Solution can be seen at http://javaops.ru/

Can I have an onclick event on a imagemap area element?

I would like to put an onclick event on an area element. Here is my setup:
<img id="image" src="wheel.png" width="2795" height="2795" usemap="#Map" >
<map name="Map">
<area class="blue" onclick="myFunction()" shape="poly" coords="2318,480,1510,1284" href="#">
</map>
I have tried 2 different ways to have an onclick event. Firstly i tried this:
$(".blue").click( function(event){
alert('test');
});
I have also tried this:
function myFunction() {
alert('test');
}
Neither of the above work. Do area elements support the above, or do they only support having a href?
Pay attention:
Attribute href is obligatory, without it the area-tag does nothing!
To add a click event, you'll need to block default href.
Your code should start as follows:
$(".blue").on("click", function(e){
e.preventDefault();
/*
your code here
*/
});
Live example here.
Its the shape that's the problem. Your code has set shape equal to polygon but only has 4 points in the coordinates attribute. You need to set shape to rectangle instead.
Set shape="rect" like this:
<img id="image" src="wheel.png" width="2795" height="2795" usemap="#Map" >
<map name="Map">
<area class="blue" onclick="myFunction()" shape="rect" coords="2318,480,1510,1284" href="#">
</map>
Use a class for all elements you want to listen on, and optionally an attribute for behavior:
<map name="primary">
<area shape="circle" coords="75,75,75" class="popable" data-text="left circle text">
<area shape="circle" coords="275,75,75" class="popable" data-text="right circle text">
</map>
<img usemap="#primary" src="http://placehold.it/350x150" alt="350 x 150 pic">
<div class='popup hidden'></div>
Then add your event listeners to all elements in the class:
const popable = document.querySelectorAll('.popable');
const popup = document.querySelector('.popup');
let lastClicked;
popable.forEach(elem => elem.addEventListener('click', togglePopup));
function togglePopup(e) {
popup.innerText = e.target.dataset.text;
// If clicking something else, first restore '.hidden' to popup so that toggle will remove it.
if (lastClicked !== e.target) {
popup.classList.add('hidden');
}
popup.classList.toggle('hidden');
lastClicked = e.target; // remember the target
}
Demo: https://codepen.io/weird_error/pen/xXPNOK
Based on your comments, you just need this:
$("#image").click( function(){
alert("clicked");
//your code here
});
Demo:
http://codepen.io/tuga/pen/waBQBZ
This is a simple one:
<area class="blue" onclick="alert('test');" shape="poly" coords="2318,480,1510,1284" href="#">
Or for any other code:
<area class="blue" onclick="//JavaScript Code//" shape="poly" coords="2318,480,1510,1284" href="#">
Try :
<img src="wheel.png" width="2795" height="2795" alt="Weels" usemap="#map">
<map name="map">
<area shape="poly" coords="2318,480,1510,1284" alt="otherThing" href="anotherFile">
</map>
You souldn't want to add onClick events on area, documentation :
The tag defines an area inside an image-map (an image-map is an image with clickable areas).
Edit : your coords are a bit weird since its supposed to the couples of each vertices (so right now, your polygon is a line)
I found this question by #TimorEranAV
HTML map that displays text instead of linking to a URL
and was marked as duplicate, but i think what he was expecting is this,
<html>
<head>
<title> Program - Image Map</title>
</head>
<body>
<img src="new.png" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" title = "Sun">
<area shape="rect" coords="82,0,100,126" href="mercur.htm" alt="Mercury" title = "Mercury">
</map>
</body>
</html>
Here the title tag gives the opportunity to add a hover text(tip) to the image map.

JS Math.random doesn't get -9-

The code is working for all the areas and figures, except when the variable id equals 9. Then the #10 image (#9 index) doesn't appear, an undefined message is written instead. When id equals any other number, the checkAnswer() function alert correct or wrong for every area clicked, except for the #10 area, which doesn't alert anything. What's wrong with the code? (the images are all correctly on the directory)
<!doctype html>
<html>
<head>
<script type="text/javascript">
var cobras=new Array();
cobras[0] = '<img src="cobra1.jpg">';
cobras[1] = '<img src="cobra2.jpg">';
cobras[2] = '<img src="cobra3.jpg">';
cobras[3] = '<img src="cobra4.jpg">';
cobras[4] = '<img src="cobra5.jpg">';
cobras[5] = '<img src="cobra6.jpg">';
cobras[6] = '<img src="cobra7.jpg">';
cobras[7] = '<img src="cobra8.jpg">';
cobras[8] = '<img src="cobra9.jpg">';
cobras[9] = '<img src="cobra10.jpg">';
cobras[10] = '<img src="cobra11.jpg">';
cobras[11] = '<img src="cobra12.jpg">';
cobras[12] = '<img src="cobra13.jpg">';
cobras[13] = '<img src="cobra14.jpg">';
cobras[14] = '<img src="cobra15.jpg">';
id=Math.floor(Math.random()*15);
function makeDisappear() {
var elem = document.getElementById("main");
elem.style.visibility = "hidden";
var elem = document.getElementById("empty");
elem.style.visibility = "visible";
var bodyE1 = document.body;
bodyE1.innerHTML += cobras[id];
}
function checkAnswer(a) {
if (a==id) {
alert('Correct!')
}
else {
alert('Wrong!')
}
}
</script>
</head>
<body>
<center> <button onclick="makeDisappear();"> Hide </button> </center>
<center> <img id="main" src="..\images\cobra.jpg" width="941" height="689" alt="Todos os bichos."> </center>
<center> <img style="visibility: hidden;" id="empty" src="..\images\vazio.jpg" width="941" height="689" alt="Vazio." usemap="#empty"> </center>
<map name="empty">
<area shape="rect" coords="0,230,190,40" alt="1" onclick="checkAnswer(1)">
<area shape="rect" coords="191,230,380,40" alt="2" onclick="checkAnswer(2)">
<area shape="rect" coords="381,230,570,40" alt="3" onclick="checkAnswer(3)">
<area shape="rect" coords="571,230,760,40" alt="4" onclick="checkAnswer(4)">
<area shape="rect" coords="761,230,941,40" alt="5" onclick="checkAnswer(5)">
<area shape="rect" coords="0,470,190,240" alt="6" onclick="checkAnswer(6)">
<area shape="rect" coords="191,470,380,240" alt="7" onclick="checkAnswer(7)">
<area shape="rect" coords="381,470,570,240" alt="8" onclick="checkAnswer(8)">
<area shape="rect" coords="571,470,760,240" alt="9" onclick="checkAnswer(9)">
<area shape="rect" coords="761,470,941,689" alt="10" onclick="checkAnswer(10)">
<area shape="rect" coords="0,490,190,689" alt="11" onclick="checkAnswer(11)">
<area shape="rect" coords="191,490,380,689" alt="12" onclick="checkAnswer(12)">
<area shape="rect" coords="381,490,570,689" alt="13" onclick="checkAnswer(13)">
<area shape="rect" coords="571,490,760,689" alt="14" onclick="checkAnswer(14)">
<area shape="rect" coords="761,490,941,689" alt="15" onclick="checkAnswer(15)">
</map>
</body>
</html>
If it is indeed only happening on item #9, it suggests to me some type of number verses string problem.
First change the variable name of 'id' to something else, that name could cause problems.
Then declare it at the top with a var, the same as you are doing with the cobras array.
I would change 'id' to a string, and convert the result of the Math function using parseInt.
Change the index values you are giving in the array to strings as well, so they become keys instead.
Then add single quotes around the value given in the checkAnswer calls from the area tags.
No guarantee that this would fix the problem, but at least you know for sure that the random item, and the item chosen, are all strings.

grab one element instead of all

i have areas in my html, that have unique href='#cha', cha is unique and different for every area. I need to grab area on click in my js, i have already this unique value.
valueRegionSelect contains my unique value on click(it's change depends on my click, for example klu, chu, ada, etc.).
html part with my areas:
<div class="b-map">
<div class="b-map__city"></div>
<div class="b-map__item">
<img class="mapImage" src="/images/map-light.png" width="701" height="408" border="0" usemap="#map" />
<map name="map">
<area shape="poly" coords="615,0,554,20,548,87,558," title="<?php echo isset($this->region['chu']) ? $this->region['chu']['r_name'] : "region name for chu" ?>" href="#chu" />
<area shape="poly" coords="47,237,63,237,67,246,48,248" title="<?php echo isset($this->region['klu']) ? $this->region['klu']['r_name'] : "region name for klu" ?>" href="#klu" />
this one grab all areas, but i need only one area with selected unique element:
$mapItem = $('.b-map__item area');
I use it in same function in js:
coords = $mapItem.attr('coords').split(','),
Thanks for any help!
If you're looking for the <area> with a specific href, then use the attribute selector:
var valueRegionSelect = "cha";
$mapItem = $('.b-map__item').find('area[href="#' + valueRegionSelect + '"]');
http://api.jquery.com/category/selectors/attribute-selectors/
( http://api.jquery.com/attribute-equals-selector/ )
If I am getting you correctly then this should work
var areaHref = ('#yourselectId').val();
$mapItem = $('.b-map__item').find('area[href="#'+areaHref+'"]'); ;

Categories

Resources