How to send paramenter in jquery syntax function? - javascript

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>

Related

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.

javascript onclick function does not run all code in function

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()()

jquery :: Why does hover trigger instantly?

Why does the hover event trigger as soon as the page is loaded?
function showSelector(position) {
alert(position);
}
function hideSelector() {
}
$("#1").hover(showSelector(17), hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup
Because you're calling the function instead of referencing it.
$("#1").hover(showSelector(17), hideSelector);
// ^^^^
Using showSelector(17) as callback to the hover function will call the function first and then assign it's return value to the hover callback. To solve the issue, you can use anonymous function as callback and then call the function inside it with parameters.
function showSelector(position) {
alert(position);
}
function hideSelector() {}
$("#1").hover(function() {
// Use anonymous function
// Call the function with parameter here
showSelector(17);
}, hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup
Because you are invoking the function by adding () at the end, what you can do is to pass a anonymous function as the mouseenter callback which can call showSelector with the desired arguments like
function showSelector(position) {
alert(position);
}
function hideSelector() {}
$("#1").hover(function() {
showSelector(17)
}, hideSelector);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sup

Backbone.js event always activated [duplicate]

i have the following code which extends the JQuery and adds a method to the JQuery:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage());
}
function showMessage() {
alert('hi');
}
so I can use that code as follows :
<input type="text" name="name" id="textbox" />
$(document).ready(function () {
$("#textbox").attachWithMessage ();
});
when I load the page for the first time, a message box shows up with ('hi') message.
even if I didn't click in the text box.
I also tried the click event, and the message still shows automatically.
any ideas ??
The issue here is that when you pass showMessage() as a parameter to focusin, the function showMessage is executed and the return value is passed to focusin.
Instead you need to pass a reference to the function (without the paranthesis).
Use the following code to extend:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage);
}
Working example# http://jsfiddle.net/eXEP5/
EDIT:
If you want to pass a parameter to showMessage then try this:
$.fn.attachWithMessage = function () {
var param1 = "Some Param";
$(this).focusin(function(){
showMessage(param1); //Make sure showMessage is modified accordingly for the parameters.
});
}
just remove the parenthesis
$(this).focusin(showMessage());
should be
$(this).focusin(showMessage);
Hope this helps

Javascript anonymous function vs normal function

What's the difference between:
<script type="text/javascript">
$().ready(function() {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(function() {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
)
})
</script>
and
<script type="text/javascript">
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=SomeLink]").click(CheckValuesChanged(InitialDictionary));
})
function CheckValuesChanged(InitialDictionary) {
if (!CompareDictionaries(InitialDictionary))
{
alert('Hello')
}
}
</script>
Without going into details into what I'm trying to achieve here, is there any reason why an anonymous method works fine and the call to a function doesn't? Shouldn't they produce the same results?
To call a function you have to do this:
$("a[id*=LogoLink]").click(function(){CheckValuesChanged(InitialDictionary)});
Or:
$("a[id*=LogoLink]").click("CheckValuesChanged(InitialDictionary)"); //might work
They both work, but you cannot bind a function to an event like this
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
because the a function must be bound to the click event. When you pass an argument to the function it returns undefined, which is not a function. You can fix this by changing your second code sample like so:
$().ready(function () {
InitialDictionary = new Array();
LoadCurrentValues(InitialDictionary);
$("a[id*=LogoLink]").click(CheckValuesChanged);
function CheckValuesChanged() {
if (!CompareDictionaries(InitialDictionary)) {
alert('Hello')
}
}
});
The second example is wrong:
$("a[id*=LogoLink]").click(CheckValuesChanged(InitialDictionary));
It should be:
$("a[id*=LogoLink]").click(CheckValuesChanged);
But because you want to pass InitialDictionary as argument you need to use the first approach which will capture it in the anonymous function.

Categories

Resources