最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onclick not working in external js-file, but in inline - Stack Overflow

programmeradmin0浏览0评论

What I want : change text-color to red on text in a <h1>tag with <id="headline">

Anyone that has an idea why the following code does not work, but further down in this question, that code work by moving onclick-event to inline code?

Does not work : following code written in external js-file

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

document.getElementById("headline").onclick = changeColor;

Works : Following code written in external js-file (function is the same):

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

…and this written in inline code:

<h1 id="headline"  onclick="changeColor()">with inline code this text change color on click</h1>

What I want : change text-color to red on text in a <h1>tag with <id="headline">

Anyone that has an idea why the following code does not work, but further down in this question, that code work by moving onclick-event to inline code?

Does not work : following code written in external js-file

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

document.getElementById("headline").onclick = changeColor;

Works : Following code written in external js-file (function is the same):

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

…and this written in inline code:

<h1 id="headline"  onclick="changeColor()">with inline code this text change color on click</h1>
Share Improve this question asked Jul 2, 2013 at 22:52 VoteForPedroVoteForPedro 331 silver badge6 bronze badges 4
  • Any errors in the console? Does it appear after the element? if not is it wrapped in window.onload? – PSL Commented Jul 2, 2013 at 22:56
  • Works fine in JSFiddle: jsfiddle/Wm6Qv – bpeterson76 Commented Jul 2, 2013 at 22:57
  • As @bpeterson76 said, it seems to be working fine. – Grant Weiss Commented Jul 2, 2013 at 22:59
  • Yes an error in console. Console says document.getElementById(...) is null. (beginner to js, but know now what console is, had to googled it :) ). Still don't know what the error means though – VoteForPedro Commented Jul 2, 2013 at 23:08
Add a ment  | 

1 Answer 1

Reset to default 5

Without seeing more of your code, I would assume that you are creating and binding the changeColor() function in a javascript file that is loaded in the <head> of your HTML.

If so, the element with id headline doesn't exist yet (the javascript file is being processed before the HTML has fully loaded), so you are trying to bind to a non-existent element.

If this is the case, either move your script include to the bottom of the <body> element , or wrap the binding in a window.onload function as seen in this jsFiddle.

发布评论

评论列表(0)

  1. 暂无评论