Trevader24135
Trevader24135

Reputation: 77

Event listener not working?

Sorry for so many questions, but I suck at javascript and want to get good at it. I'm trying to make a page change colors when you press a button as another proof of concept for me, but it's not working and I'm not entirely sure why...

<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
button.eventlistener(BGchange, BGcolor());
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
    document.body.style.background = white;
}
else
    if(BG==1){
        document.body.style.background = black;
    }
}
</script>
</body>
</html>

k, fixed a little, here's what I have now:

<html>
<head>
</head>
<body>
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
BGchange.addEventListener("click", BGcolor);
var BG++
function BGcolor (){
if(BG==0){
backgroundcolor = "white";
}
else
    if(BG==1){
    backgroundcolor = "black";
    }
}
</script>
</body>
</html>

Upvotes: 1

Views: 10832

Answers (1)

jfriend00
jfriend00

Reputation: 707328

If you're trying to listen for an event click, then you need something like this:

 document.getElementById("BGchange").addEventListener("click", BGcolor);

Then, you need to fix some things in this function:

function BGcolor (){
    var BG = BG2+1
    var BG2 = BG
    if(BG==0){
        document.body.style.background = white;
    } else if (BG==1) {
        document.body.style.background = black;
    }
}

Because you are trying to reference BG2 before it has been initialized so it is not clear what you want to be doing there.

In order, the things I changed:

  1. Get the DOM element for the button with document.getElementById()
  2. Use addEventListener() which is the standard way of adding event handlers
  3. Change to the click event which is what buttons create when you click on them
  4. Pass just a reference to the event handler as BGcolor without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.

In addition, a bunch of things to fix in your BGcolor() function:

  1. Variables that remember their state from one function call to the next must be declared outside that function.
  2. A color value is a string so you would use "white", not white.
  3. To change just the background color, it's best to use the backgroundColor property.

Here's a working version:

<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);

var curColor = "white";
function BGcolor (){
    if (curColor == "white") {
        curColor = "black";
    } else {
        curColor = "white";
    }
    document.body.style.backgroundColor = curColor;
}
</script>

Working demo: http://jsfiddle.net/jfriend00/Nk2N5/

Upvotes: 2

Related Questions