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 trialsibal gesekki
3,484 Pointswhy wouldnt this work
<button id="load" onclick="sendAJAX()">Load</button>
function sendAJAX() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
xhr.send();
this.style.display = 'none';
}
my last line doesnt work if i do it like that. the button is firing the event so why wouldnt it work?
2 Answers
Clayton Perszyk
Treehouse Moderator 48,850 PointsHey Sibal,
The id in your HTML is 'load' , while in your javaScript you are trying to access an element with the id of 'ajax'. Also, I'm not sure what you are trying to set to 'none' with this.style.display. In this context the keyword, this, refers to the window object, which does not have a style property. As such, it will throw an error.
Best,
clayton
Clayton Perszyk
Treehouse Moderator 48,850 PointsHey Sibal,
The context of this changes depending on where the function is defined and what object called it. In the code you have, the function is defined on the global scope (i.e. the window); so, when the function is called this changes context from the HTML element (i.e. the button) to the window object. One of the nice features of jQuery is that it keeps this consistent with what you think it will be. You can however use a method on the function (e.g. apply(), call() ) to explicitly set the context of this. I'm not sure if this is very clear, so I posted a link to blog post with a good description. If you I can help any more, just ask.
- http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ (see the section entitled Problem When Using Methods With The this Object as Callbacks)
sibal gesekki
3,484 Pointssibal gesekki
3,484 Pointshi clayton. i thought that calling 'this' refers to the element that fires the function. so when i click the button, it runs the sendAjax() function. so if i call 'this' within that function, would it not refer to the button?
i intended for the button to change its display to none when it is clicked. i know that i can just use getElementById on the button but i was just wondering why i couldnt use 'this'
when i did the jquery track that is what we generally did. and why would 'this' refer to the window object when im calling the function from a button element?
thanks