5

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.

Bernard
  • 4,240
  • 18
  • 55
  • 88
  • possible duplicate of [Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events](http://stackoverflow.com/questions/3763080/javascript-add-events-cross-browser-function-implementation-use-attachevent-add) – Lucky Soni Feb 23 '14 at 13:43
  • I'm new to javascript and I was not able to find it... Anyway thanks for your vote! – Bernard Feb 23 '14 at 13:45
  • Sure, don't take it personally.. its just to keep the site clean :) cheers! – Lucky Soni Feb 23 '14 at 16:12

5 Answers5

5

Couple 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.

Lucky Soni
  • 6,811
  • 3
  • 38
  • 57
2

You can invoke alert using:

<button type="button" onclick="javascript:alert('My First JavaScript');">Click Me!</button>
Kiran
  • 20,167
  • 11
  • 67
  • 99
2
<button type="button" onclick="myFunction()">Click Me!</button>



<script>
    function myFunction() {
        alert("My First JavaScript");
    }
</script>
Matúš Bartko
  • 2,425
  • 2
  • 30
  • 42
1
  1. Make the script type="text/javascript"
  2. Close the alert inside a function example function temp(){....}
  3. add onClick in the button section i.e.
Jamie Tabone
  • 581
  • 1
  • 4
  • 7
1

HTML

<button onclick="myFirst()" type="button">Click Me!</button>

<script>
function myFirst() {
    alert("My First JavaScript");
}
</script>
Jonathan
  • 8,771
  • 4
  • 41
  • 78