Can onclick take a function in a function? - javascript

THis is what I want.
onclick="pager(function2();)
but it doesn't seem to work.

Take out the semicolon:
onclick="pager(function2())"
http://jsfiddle.net/BQYVV/
You are not passing a function to a function, but just a value. When the element is clicked, function2() is called, and it's return value becomes an argument to the pager() function. If function2 does not return anything, pager will receive undefined as an argument.

This works for me
<html>
<head>
</head>
<body>
Click me
<script>
function function2(msg) { alert(msg); };
function function1() { return "Hello World"; };
</script>
</body>
</html>
What's not working in your code?

you can do something like this to make it work
<p onclick="pager(function2())">Click Me</p>
​function pager(fn)​{
return fn;
}
function function2(){
alert('hello');
}

If you're using jQuery, please don't use in-line script, assign the click handler, like this:
$("div").click(function() {
pager(function2());
});
This is if you wanted to assign it to all <div> elements, if you wanted it on a particular element via ID, like this: Link. You would use $("#bob") instead of $("div"). There's a full list of selectors here, if you're familiar with CSS, you'll feel right at home.

Related

Multiple function onClick javascript

Multiple functions on js not executing the first one does but the second one doesnt
onClick="javascript:${ formId }(${ peopleId }, 'userSettingsAddAccountNotificationsModify') contactMethodPopUp() "
You're going about it the wrong way what you could do is have one function onClick and then execute the other inside the that first function.
<button onclick="firstFunc()"><button/>
<script>
function firstfunc(){
//do something
secondFunc()
}
function secondFunc(){
//do something
}
<script/>
Use addEventListener instead of setting the onclick attribute.
You can put multiple functions in onclick like this:
onclick="alert('hey'); console.log('hey');"

html button not calling its onclick js function

Why does this simple alert not work?
HTML:
<button id="mybutton" type="button" onclick="add()">Add</button>
JS:
function add(){
alert("hello???");
}
https://jsfiddle.net/k86mg0aj/
The problem is specific to JSFiddle. You need to change the LOAD TYPE to No wrap - bottom of <body>.
When using onLoad, the function won't become global one, so you can't invoke it directy from HTML. If it is global - like when using no-wrap - it works.
In my opinion the best solution for call a function in current times is to use ES6. You can create for example something like that:
var x = document.querySelector('.class');
x.addEventListener('click', function() {
});
x.addEventListener('click', () => {
});

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");
}

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>

Trying to pass in a callback function fails

I am trying to create some functionality when a user clicks on an element on the webpage. The callback function executes as soon as the page is executed. It is only supposed to execute when the user clicks on an element.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Test</title>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
$("#clickMe").one('click', printThis("Hello All"));
function printThis(msg) {
console.log(msg);
}
</script>
</head>
<body>
<div id="clickMe">Click me!</div>
</body>
</html>
Thanks!
That isn't actually passing the function, but instead it is evaluating the function and passing the result as the callback parameter (in this case, undefined).
Try this instead
<script>
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() {
printThis("Hello All");
});
</script>
Don't invoke the callback. Pass an anonymous callback function that invokes the function you want.
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() { printThis("Hello All") });
one method takes a callback as the second parameter. printThis("Hello All") will actually call the method there itself so on click of clickMe nothing will happen as there is no handler attached. Try this
function printThis(msg) {
console.log(msg);
}
$("#clickMe").one('click', function() { printThis("Hello All") });
The answer already posted is right:
$("#clickMe").one('click', function() { printThis("Hello All") });
This is known as a closure: https://developer.mozilla.org/en/JavaScript/Guide/Closures
A closure is a function, often declared as an inline/anonymous block of code, that delays the execution of your function and stores the value of that "Hello All" argument that you want to pass in.
jQuery will store this "function() {...}" code block as an event handler, and then later when the #clickMe element is clicked, that code block will be executed, which in turn will call the printThis function.
You will find yourself using this pattern quite often with jQuery.
Try this ... http://jsfiddle.net/PcVJq/

Categories