-1

I have a webpage that has a link set to change the background colour of the page, the colour of the link, & the link text. Here is my code:

<html>

<head>
<title>Title</title>
<script type="text/javascript">
function Lights() {
document.body.style.backgroundColor='#000000';
document.getElementById("on").innerHTML="Turn on the lights";
document.getElementById("on").style.color="#00ffff";
}
</script>
</head>

<body style="font-size:200px; text-align:center;">
<a href="javascript:void(0)" id="on" onclick="Lights()">Turn off the lights</a>
</body>

</html>

I was wondering how I would set the JavaScript to reverse those statements when the link is clicked again so the page is back to the white background, the text is back to "Turn off the lights", & the link is back to the darker blue.

Thank you

2 Answers 2

3

You can use a variable to store the state and toggle based off that.

<script type="text/javascript">
  var toggle = false;
  function Lights() {
    var link = document.getElementById("on");
    document.body.style.backgroundColor= toggle ? '#ffffff' : '#000000';
    link.innerHTML=toggle ? "Turn off the lights": "Turn on the lights";
    link.style.color= toggle ? '#000000': "#00ffff";
    toggle = !toggle;
  }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Glad that helped. On SO, if an answer solved your problem, the way to say thanks and show other people that its solved is by accepting the answer. That will also help you build rep, which will let you upvote and downvote questions and answers among other things.
0

You can toggle the settings based on a class value:

<a ... class="lightsOn" onclick="Lights(this);" ...>Turn off the lights</a>

then:

function lights(element) {
    if (element.className == 'lightsOn') {
        element.className = 'lightsOff';
        // do settings for lights off
    } else {
        element.className = 'lightsOn';
        // do settings for lights on
    }
}

Most of the setting can be assigned to the class in CSS rather than hard coded in the function.

Note that function names starting with a capital letter are, by convention, reserved for constructors, and you shouldn't use an A element if you don't want an A, use a span with appropriate styling:

<style type="text/css">
  .clickable {
    cursor: pointer;
    text-decoration: underline;
    font-color: blue;
  }
</style>

<span class="clickable" ...> ... </span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.