3

I'm currently writing a Greasemonkey script to add an onclick event to an existing button, to show a confirmation popup window.

This is the existing html:

<input type="button" id="previewOrder" title="" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false" value="Preview Order">

I came up with the following javascript but it does not work or fails

function confirm () {
    alert ("Sure?");
}

document.getElementById("previewOrder").addEventListener("click", confirm(), false);

Any suggestions on how to get this working?

Aurelia
  • 47
  • 1
  • 4
  • you can't call your function confirm, which is vauge anyway. call it something meaningful to and avoid the conflict. – dandavis Jun 22 '16 at 00:08

2 Answers2

3

confirm() is native window method. Therefore put it in a function :

function myFunction() {
    confirm( ... );
}

Example :

function myFunction() {
  confirm("Sure?");
}

document.getElementById("previewOrder").addEventListener("click", myFunction);
<input type="button" id="previewOrder" title="" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false" value="Preview Order">
  • It should work! You have to put the JavaScript at the end of `` after the ``. I've added an example! –  Jun 21 '16 at 23:45
1

Thanks for helping out. In the end it appears the reason it was not working on my side is that the script was executed before the page (and in particular the target element) was loaded. After adding the waitForKeyElements() utility the code was working.

See https://stackoverflow.com/a/12899331/3149095

function myConfirm () {
confirm ("Sure?\n\nCheck rules.\n\n");
}

function setConfirm () {
document.getElementById("previewOrder").addEventListener("click", myConfirm);
}

waitForKeyElements ("#previewOrder", setConfirm);
Community
  • 1
  • 1
Aurelia
  • 47
  • 1
  • 4