EDIT: Just an example. I need support for if/else
I want to do this:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
Apparently this doesn't work.
Do you know how I could do this?
How can I "call" a new function?
I cannot simply define it in a <script></script>-node.
You don't need a function to call. You can directly use Javascript code. This is considered bad practice.
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
Demo
You can also use function as event handler as follow:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
Demo
Using addEventListener you can bind events from javascript instead of inline in the HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
Demo
It is not recommended to write the functions inside the parameter. It is better to write them on a separate function and then link it with one of the methods listened above. You can still do what you said in the example by using the anonimous function like this:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With