Solved

Click function doesn't work first time

Posted on 2015-02-18
5
294 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
date format angularjs2 16 41
CSS help matching specific span class 2 22
Re-position the objects 7 51
Datepicker in PHP 9 0
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now