Reputation: 185
I want to understand how to call a function with an event object and another parameter(that I'll use to pass in for instance a string). So I've tried to set up this example, which is supposed to change color of the button when I press the button and add the event object and parameter to the html p element. The whole point of this is to understand how I can invoke a function that has both an event object and another variable in its parameter.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random color event object example</title>
<style>
button {
margin: 10px;
font-size: 300%;
padding: 30px;
};
</style>
</head>
<body>
<button>Change color</button>
<p></p>
<script>
var btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random()*number);
}
function bgChange (e, em) {
var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
e.target.style.backgroundColor = rndCol;
var emm = em;
document.querySelector('p').textContent = e + emm + 'hj';
}
btn.addEventListener('click', function () {
bgChange("j");
});
</script>
</body>
</html>
Upvotes: 0
Views: 35
Reputation: 413720
You'd use a wrapper function (as you're doing), but you have to handle the event parameter the browser will pass into that function:
btn.addEventListener('click', function(event) {
bgChange(event, "j");
});
In reality you'd probably want to handle old versions of IE that don't pass along the event
object as a parameter:
btn.addEventListener('click', function(event) {
bgChange(event || window.event, "j");
});
There's nothing particularly special about an event object as a parameter to a function. It's just a reference to an object.
Upvotes: 2