This may be a basic question. I have a button which is
<button type="button">Click Me!</button>
And then I have a script which is:
<script>
alert("My First JavaScript");
</script>
To call this script I can say onclick call another php or html file. But I want to add this script to the same file instead of adding a new file. Any suggestion will be appreciated.
This may be a basic question. I have a button which is
<button type="button">Click Me!</button>
And then I have a script which is:
<script>
alert("My First JavaScript");
</script>
To call this script I can say onclick call another php or html file. But I want to add this script to the same file instead of adding a new file. Any suggestion will be appreciated.
Share Improve this question asked Feb 23, 2014 at 13:38 BernardBernard 4,58019 gold badges59 silver badges93 bronze badges 3- possible duplicate of Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events – Lucky Soni Commented Feb 23, 2014 at 13:43
- I'm new to javascript and I was not able to find it... Anyway thanks for your vote! – Bernard Commented Feb 23, 2014 at 13:45
- Sure, don't take it personally.. its just to keep the site clean :) cheers! – Lucky Soni Commented Feb 23, 2014 at 16:12
5 Answers
Reset to default 5Couple of ways:
1st
<button type="button" onclick="clickHandler()">Click Me!</button>
<script>
function clickHandler() {
alert("something");
}
</script>
2nd (if you are using something like jQuery)
<button id="btn" type="button">Click Me!</button>
$('#btn').click(function() {
alert('something')//
});
you may also do this in plain javascript.. just search for add event handler and you will get plenty of cross browser ways of doing this.
You can invoke alert using:
<button type="button" onclick="javascript:alert('My First JavaScript');">Click Me!</button>
<button type="button" onclick="myFunction()">Click Me!</button>
<script>
function myFunction() {
alert("My First JavaScript");
}
</script>
- Make the script type="text/javascript"
- Close the alert inside a function example function temp(){....}
- add onClick in the button section i.e.
HTML
<button onclick="myFirst()" type="button">Click Me!</button>
<script>
function myFirst() {
alert("My First JavaScript");
}
</script>