kawnah kawnah - 19 days ago 7
HTML Question

Valid Javascript snippet not working on codepen or jsfiddle?

I have a button that when clicked it changes the color of text to red.

Some basic JS below:

function colorChange() {
document.getElementById('text').style.color = "red";
}


and HTML:

<p id="text">some text</p>
<button type="button" onclick="colorChange()">red</button>


Does not work on either JSfiddle or Codepen. However - when I make an identical local HTML file it works as expected.

What would be a/the reason as to why this vanilla Javascript doesn't work in Codepen/JSfiddle? There are no libraries (jQuery, React etc) involved. My first immediate thought was in JSFiddle, there is a property that you can set in settings for the load type. I set this to
onLoad
and still did not work. Codepen doesn't look like it offers control over this.

JSFiddle:
https://jsfiddle.net/mo5pro4a/1/

Codepen:
https://codepen.io/anon/pen/YVYZXj

UPDATE: Codepen actually looks to be OK - the issue is primarily now with jsfiddle.

Answer

Because you use onclick attr in html, but js is inserted after this tag.

It'll work fine if you add <script> in html area.

<script>
function colorChange() {
    document.getElementById('text').style.color = "red";
}
</script>
<p id="text">some text</p>
<button type="button" onclick="colorChange()">red</button>

Thanks imtheman. Another way is to click on the JavaScript gear and change the load type to "head" or "body" in fiddle.