javascript onclick function does not run all code in function - javascript

This onClick function does not run the console.log in the code snippet below, any ideas?
var clickFunction = function myfunc() {
return function (){
return console.log('here');
}
};
<button onClick="clickFunction()"> Click here</button>
Thanks for your time

Because you're calling a function that returns a function. If you want to run the function that is returned you would need to do: clickFunction()()

Related

How to call a function 10 seconds after calling another function?

I have two functions, functionOne() and functionTwo().
How can I go about calling functionTwo() 10 seconds after functionOne() ends/is called?
I'd like functionOne to occur after a button is clicked, and then functionTwo 10 seconds after functionOne ends (without the need to click a button again/have the user do anything!)!
See below for my code!
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
}
functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
I tried to use setTimeout, but the problem is that I don't think there is an 'onend' event I can use for the first function. Eg:
setTimeout(functionOne.onend, 10,000);
This code calls functionOne onClick and calls functionTwo 10 seconds later.
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
function functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
setTimeout(() => functionTwo(), 10000);
}
function functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
Most importantly you have to declare your functions properly using the function keyword: function functionOne, function functionTwo.
Here's the documentation for setTimeout: "The global setTimeout() method sets a timer which executes a function... once the timer expires." So you pass in the function that you want to execute once the timer has completed.
And here are some more methods of approaching the problem.
Cache your paragraph element along with the button up front so you're making the code as DRY as possible.
Move the inline JS to the script, and use addEventListner to the para element
Use textContent instead of innerHTML because you're not adding HTML
// Cache the elements
const para = document.querySelector('#paragraphChange');
const button = document.querySelector('#clickToChangeText');
// Add a listener to the button
button.addEventListener('click', functionOne, false);
// Set the text content of the para element
// and then call the second function with a time out
function functionOne() {
para.textContent = 'Bye World';
setTimeout(functionTwo, 5000);
}
// Update the para with new text
function functionTwo() {
para.textContent = 'Jokes I\'m still here';
}
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText">Click!</button>
Define functionTow() first.
function functionTwo() {
//code to be execute
}
The call functionTwo in functionOne's body using setTimeout.
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}
I don't think there anything called onend in JavaScript you have to use setTimeout(functionTwo, 10000) at the end of functionOne() like this:
function functionTwo() {
//code to be execute
}
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}

JS removeEventListener with function inside

