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

JavaScript Callback Functions in JavaScript Callbacks and the DOM Callbacks with Arguments

Dilip Agheda
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dilip Agheda
Full Stack JavaScript Techdegree Graduate 28,581 Points

I would like to share a very flexible code based on this lecture.

I was playing around with the code explained in the video and I ended up with something like this.

const div1 = document.getElementById('first');
const div2 = document.getElementById('second');
const div3 = document.getElementById('third');

function changeColor(options) {
    options.element.style.backgroundColor = options.color;
}

function applyBorder(options){
        options.element.style.border = options.border;

}
const actionWithOptions = {
    options: {element : div3,
    color: 'green',
  border: '5px solid black'},
    f: changeColor,
    f1: applyBorder
}

function addStyleToElement(actionWithOptions) {
    actionWithOptions.f(actionWithOptions.options);
      if(actionWithOptions.options.border && actionWithOptions.f1){
                actionWithOptions.f1(actionWithOptions.options);

        }
}

//method-1 : pass json const as options which changes color and apply border
addStyleToElement(actionWithOptions);

//method-2: pass json directly in the call
addStyleToElement({options:{element:div1, color:'red'},f:changeColor});