Set onclick event using script

89,393

Solution 1

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();
  });
});

Solution 2

Alternatively, if you're not using jQuery:

document.getElementById('forgotpass').onclick = forgotpass;

Solution 3

Something like this might work..

var div = document.getElementById("forgotpass");
div.onclick=function(){ /*do something here */ };

if you dont add the function, the javascript will run the onclick once it runs through the script.

Solution 4

You can do it with jQuery like

$("#forgotpass").click(function() {
  alert("Handler for .click() called.");
});

Solution 5

In pure javascript you can do:

function forgotpass() {
 //..code
}

var el = document.getElementById("forgotpass");
el.onclick = forgotpass;

but this is very naive, not flexible and probably a bad practice.

If you are using jQuery, you can do:

function forgotpass() {
 //..code
}

$(document).ready(function() {
  $("#forgotpass").click(function() {
    forgotPass();
  });
});
Share:
89,393
Γεώργιος Βιδαλάκης
Author by

Γεώργιος Βιδαλάκης

Γεώργιος Βιδαλάκης: Student, Web and Program developer Knowledge: html, css, javascript, jquery, ajax, php, pascal, Visual Basic.

Updated on July 22, 2022

Comments

  • Γεώργιος Βιδαλάκης
    Γεώργιος Βιδαλάκης almost 2 years

    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>