0

OK I have:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript index</title>
</head>
<body id="body">
<p id="para">Hello I am Sam</p>

<script>
"use strict";

var element = document.getElementById("para");

element.addEventListener( "click", function(color){
    this.style.backgroundColor = color;
}, false );


</script>
</body>
</html>

My main question is with regards to:

element.addEventListener( "click", function(color){
    this.style.backgroundColor = color;
}, false );

Is there a way to dynamically pass in a color or does it have to be hard coded?

Robert
  • 10,126
  • 19
  • 78
  • 130

2 Answers2

3

One solution is to use a named function to add the handler like

function addClickHandler(element, color) {
    element.addEventListener("click", function (e) {
        this.style.backgroundColor = color;
    }, false);
}

then

addClickHandler(element, 'red')
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Another solution is to use composition and have a function that returns a handler.

function createHandler( color) {
    return function (e) {
        this.style.backgroundColor = color;
    };
}

element.addEventListener( "click", createHandler('red'), false );

Or what I think is the most elegant of all solutions, Function.bind

function clickHandler(color, e) {
  this.style.backgroundColor = color;
}

var divs = document.getElementsByTagName('div');
var colors = ['blue', 'red', 'gray'];
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', clickHandler.bind(divs[i], colors[i]), false);
}
div {
  height: 100px;
  width: 100px;
  border: 1px solid firebrick;
  display: inline-block;
  margin: 5px;
}
<div></div>
<div></div>
<div></div>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • Nicely done! @juan mendes. My skills and understanding in JavaScript and closures just went up 10%. – Robert Mar 10 '15 at 03:54
  • @samyismyhero Since you're learning JavaScript, I added another example that is even more abstracted, and, IMO, much cooler . – Ruan Mendes Mar 10 '15 at 12:56