Can you create a javascript function on an event handler? - javascript

can you call a javascript function on event handlers? What I mean is like,
... onClick="dosomething()">
<script type="text/javascript">
function dosomething(){alert("I just did something");}
the code isn't complete but i've tried it this way all nice and neat and it doesn't work, does this mean we have to enter the whole JS code inside the event handler???

You can attach the event handler without specifying it inline. If you know the id of the element its pretty simple.
Javascript
function doSomething(){
alert("I just did something");
}
var elem = document.getElementById("idGoesHere");
elem.onclick = function(){
doSomething();
}
HTML
<div id="idGoesHere">Click Me</div>
JS Fiddle: http://jsfiddle.net/DYqjA/

<script>
document.getElementById("myBtn").onclick=function(){dosomething()};
function dosomething(){alert("I just did something");}
</script>
Crude example using JavaScript

Related

How can I get the function bound to an onclick attribute?

I've got a function bound to the onclick event in the html, like so:
<script>
function f1(){ alert('hello world'); };
</script>
<a onclick="f1()">test</a>
I'd like to do something with that function, like bind it to another event. I tried this in jQuery:
var defaultFunction = $('a').attr('onclick');
but defaultFunction is defined as a string rather than the function itself. I can evaluate it with eval(defaultFunction), but that makes me feel dirty. Is there a way I can access the function itself, rather than the string?
i.e. I'd like to be able to call defaultFunction() and do whatever the default onclick behavior bound to the a element is. (In this case, call f1()).
Here's a fiddle that tries to do that, but fails.
see this document.getElementById("id_of_your_element").onclick if that help you, it will return click handler, and you can call that, but its not right to raise events manually
Something like this:
Example
var defaultFunction = $('a').attr('onclick');
var defaultFunctionName = defaultFunction.substring(0, defaultFunction.indexOf('('));
$('div').on('click', function(){
if(typeof window[defaultFunctionName] ==="function")
{
window[defaultFunctionName]();
}
alert('Hello universe!');
});
It's just onclick attribute, no jQuery required:
<script>
function f1(){ alert('hello world'); };
</script>
<a onclick="f1()" id="aa">test</a>
<a id="bb">test2</a>
<script>
bb.onclick = aa.onclick;
// or
bb.onclick = function (){ alert('hello bb'); };
</script>
Use this:
function f1() {
alert('hello world');
};
$('a').on('click', f1);
Here is your fiddle with the fix: http://jsfiddle.net/o8b5j15k/2/
Instead of attempting to copy the function bound inline, you could trigger the click event programatically:
function defaultFunction() {
$("a[onclick]").click(); // change selector to match your actual element
}
http://jsfiddle.net/o8b5j15k/3/
Its best to use addEventListener() you can add all types of events. example: "click", "mousemove", "mouseover", "mouseout", "resize" and many more. the false at the end is to stop the event from traversing up the dom. If you want parent dom objects to also receive the event just change it to true. also this example requires no javascript libraries. This is just plain old javascript and will work in every browser with nothing extra needed.
Also addEventListener() is better than onClick() as you can add an unlimited number of event listeners to a dom element. If you have an onClick() on an element and then set another onClick() on the same element you have overwritten the first onClick(). Using addEventListener() if i want multiple click events to trigger when i click on an element i can do it with no problem.
If you want data about the element that is triggering the event you can pass the event to the function. You will see in my example function(e) e is the event and you can use e or this to target the element that is being triggered. Using e or this i can also get more data about the triggered event. for example if the event was a mousemove or mouseclick i can get the x and y position of the mouse at the time of the event.
<!DOCTYPE html>
<html>
<head>
<title>exampe</title>
</head>
<body>
<a id="test" href="">test</a>
<script>
document.getElementById("test").addEventListener("click",function(e){
alert('hello world');
alert('my element '+e);
alert('my element '+this);
},false);
</script>
</body>
</html>
if you want to have addEventListener call a function just change the 2nd value to the function name like this.
document.getElementById("test").addEventListener("click",f1,false);
this will execute the function
function f1(){ ... }
When you want to remove an event listener just call target.removeEventListener(type, listener[, useCapture]). Very simple and easy to manage.

JS code fires on page load instead of waiting for click event

I'm having difficulty with this code. I'm trying to get the JS to execute on a click event however, it is executing when the page loads and also when the user clicks. Any help is much appreciated!
<body>
click me!
</body>
<script type="text/javascript">
window.onload = function () {
document.getElementById('calc').onclick=xfx()
}
xfx = function (){
alert("x");
}
</script>
</body>
You are invoking the function instead of assigning it to the on click event
This should do it:
document.getElementById('calc').onclick = xfx;
The line
document.getElementById('calc').onclick = xfx();
means that you want to assign the onclick to the results of the xfx() call.
You probably want
document.getElementById('calc').onclick = xfx;
which means that you want to assign to onlick the xfx function itself.
I'd use addEventListener to look for the click on your variable; like so:
var clickMe = document.getElementById('calc');
clickMe.addEventListener('click', function () {
alert("hello!");
});
Where your variable is clickMe, defining the id 'calc', and when clicked it triggers the alert.
Here's the fiddle, http://jsfiddle.net/89Nvb/
Should be
function xfx() {
alert("x");
}

