Reputation: 11473
I've created few map areas in an image. I want to display the description of particular area onclick. I used one javascript function. Image contains around 15-20 map areas. Below is simple function for only 3 areas. This one working fine.
function showdiv(id) {
obj = document.getElementById(id);
alert(obj);
if (obj.style.display == 'block') {
obj.style.display = 'none';
}
if (obj.style.display == 'none') {
if (obj == whatever1) {
whatever1.style.display = 'block';
whatever2.style.display = 'none';
whatever3.style.display = 'none';
} else if (obj == whatever2) {
whatever2.style.display = 'block';
whatever1.style.display = 'none';
whatever3.style.display = 'none';
} else if (obj == whatever3) {
whatever3.style.display = 'block';
whatever2.style.display = 'none';
whatever1.style.display = 'none';
}
}
}
I believe this is method not fair for more than 15 map areas. So i tried to use for loop. But something went wrong.
<script>
function showdiv(id) {
obj = document.getElementById(id);
if (obj.style.display == 'block') {
obj.style.display = 'none';
}
if (obj.style.display == 'none') {
for (var i=0; i<=12; i++) {
var div = whatever + i;
if (div == obj) {
div.style.display = 'block';
home.style.display = 'none';
} else {
div.style.display = 'none';
}
}
}
}
</script>
What's the solution to this basic problem? Anybody have any suggestion?? Thank you so much in advance.
Upvotes: 0
Views: 107
Reputation: 7855
I suggest that you summarize all your wahtever
elements with classes. i.e:
<div id="whatever1" class="whateverElement"/>
Then in your function you can handle them all the same:
function showdiv(id) {
obj = document.getElementById(id);
var isBlock = (obj.style.display == 'block');
//first change all elments
var allElements = document.getElementsByClassName("whateverElement");
for(var e in allElements){
var element = allElements[e];
element.style.display = "none";
}
//now change the value for the object with the given id
if (isBlock) {
obj.style.display = 'none';
} else {
obj.style.display = 'block';
}
}
Just to show that it can be worth having a look at "jQuery" for such tasks the following code would do the same as above using jQuery:
function showdiv(id) {
$(".whateverElement").hide();
$("#" + id).show();
}
Upvotes: 1
Reputation: 26961
You must get your elements by
div = document.getElementById("whatever" + i);
then manage it as you did...
Upvotes: 0
Reputation: 1081
if whatever
is a string
then you can do as following:
var whatever = whatever+i;
var div = $(whatever);
alert(div);
if (div == obj) {
//.....your code continue.......
Upvotes: 0