-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
  • 143,427
  • 25
  • 201
  • 198
3

Use .on() to bind event handler.

$("#hello").on('click', hello);
Satpal
  • 129,808
  • 12
  • 152
  • 166
  • Why `on` for a simple `click` handler case? Just makes the code longer and no extra gain here. – Gone Coding Jul 23 '15 at 11:54
  • You very well know `click` is just shorthand for `.on( "click", handler )`. So why not tell OP the use of `.on()` – Satpal Jul 23 '15 at 11:59
  • because, as I said, *it is longer* (6 characters longer to be precise)... One of the aims for JS code is conciseness :P – Gone Coding Jul 23 '15 at 12:01
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
Simpal Kumar
  • 3,765
  • 3
  • 26
  • 48
1

Pure javascript:

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

Jquery:

$("#hello").click(hello() );
3pic
  • 1,200
  • 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 :) – Gone Coding Jul 23 '15 at 12:17