idungotnosn
idungotnosn

Reputation: 2047

Can't get a button to execute Javascript code

I wrote some html/css/javascript code that was taken verbatim from a javascript textbook. For some reason, the code does not run correctly in my browser (which is the newest version of Firefox). When I click the button, the javascript function "toggleStyle()" does not execute in the browser at ALL. This is the code for the button:

<button type="button" onclick="toggleStyle()">Toggle Style</button>

This is the javascript coding. Note that when I click the button, not even the alert() method is executed:

        function toggleStyle() {
        alert("toggleStyle() is working.");
        var divMessage = document.getElementById("divMessage");

        if (divMessage.className === "message-style1") {
            divMessage.className = "";
        }
        else {
            divMessage.className = "message-style1";
        }

Upvotes: 1

Views: 7690

Answers (2)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

Did you put the code inside <script type="text/javascript">?

<script type="text/javascript">

function toggleStyle() {
        alert("toggleStyle() is working.");
        var divMessage = document.getElementById("divMessage");

        if (divMessage.className === "message-style1") {
            divMessage.className = "";
        }
        else {
            divMessage.className = "message-style1";
        }
}
</script>

The above code is working:

enter image description here

Upvotes: 4

megakorre
megakorre

Reputation: 2223

For starters, I don't see the end } brace; do you have one?

Also, where is the function defined? Does the script get loaded? Are there any errors?

Upvotes: 3

Related Questions