I've created a function search with an event listener on a button. The problem is that the removeEventListener isn't working because init() is inside it to execute. Thus the EventListener is replicated everytime I click the button. If I remove init() all is fine. Maybe i misunderstand someting about it?
Also if i remove the function search and only use const I know it fires ones. But the whole point is that i need to use search.
function search(data) {
const clickHandler = () => {
console.log('search');
init();
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
}
search(data);
function init() {
console.log('hello');
}
console results:
first time; hello
second time; hello hello
third time; hello hello hello hello
The problem here is scoping. When you put the function inside another, it is scoped to that function. So next time you call the function, you create a new function. So you are trying to remove a function that did not exist before.
function clickHandler2() {
console.log('world');
}
function search() {
const clickHandler = () => {
console.log('hello');
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
document.getElementById('search').removeEventListener('click', clickHandler2);
document.getElementById('search').addEventListener('click', clickHandler2);
}
search();
search();
search();
<button type="button" id="search">Search</button>

How to send paramenter in jquery syntax function?

i want click the button call function with parameter but i don't know how to write syntax
$(document).ready(function () {
$('#ShowMap').on('click', initialize);
})
function initialize(value) {
alert(value);
}
if change code for code down code work but after load page function called
$(document).ready(function () {
$('#ShowMap').on('click', initialize("test"));
})
how to fix the problem ?
This doesn't send the function as a parameter, it immediately executes the function and sends the result (which is undefined) as the parameter:
$('#ShowMap').on('click', initialize("test"));
Instead, wrap it in a function to be the parameter:
$('#ShowMap').on('click', function () { initialize("test"); });
You can pass another function as argument and inside that function call the desired function
$('#ShowMap').on('click', initialize("test")); will not send function as argument it will send the return value of the initialize which is undefined
function initialize(value){
console.log(value);
}
$(document).ready(function () {
$('#ShowMap').on('click',() => initialize("test"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="ShowMap">Show Map</button>

dynamically change assigned click function

<div id='example' data-fn='functiona'>OK</div>
$('#button').click function(){
$('#example').attr('data-fn', functionb');
});
function functiona(){
console.log('functiona');
}
function functionb(){
console.log('functionb');
}
$('#example').click(function(){
// execute function currently stored inside data-fn attribute
});
Probably everything is clear.
I need dinamically change the function which will be executed by clicking on example.
The current function should be stored inside data-fn.
Any help?
What you want to do is described in Can you set a javascript function name as an html attribute?
But I suggest that you solve it that way:
$('#button').click(function() {
$('#example').off('click.myNamespace') // remove the previously assigned callback
.on('click.myNamespace', creatClickCallback(functionb)); // register the new callback
});
function functiona() {
console.log('functiona');
}
function functionb() {
console.log('functionb');
}
function creatClickCallback(functionToCall) {
return function(evt) {
functionToCall()
}
}
$('#example').on('click.myNamespace', creatClickCallback(functiona));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example'>OK</div>
<div id='button'>button</div>
This way you ensure that you do not accitantily name a function the wrong way, because you pass it as an actual reference to that function instead of a string.
Couldn't you just store the function name, then when you click you check which function is then call it and update the function to which one you want?
Something like this:
function functiona(){
console.log('called functiona');
document.body.style.background = '#aaa';
}
function functionb(){
console.log('called functionb');
document.body.style.background = '#fff';
}
$('#example').on("click", function(ev){
var func = $(ev.target).attr('data-fn');
console.log(func);
window[func]();
});
$('#changer').on("click", function(ev){
//HERE you can change the function will be called based on what you want
//Here I just changed it with a simple if...
var fn = $("#example").attr("data-fn");
if (fn == 'functiona'){
$("#example").attr("data-fn", "functionb");
}else {
$("#example").attr("data-fn", "functiona");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example' data-fn='functiona'>Click Me to call function</div>
<button id='changer'>Change Function</button>
Here, the global variable window have your functions stored, so going through it by it's name and calling it, should work, if this name exist as a function window[stringOfFuncionName]();
This is not the best way of doing what you need (actually you didn't let completely clear your final objective), but this maybe can help.

Jquery Click-handler doesn't work with named function?

I feel like this is one of those problems you only run into after too little sleep or too many coffees...
I have an element
<a id="blah" href="#">somethinghere.com</a>
I define a function
function test(){
alert('hi');
};
I try to attach the function as a click-handler(https://jsfiddle.net/8r1rcfuw/30/):
$('#blah').on('click', test());
and load the page, and the handler executes immediately - without any clicks.
However when I just use an anonymous function as a handler(https://jsfiddle.net/8r1rcfuw/36/) :
$('#blah').on('click', function(){
alert('hi');
});
it works fine
Doing both (https://jsfiddle.net/8r1rcfuw/39/):
$('#blah').on('click', function(){
test();
});
function test(){
alert('hi');
}
seems to work fine - but seems a little redundant.
This feels like something I've done 1000 times before - what gives?
The event handler has to be a function, and you are passing the result of a function to it:
$('#blah').on('click', test());
is the same as:
$('#blah').on('click', undefined); //As your funcion doesn't return anything
Think of it as a function is a value, you can do:
var myFunction = function() {
alert("Hi");
}
or
function myFunction() {
alert("hi");
}
And then:
$('#blah').on('click', myFunction); //Without invocation!
or using an anonymous function:
$('#blah').on('click', function() {
alert("Hi");
});
You can also use object of function :
var temp=function test() {
alert('hi');
}
$('#blah').on('click', temp);
Try :
$('#blah').on('click', test); // your function name only
Updated Fiddle

Categories

Resources