onclick function need to execute a simple javascript function

I have a button where I am trying to add on click jquery as below
<button onclick="myFunction()">YES</button>
And
$(document).ready(function() {
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})
However, on click I am getting Uncaught ReferenceError: myFunction is not defined
What am I doing wrong and how to fix this?
Updated with a sample jsfiddle
http://jsfiddle.net/3aC7W/1/
What am I doing wrong and how to fix this?
You are defining the function inside another function, i.e. the function is not defined in global scope and hence cannot be found by the inline event handler.
Just remove $(document).ready(function() { because you don't need it there:
function myFunction(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
You only have to use $(document).ready(function() { ... }); if you manipulate the DOM, and also only if you place the script before the elements in the HTML document.
The better solution of course would be to bind the event handler with jQuery (and not use inline event handlers):
$(document).ready(function() {
$('button').on('click', function(){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
You might have to add a class or ID to the button to make the selector more specific. Have a look at the list of available selectors.
change your code to this way to achieve click :
<button id="myFunction">YES</button>
and
$(document).ready(function() {
$('#myFunction').click(function(e){
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
});
});
check it at: http://jsfiddle.net/aneesh_rr/XJ758/3/
change your code to this:
$(document).ready(function() {
window.myFunction = function(){ //you should make myFunction avaliable in global
$('#mycheckboxdiv').toggle();
$("div#headersteptwo").addClass("hidden");
}
})

Toggle text with function called with onclick

my question is a short one but I couldn't figure it out by myself. I've got a function like -> http://jsfiddle.net/gtU56/ . I'm calling a javascript-function with an event-listener(onclick) in my html-code. The function itself is more complex but I need the last snippet. By clicking 'Show More' the text should change. Why won't the text change?
Because the toggleText function isn't available when the html code is rendered.
In other words the function isn't set until the page is ready so the onclick function doesn't reference anything.
Either have the function like here http://jsfiddle.net/gtU56/2/
or have it in the head of the page because its needs to be ready immediately
If you want it to wait for the ready state you can do the following and remove the onclick action all together
http://jsfiddle.net/gtU56/7/
$(".text").click(function()
{
$(".text").toggle();
});
toggleText = function () {
$('.text').toggle();
}
check here http://jsfiddle.net/gtU56/3/
It's because of how you're loading the function. Switch it from onLoad to no wrap (head) and it works fine.
jsFiddle example
Using jsFiddle's onLoad wraps your function in a window.onload call like this:
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
function toggleText() {
$('.text').toggle();
}
});//]]>
</script>
While no wrap (head) just adds it normally like this:
<script type="text/javascript">
//<![CDATA[
function toggleText() {
$('.text').toggle();
}
//]]>
</script>
since you are already claiming having jquery, you need not use inline javascript. try this
var elems = $('.text');
elems.click(function(){
elems.toggle();
});
fiddle : http://jsfiddle.net/gtU56/5/
$('.text').click(function() {
$('.text').toggle('slow', function() {
// do your animation..
});
});
​
Js Fiddle
This is the solution - http://jsfiddle.net/gtU56/6/
You need to first make sure that the function is registered after page load. Then, bind a click event to the div.
Hope this helps!
First you should organize you jQuery code like this:
$.(document).ready(function() {
// enter jQuery code here
});
Otherwise you're accessing a not completly loaded html document.
Also, you don't need the event-listener if you are using jQuery.
This should work for you:
$.(document).ready(function() {
$('.text').click(function() {
$(this).toggle();
});
});
Is very easy. You can use ID or CLASS.
onclick="$('NAME ID or CLASS').toggle(ANIMATION or DURATION);"
<div>
<div class="text" onclick="$('.text2').toggle(400);">Show More</div>
<div class="text2" style="display:none">Show Less</div>
</div>

How to put a Javascript event on something?

I have a pre-made layout, cannot be changed. But I must put an onload() event to <BODY>. As I said, I'm not allowed just add "onload = sdfsdf" event. Then how?
You could make a script to attach the event (i suppose that your problem is that you have no control over the html):
<script>
document.body.onload = function(){};
</script>
Use JQuery:
$(document).ready(function() {
});
http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29
You can register events on the body through a (java)script using:
document.body.<event name> = function(){ // whatever your function does };
Use window.onload = function(){ ... }. That has the equivalent result as <body onload="...">.
put all your code in an function that autoexecute:
(function () {
//your code here
})();
and put it at the end of the body.
If you want to make everything by yourself, without jQuery. MDN addEventListener.
target.addEventListener(type, listener, useCapture<Optional>);
Depending on the required effect, listener:
DOMContentLoaded - loading of the DOM
load - loading of all the resource on the page - useful if the page contains large images

Categories