HTML Question

set onclick event using script

I want to make my

script
set the
onclick
properity of a
<div>
.

I use this Html code:

<div id="forgotpass">Forgot Password?</div>


I want when a user clicks the
<div>
a
forgotpass()
function to run, but I do not want to use this:

<div id="forgotpass" onclick="forgotpass();">Forgot Password?</div>

Answer Source

Pure JavaScript:

function addListener(element, eventName, handler) {
  if (element.addEventListener) {
    element.addEventListener(eventName, handler, false);
  }
  else if (element.attachEvent) {
    element.attachEvent('on' + eventName, handler);
  }
  else {
    element['on' + eventName] = handler;
  }
}

function removeListener(element, eventName, handler) {
  if (element.addEventListener) {
    element.removeEventListener(eventName, handler, false);
  }
  else if (element.detachEvent) {
    element.detachEvent('on' + eventName, handler);
  }
  else {
    element['on' + eventName] = null;
  }
}

addListener(document.getElementById('forgotpass'), 'click', forgotpass);

jQuery:

$(document).ready(function() {
  $("#forgotpass").click(forgotPass);
});

Or:

$(document).ready(function() {
  $("#forgotpass").click(function() {
    forgotPass();
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download