Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
eslam said
Courses Plus Student 6,734 PointsBrackets and javascript
I`m using brackets and i linked my script.js to html like that :
<script src="script.js"></script>
and here is my html
<h1 id="main-heading">No subject is terrible if the story is true.</h1>
and here is my js
onclick='document.getElementById("main-heading").style.display="none"';
dont worry about the code i am just practicing nothing more but its not working and i`m getting weird errors in brackets like the following :
- 'onclick' was used before it was defined.
3 Answers
Steven Parker
243,318 PointsIf that's the only line of JavaScript the error makes perfect sense. Were you trying to access the "onclick" property of the h1 element? As shown, it should be part of the h1 header, not separate code. A code version might look like this:
document.getElementById("main-heading").onclick = function() {
this.style.display = "none";
};
And here it is inserted into the HTML instead:
<h1 id="main-heading" onclick='document.getElementById("main-heading").style.display="none"'>
No subject is terrible if the story is true.
</h1>
eslam said
Courses Plus Student 6,734 PointsThanks steven for your answer and yes i was trying to access the h1 element, can you give me further explanation of what`s happening ?
Steven Parker
243,318 PointsFrom the code standpoint "onclick" hasn't been defined yet, or associated with a specific element. But it could be directly assigned in the element tag.
Dave StSomeWhere
19,870 PointsAs Steven has said, "onclick()" needs to be associated with an element and doesn't stand alone as per your original statement. "onclick()" is a method associated with an element. The key thing to recognize from Steven's examples is that in the first one you see ".onclick()" because it is a valid method of document.getElementByID() and in the second one, it is one of the valid <h1> element properties.
So... brackets sees you using onclick and thinks it is a variable name (as opposed to the desired method onclick() and doesn't see a declaration for it.
Make sense?
eslam said
Courses Plus Student 6,734 PointsThank you for your answers