Reputation: 92
Here's an easy one.
I'm creating a link with content that changes onClick. Onload it should say ""Click here for more information!" when clicked, it should say "Click here for less information!" then on re-click "...more information".
I'm sure that I'm just making a tiny mistake somewhere, help?
JavaScript
<script>
function change_text()
{
if(document.getElementById("toggle_button").innerHTML="Click here for more
information!"){
document.getElementById("toggle_button").innerHTML="Click here for less
information!";
}else{
document.getElementById("toggle_button").innerHTML="Click here for more
information!";
}}
</script>
Here's the HTML
<a href='javascript: toggle()'><p id="toggle_button" onclick="change_text()">Click here
for more information!</p></a>
Upvotes: 1
Views: 6384
Reputation: 60717
Not only are you misusing =
as ===
, but you can also greatly improve your code with a simple technique: caching.
function change_text() {
var button = document.getElementById('toggle_button');
if (button.innerHTML === "Click here for more information!") {
button.innerHTML = "Click here for less information!";
}
else {
button.innerHTML = "Click here for more information!";
}
}
You can see how way clearer the code becomes.
Upvotes: 4
Reputation: 1046
use this for your problem it will help you better-
javascript:void(0) use on href
<html>
<head>
<title>index</title>
</head>
<body>
<script type="text/javascript">
function change_text()
{
if(document.getElementById("toggle_button").innerHTML=="Click here for more information!")
{
document.getElementById("toggle_button").innerHTML="Click here for less information!";
}
else
{
document.getElementById("toggle_button").innerHTML="Click here for more information!";
}
}
</script>
<a href='javascript:void(0)' onclick="change_text()"><p id="toggle_button" >Click here for more information!</p></a>
</body>
</html>
Upvotes: 1
Reputation: 35963
You have miss "=" in
if(document.getElementById("toggle_button").innerHTML="Click here for more
information!")
Try this code:
<script>
function change_text()
{
if(document.getElementById("toggle_button").innerHTML=="Click here for more
information!"){
document.getElementById("toggle_button").innerHTML="Click here for less
information!";
}else{
document.getElementById("toggle_button").innerHTML="Click here for more
information!";
}}
</script>
Upvotes: 0
Reputation: 100175
if(document.getElementById("toggle_button").innerHTML="Click here for more
information!"){
should be
if(document.getElementById("toggle_button").innerHTML == "Click here for more
information!"){
you are assigning rather than comparing, so use ==
instead of =
Upvotes: 1