title: javascript add an event listener any time and remove the event listener any time
body: <ol>
  <li>In a web page i have a button when clicked it calls a JavaScript function.</li>
  <li>In that function i show a modal dialog box and i want to process keystrokes only at this time. That is when the modal dialog is visible.</li>
  <li><p>When i close the modal dialog i want to stop the keystroke processing.</p></li>
  <li><p>consider that i click a button and function sam() is called.</p>
  
  <p>function sam()
  {
       document.onkeypress = function(e) { processKeystroke(e); }
  }</p></li>
  <li><p>So now a function is attached to the keypress event. when ever a key is pressed the function processkeystroke will be called.
  The function sam is called only after i display the  modal dialog box.</p></li>
  <li><p>Now i am closing the modal dialog and with that i dont want function(e) { processKes...} to be called.</p></li>
  <li><p>What should i do to remove the attached event listener from document.onkeypress.</p></li>
  <li><p>Also i would like to have alternatives for the above approach because that one i assumed of my own and i did not refer any specific documentation so i really going through trial and error procedure to use event handlers or listeners. </p></li>
  <li><p>So when i call function sam i want a function to be attached with the keypress event and if i call another function form example closedialog() i want that keypress listening function to be removed. Because i want to write proper code which should not consume lots of system resources.</p></li>
  </ol>