Can someone tell me why the javascript code below causes renewSession() to be called 7 times after a single click?
$(document).ready(function () {
$("*").mouseup(function () {
renewSession();
});
});
function renewSession() {
$.ajax({
url: "/Account/RenewSession",
type: "POST"
});
}
Probably it's because the mouseup
event propagates up through the DOM tree, and you're applying the handler to every element in the document. So it'll fire on the first element, and then the parent and so on until it gets to the html
(or the body
, I can never quite remember without checking every time).
You could use:
$(document).ready(function () {
$("*").mouseup(function (e) {
e.stopPropagation();
renewSession();
});
});
To prevent the multiple calls.
Thanks for the quick response...what I am trying to do is call renewSession() every time the user clicks on the site to keep the session alive. This solution prevents the renewSession from getting called multiple times in a single click but prevents the actual intent of the user's click from firing. Anyway to get around this?
You could just target the body
element; so long as events are allowed to propagate through the DOM tree (so long as you're not calling event.stopPropagation()
on elements between the element clicked on (or 'mouseup'-ed) then the event(s) will propagate to the body
. So I'd suggest using:
$(document).ready(function () {
$("body").mouseup(function () {
renewSession();
});
});