Solved

Click function doesn't work first time

Posted on 2015-02-18
5
340 Views
Last Modified: 2015-03-05
This code to toggle a button color does not work on the first click and only starts working after the second one. Why?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style>
        #Button1 {
            background-color: rgb(0, 170, 88);
        }
    </style>
</head>

<body>
    <input id="Button1" type="button" value="Toggle Color" onclick="toggleColor()" />
        <script language="javascript" type="text/javascript">
        function toggleColor() {
            if (document.getElementById("Button1").style.backgroundColor == "rgb(0, 170, 88)") {
                document.getElementById("Button1").style.backgroundColor = "rgb(238, 52, 36)";
            }
            else {
                document.getElementById("Button1").style.backgroundColor = "rgb(0, 170, 88)";
            }
        }

    </script>
</body>
</html>
0
Comment
Question by:BobHavertyComh
5 Comments
 
LVL 29

Expert Comment

by:Paul Jackson
ID: 40617186
Your JavaScript function needs to be defined before it appears in the html, move your JavaScript in between the Head tags where it belongs and it will work fine.
0
 
LVL 44

Accepted Solution

by:
Rainer Jeschor earned 500 total points
ID: 40617610
Hi,
nothing to do with the location of the script.
Simply on the first click, the Javascript returns an empty string as the color is not set on the button directly. Then it sets the value whereas in the subsequent calls there is a value where the compare works.

Please try here:
http://jsfiddle.net/EE_RainerJ/kp630L57/

Solution:
either set the style directly on the button OR additionally add the check for "" (empty)

HTH
Rainer
0
 
LVL 4

Expert Comment

by:Jim Riddles
ID: 40618802
As Rainer stated, the value of the background color is not actually set in JavaScript at the beginning of the script, therefore you need to check for a null value, as well.  I have altered your code somewhat to make it a little cleaner and less cluttered.  See below:

<input id="Button1" type="button" value="Toggle Color" onclick="toggleColor(this)" />
<script language="javascript" type="text/javascript">
function toggleColor(obj) {
    if (!obj.style.backgroundColor || obj.style.backgroundColor == "rgb(0, 170, 88)") {
        obj.style.backgroundColor = "rgb(238, 52, 36)";
    } else {
        obj.style.backgroundColor = "rgb(0, 170, 88)";
    }
}
</script>

Open in new window


Note that on line 1 I am passing the object along with the function call.  This allows me to reference the object as a variable, obj, rather than using "document.getElementById" every time.  On line 3, I add the obj reference in the parens for the function.  On line 4, I begin the if statement by checking to see if the background is false or null while checking for the default color, as well.  That is the only true change you need to make to your existing code.  Whereas before, on the first click, your if statement was false for the first condition, and automatically assigned the background color to the same value you were using in the else clause.

Alternatively, you also could have simply checked to see if it the value was not your default value, first and change it to the second color in the else clause.  Although that would have worked in this instance, as you were only checking for two colors, that is not the correct method.

Let me know if you have any questions on this.  Thanks!
0
 
LVL 4

Expert Comment

by:Jim Riddles
ID: 40642420
Upon further reflection, I wanted to get a clearer understanding of this issue.  What I came upon is that if an element is styled using CSS stylesheets, then there is a different method to detect the style.

<input id="Button1" type="button" value="Toggle Color" onclick="toggleColor(this)" />
<script language="javascript" type="text/javascript">
function toggleColor(obj) {
    if (getComputedStyle(obj).backgroundColor == "rgb(0, 170, 88)") {
        obj.style.backgroundColor = "rgb(238, 52, 36)";
    } else {
        obj.style.backgroundColor = "rgb(0, 170, 88)";
    }
}
</script>

Open in new window


Note my change on line 4.  What I have done is used "getComputedStyle(element)" to get the current computed style of the input button using the obj variable.  This will correctly determine the current background color of the button each time the function is called.

I believe this is the best method to use, but my previous post will work, as well.  Cheers!
0
 
LVL 9

Author Closing Comment

by:BobHavertyComh
ID: 40647639
Right, inline styling assures it is set from the beginning. Thanks.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
In this tutorial viewers will learn how to style rounded corners for elements in CSS using the border-radius property Begin with a normal styled element such as a div: To style all four corners of the div to be the same degree of roundness, use the …

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question