Reputation: 352
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>
Upvotes: 24
Views: 92067
Reputation: 2261
If you are using jQuery it's best if done as follows. If the function call is executed more than once multiple eventhandles will be registered. Following approach makes sure the previous handlers are removed
$("#forgotpass").off().on('click', function () {
forgotPass();
});
Upvotes: 0
Reputation: 23727
...
<div>
<input type="button" value="Set Cookie" onclick="setCookie();" />
</div>
<script>
function setCookie() {
console.log('ready to set cookie?');
}
</script>
...
Good Luck!
Upvotes: 0
Reputation: 31
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.
Upvotes: 3
Reputation: 19534
If you only need to support IE 9+ (source), you can use EventTarget.addEventListener
in pure JavaScript.
function forgotpass() {
alert("Hello, world!");
}
var element = document.getElementById("forgotpass");
element.addEventListener("click", forgotpass, false);
<button id="forgotpass">Forgot Password?</button>
Upvotes: 2
Reputation: 30453
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();
});
});
Upvotes: 29
Reputation: 51441
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();
});
});
Upvotes: 2
Reputation: 1407
Alternatively, if you're not using jQuery:
document.getElementById('forgotpass').onclick = forgotpass;
Upvotes: 55
Reputation: 2288
You can do it with jQuery like
$("#forgotpass").click(function() {
alert("Handler for .click() called.");
});
Upvotes: 2