-2

I have below function in JS file name as hello.js inside js folder.

JS

function hello(){
    alert('hello world !);
}

HTML

<!DOCTYPE HTML>
<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="js/hello.js"></script>
        <script>
            $(function() {
                $("#hello").hello();
            });
        </script>
    </head>
    <body>
        <button type="button" id="hello">Click Me!</button> 
    </body>
    </html>

How do I attach the hello() function to the button with the id="hello"? I'm doing something wrong but I can't find what.

Edit : I recommend reading all answers for completeness.

Edit2: The purpose of this question was to clarify the general method of attaching functions to specific elements on html. The button and the click interaction was an example.

hardstudent
  • 63
  • 1
  • 1
  • 8

4 Answers4

4

You are probably looking to bind click event on button with id hello using hello as handler

$("#hello").click(hello);
Adil
  • 146,340
  • 25
  • 209
  • 204
3

Use .on() to bind event handler.

$("#hello").on('click', hello);
Satpal
  • 132,252
  • 13
  • 159
  • 168
3

There are many ways to handle events with HTML or DOM.

Defining it in HTML

<button type="button" id="hello" onclick="hello();">Click Me!</button> 

Using JQuery

$("#hello").click(hello);

Attaching a function to the event handler using Javascript:

var el = document.getElementById("hello");
    if (el.addEventListener)
        el.addEventListener("click", hello, false);
    else if (el.attachEvent)
        el.attachEvent('onclick', hello);

function hello(){
            alert("inside hello function");
}

Useful links

MDN - onclick event

SO - Ans 1

SO - Ans 2

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48
1

Pure javascript:

var elm=document.getElementById("hello");
elm.onclick= function{ hello();};

Jquery:

$("#hello").click(hello() );
3pic
  • 1,188
  • 8
  • 26
  • 2
    well, `on` is not a native javascript function, and in both examples, function `hello` is called , not passed as parameter. – Hacketo Jul 23 '15 at 12:02
  • Not sure why this answer has *any* upvotes as *it will not work as written*. Please correct your example :) – iCollect.it Ltd Jul 23 '15 at 12:17