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 trialTurandeep Munday
6,047 PointsWhen i move the function out of the event listener itself my page loads with the styles already applied
// we have a button object with id="btn-main" and <h1 id ="headline">
const headline = document.getElementById('headline');
const selectButtonElement = document.getElementById('btn-main');
function changeBorder(selection, borderString) {
let a = selection;
let b = borderString;
a.style.border = b;
};
selectButtonElement.addEventListener('click', changeBorder(headline, 'solid 2px red'));
My thinking is when i select the button element then the fucntion should run with selected params and it should run much in the same way as using an arrow function as second argument on .addEventListener
1 Answer
Steven Parker
231,271 PointsWhen a function (like addEventListener) needs a callback argument, you should pass only a reference to the function. But what's happening in this code is that handler function is being called, and its return value (which is "undefined" in this case) is being passed as the callback. Calling the function is what applies the styles immediately.
In the original lesson code, the arrow function expression creates a reference and defines a function but the function isn't actually called until the event occurs.
Turandeep Munday
6,047 PointsTurandeep Munday
6,047 Pointsthis is the code that works from the course