Solved

Click function doesn't work first time

Posted on 2015-02-18
5
427 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 5

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 5

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
In this tutorial viewers will learn how to style a decorative dropcap for the first letter in a paragraph using CSS. In CSS, create a new paragraph class by typing "p.fancy": Then, to style only the first letter of the first sentence, include the ps…
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 …

691 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