Call JS function for specific id in HTML - javascript

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.

You are probably looking to bind click event on button with id hello using hello as handler
$("#hello").click(hello);

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

Use .on() to bind event handler.
$("#hello").on('click', hello);

Pure javascript:
var elm=document.getElementById("hello");
elm.onclick= function{ hello();};
Jquery:
$("#hello").click(hello() );

Related

How to add onmouseover styling to an element through javascript?

Attempting to remove and reapply function to the onmouseover event of an element. Not sure how to go about this, have attempted several ways without any luck.
<!DOCTYPE html>
<html>
<body>
<button id="my_button" onmouseover="myFunction(this)">Try it</button>
<script>
function myFunction(ele) {
alert("hi")
document.getElementById("my_button").onmouseover = "null";
document.getElementById("my_button").onmouseover = "myFunction(this)";
}
</script>
</body>
</html>
The issue is that you're setting the button onmouseover property to a string in myFunction instead of to a function object.
The HTML parser creates an anonynmous handler function from the onmousever attribute value for you, but setting the button property to a string in JavaScript won't create such a function. Try
<!DOCTYPE html>
<html>
<body>
<button id="my_button" onmouseover="myFunction.call(this, event)">Try it</button>
<script>
function myFunction(event) {
alert("hi, this.tagName = " + this.tagName)
document.getElementById("my_button").onmouseover = "null";
document.getElementById("my_button").onmouseover = myFunction; // a function object
}
</script>
</body>
</html>
Notice I've modified myFunction to see the button object as its this value, and its argument to be the mouse event raised for the click, and changed the call in the handler generated by the HTML to call myFunction as if it were the actual event handler. This was to keep the calls to myFunction seeing the button as its this value and event as its argument in both cases.
For more about the handler created by the HTML parser see a previous answer (disclaimer: of mine) to 'this inside event handler from HTML attribute' that goes into greater detail.
Note that for various reasons it is no longer recommended to create event handlers using oneventname attribute values in HTML when you can add them using element.addEventListener in JavaSript as part of initialization.
you can use :
<button id="my_button" onmouseover="alert('hi')">Try it</button>
try
<!DOCTYPE html>
<html>
<body>
<button id="my_button" class="mousemove" >try it</button>
<script>
document.getElementsByClassName("mousemove")[0].onmousemove = function(){
alert("hi")
document.getElementById("my_button").onmousemove = function(){ return null }
}
</script>
</body>
</html>

How to write jQuery code or call jQuery function in onclick attribute

Why doesn't this simple code work?
<div onClick="myFunction()"></div>
$(document).ready(function(){
function myFunction(){
alert("sss");
}
})
The JS file is external and it's called in the head of my HTML page. The jQuery library is added before that.
It doesn't work as functions called from the on* event attributes need to be within scope of the window. Your code places the function within the jQuery document.ready handler instead. Try this:
function myFunction() {
alert("sss");
}
<div onClick="myFunction()">Click me</div>
You should note though, that using on* event attributes is considered outdated for this reason, amongst many. You should instead use unobtrusive JS code to attach your event handlers, either in native JS:
document.querySelector('div').addEventListener('click', function() {
alert("sss");
});
<div>Click me</div>
Or jQuery, as you seem to be using it already:
$(function() {
$('div').on('click', function() {
alert("sss");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click me</div>
First Go and read tutorials of html and Jquery at some tutorial websites like This or thisone.
and answer to your code is
HTML
<button onclick="myFunction()">Click me</button>
Javascript
function myFunction() {
alert('Hello');
}
Assuming you included JQuery libraries.

addEventListener() not responding

I have written a small program to pop up an alert on click of a button using an addEventListener() . PFB the code below:
html file
<html>
<head>
<title>name alert</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input id="p" type="button" value="alert">
</body>
</html>
javascript file
document.getElementById("p").addEventListener("click",greet,true);
function greet(){
alert("hello there !");
}
I dont get a pop up screen this way both the files are in the same folder btw.
test.js loads and executes before the DOM is loaded. So, at that point #p returns null. Try listening to onload event, and add click event.
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("p").addEventListener("click",greet,true);
});
// global scope
function greet(){
alert("hello there !");
}
<input id="p" type="button" value="alert">
try to move your
<script type="text/javascript" src="test.js"></script>
just before
</body>
You need to put the addEventListener inside a function that is called on the load event. As the page is being created it will run the javascript as it comes to it. If it hasn't created the HTML yet, when the addEventListener runs it won't find the 'p' element and it will give you an error.
You can also move the javascript to be after the html, but it's more organized to put it in something like this:
<script type="text/javascript">
window.addEventListener('load', 'function(){pageload()}', false)
function pageload()
{
document.getElementById("p").addEventListener("click",greet,true);
}
</script>

Dynamic event-function binding isn't happening in vbscript / javascript

Button 1 works fine, but when I try to insert button 2 dynamically the onclick event doesn't call its mapped function, any clue how it works? This is a simple example but later I need to capture events from complex object like trackbar's scroll event.
<html>
<head>
<title>a simple first page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
</script>
<script language="vbscript">
Sub Button1_OnClick()
MsgBox "button 1"
End Sub
Sub Button2_OnClick()
MsgBox "button 2"
End Sub
</script>
</head>
<body>
<form id="form"><input id="button1" type="button"
value="button 1"></form>
</body>
</html>
If you are adding a new button to the DOM dynamically use the live() function of jquery:
$('[type=button]').live('click', function() { alert('Clicked button'+$(this).val(); } );
That'll add events to all current DOM elements and 'yet' to be created ones!
I am not sure about VB script but this, you can attach a handler to any your button using jQuery live function or by assigning function on onclick event while creating your input and appending to form.
see example
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
function button_2(){
alert('message 2')
}
// using jQuery live
$('#button2').live('click',button_2);
// other way attaching onclick value to input while creating it
$(document).ready(function() {
$("#form").append("<input onclick='button_2()' id='button2' type='button' value='button 2'>");
});
</script>
How does Button1_Click get called at all? Is there some sort of implicit binding in IE, that I don't know about? The way I'd do it is to add an event with attachEvent().
IE not allowing onClick event on dynamically created DOM 'a' element

Javascript, load onclick at pageload, whats broken?

I'm a dizzy designer. I can't can't see why this isn't working:
<head>
<script type="text/javascript">
$().ready(function() {
$('#test').trigger("click");
});
</script>
</head>
<body>
<a id="test" href="http://www.dartworks.net" >click here</a>
</body>
what am i doing wrong?
you didn't attach any click event to the <a> tag you just output it as a link
use the window.location.href like this :
$(document).ready(function() {
window.location.href = "http://www.dartworks.net";
});
The trigger method will fire all the event handlers bound to that event. Following the link is default behaviour, not something caused by a DOM event handler.

Categories