I have a situation where I want to add two different parameters as I want to display image tag popups in different positions?
This function is to display popup on left side
function openBubble() {
var content = myData[this.id];
bubbleContent.innerHTML = '<h3>' + content.title + '</h3>'
+ '<img src="' + content.image + '" alt="" />'
+ '<p>' + content.description + '</p>';
bubble.style.top = (event.clientY - 20) + "px";
bubble.style.left = (event.clientX - 200) + "px";
bubble.className = 'shown';
}
This function is to display popup on right side
function openBubble() {
var content = myData[this.id];
bubbleContent.innerHTML = '<h3>' + content.title + '</h3>'
+ '<img src="' + content.image + '" alt="" />'
+ '<p>' + content.description + '</p>';
bubble.style.top = (event.clientY + 20) + "px";
bubble.style.left = (event.clientX + 200) + "px";
bubble
.className = 'shown';
}
Here is my HTML –
<map name="myMap" id="myMap">
<area id="left-eye" coords="118,36,148,80" shape="rect" href="javascript:void(0);">
<area id="mouth" coords="121,84,198,118" shape="rect" href="javascript:void(0);">
</map>
I want to associate area id="left-eye" with function on the left side.
I want to associate area id="mouth" with function on the right side.
Here is the jsfiddle to my code – https://jsfiddle.net/1u6n5rvw/
How can I do this? Thanks.
3
Answers
make the positions properties of the objects …
Using a switch would be quick and dirty but this is more scaleable.
Your case is a bit special, as you are already retreiving data based on the id of the element you cliked.
As you are learning JavaScript, I will explain in case you are not sure: when you add an event listener like this
areas[i].addEventListener('click', openBubble, false);
(passing directly the function reference), JavaScript binds for youthis
to the HTML element you clicked, that allows you to usethis.id
inside the function.Now, the more flexible to you IMO will be to use this data so you can configure directly the window position inside the data. This way, you can keep using the function reference as the event handler without having to add more code to pass parameters to the function (it’s possible, but more complicated)
Here is a first version if you only want to distinguish between "left" and "right", by adding a string property
position
to your data and testing against fixed valuesHere is a more flexible version where you can directly set the x and y offsets by adding numeric properties
yOffset
andxOffset
to your data and using them directly to set the window coordinatesSince you already have the object myData, you can store the top and left values in there. You can store the negatives with a minus and the positive without it. Then for the math just + those values.