Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new function in onclick

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.

like image 260
000000000000000000000 Avatar asked Nov 27 '25 20:11

000000000000000000000


2 Answers

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

like image 116
Tushar Avatar answered Nov 29 '25 10:11

Tushar


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>
like image 39
Meowtwo 117 Avatar answered Nov 29 '25 10:11

Meowtwo 117



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!