0

I'm trying to add on click event to a button dynamically. the problem is that the function is triggering before I click the button here is my code ..

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
    function start() {
    var p = document.getElementById("myP");
    var b = document.getElementById("myB");
    b.addEventListener("click", colorIt(p) );
          }
    function colorIt(ele){
    ele.setAttribute("style", "color : red" );
          }
    window.addEventListener("load", start , false);
</script>
</head>
<body>
<button id="myB"> click me </button>
<p id ="myP"> test </p>
</body>
</html>
Sarah
  • 39
  • 6

1 Answers1

0

You can call the function inside of an anonymous function:

b.addEventListener("click", function() {colorIt(p)} );

function start() {
  var p = document.getElementById("myP");
  var b = document.getElementById("myB");
  b.addEventListener("click", function() {colorIt(p)} );
}
function colorIt(ele){
  ele.setAttribute("style", "color : red" );
}
window.addEventListener("load", start , false);
<button id="myB"> click me </button>
<p id ="myP"> test </p>
Mamun
  • 66,969
  • 9
  • 47
  • 59