The following div's are displayed onclick. How can I make it display a different message in the div "content" depending onclick. I already have the javascript to display the div's Test1 and Test2. I just wanted to add the ability to also add a message to the div "content". Sorry for the confusion.
<a href="" onclick="showThis('test1');return false;">Test 1</a>
<div class="test1"> <p>some content</p> </div>
<a href="" onclick="showThis('test2');return false;">Test 2</a>
<div class="test2"> <p>some content</p> </div>
<div id="content">
<!-- if clicked on Test 1, display some message. And if clicked on Test 2, display some other message -->
</div>
There's a dozen different ways to handle this. Most would require some minor changes to your markup - your current approach is not very robust and doesn't degrade very gracefully. This is just one possible way:
<a href="" id="test1">Test 1</a>
<div class="test1"> <p>some content</p> </div>
<a href="" id="test2">Test 2</a>
<div class="test1"> <p>some content</p> </div>
<div class="content">
<!-- if clicked on Test 1, display some message. And if clicked on Test 2, display some other message -->
</div>
Assign the click handlers programmatically:
document.getElementById('test1').onclick = handleClick;
document.getElementById('test2').onclick = handleClick;
function handleClick(e)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
if(sender.id == "test1")
{
showContent('message 1');
}
else if(sender.id == "test2")
{
showContent('message 2');
}
if(window.event)
{
window.event.returnValue = false;
}
return false;
}
function showContent(msg)
{
document.getElementById('content').innerHTML = msg;
}
First, change:
<div class="content>
to
<div id="content">
then (without using a library like jQuery):
var showThis = function(caller){
switch(caller){
case "test1":
document.getElementById("content").innerHTML = "Your content here";
break;
case "test2":
document.getElementById("content").innerHTML = "Your other message";
break;
default:
break; // here just in case you need it
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With