Monarch Wadia
Monarch Wadia

Reputation: 4966

Why is this code not working with separate javascript?

I want to turn a span of text red when I click on a button. Why does the first set of code, with separate Javascript and HTML, not work... but the second set of code does?

FIRST SET (not working)

JAVASCRIPT:
    function focus()
    {
        getElementById('redder').style.color = '#ff0000';
    }

HTML:
    <button id="button1" onClick="javascript:focus()">cool</button>
    <span id="redder"> RED </span>

. . .

SECOND SET (working)

HTML:
    <button id="button1" onClick="getElementById('redder').style.color = '#ff0000';">cool</button>
    <span id="redder"> RED </span>

Upvotes: 1

Views: 107

Answers (2)

spiritwalker
spiritwalker

Reputation: 2257

  1. change the name of click event handler from focus to something else;
  2. you need use document.getElementById()
<script>
     function changeColor()
        {
            document.getElementById('redder').style.color = '#ff0000';
        }
    </script>
    <body>
        <button id="button1" onClick="changeColor();">cool</button>
        <span id="redder"> RED </span>
    </body>

Upvotes: 3

Justus Romijn
Justus Romijn

Reputation: 16019

When using non-inline JavaScript, you need to add the document scope:

document.getElementById('redder').style.color('#ff0000');

I think JavaScript does not need that scope when defined inline, but I can't find documentation on that quickly.

Upvotes: 1

Related Questions