Jquery execute two functions on click - javascript

I am trying to execute functions on click, Below is click button on HTML,
Insights.init() will execute on page load will give me some data from server, now with click on button, i need to pass variable to month function to filter data, and with click i want to execute all functions inside Insights()
var Insights = function() {
var initCheckColor = function(vari) {
console.log(vari);
}
var testFunction = function(vari) {
console.log('test');
}
return {
init: function() {
initCheckColor();
testFunction();
}
};
}();
jQuery(document).ready(function() {
Insights.init();
});
function month(vari) {
console.log("hoo");
return {
init: function() {
initCheckColor(vari);
testFunction();
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Month
Now problem is, i can see "hoo" printed on console when i click on link, but i also want to print it with execution of initCheckColor(vari) function, means i want output two times, but i could not output it,
How can i get output two times?

Problem: Is with this code
function month(vari) {
console.log("hoo");
//this block of code
return {
init: function() {
initCheckColor(vari);
testFunction();
}
};
// upto here
}
When you call the month function you are returning a object with a property named init Note: you are just returning a object and not executing the functions within the property. Also other issue is this property is a function which executes two other function, But those functions are not available in the current scope. As they are equal to Private methods for the Insights object.
Solution: Would be to re initialize the object with data just like how you are doing on page load.
I have fixed your code and added comments in the code where the changes were made.
var Insights = function() {
var initCheckColor = function(vari) {
console.log(vari);
}
var testFunction = function(vari) {
console.log('test');
}
return {
init: function(vari) { // have a input parameter during initialization.
initCheckColor(vari);
testFunction();
}
};
}();
jQuery(document).ready(function() {
Insights.init('something'); // I pass in the string "something" now this will be printed by the initCheckColor function.
});
function month(vari) {
console.log("hoo");
Insights.init(vari); // initialize the Insights object by passing in some value.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Month

Related

Passing variable that detects specific button in jQuery

I created function that recognize which post has been clicked on.
jQuery(document).ready(function() {
jQuery(.recognize-post).on("click", function() {
var clickedButton = jQuery(this).data("id")
console.log("click button with post id: ", clickedButton)
button-id = "recognize-post"
...
...
})
})
}
html
<button id="recognize-post" class="recognize-post" data-id="<?php the_title() ?>">POST</button>
Code above works perfectly and in recognizes the correct post, but I need to pass clickedButton outside of this function and I don't know how to do so.
I need to have it in else if function, this is my attempt
else () {
...
} else if (button-id === "recognize-post") {
console.log(clickedButton)
}
Here the problem comes, clickedButton is underfined and need it to recognize post in exactly the same way how in on click function. Is it possible?
You can make a separate function that takes in the information you want to preserve.
// make a new function
function doSomethingWithTheIdAndBtn(id, btn) {
// take in arguments that represent the id or btn or whatever you need
else () {
...
} else if (id === "recognize-post") {
console.log(btn)
}
}
jQuery(document).ready(function() {
jQuery(.recognize-post).on("click", function() {
var clickedButton = jQuery(this).data("id")
console.log("click button with post id: ", clickedButton)
button-id = "recognize-post"
doSomethingWithTheIdAndBtn(button-id, clickedBtn) // call the function
...
...
})
})
}
So, the issue here is that if you declare a variable function in a given "scope" — in your case, the anonymous function's scope — it will only be defined inside of that scope. If you want to use the variable outside of the function, you need to declare it outside of the function.
So, for instance, if your code was
function foo() {
var myVariable = 0;
}
foo();
// This will throw an error, cuz myVariable is not defined in this scope
console.log(myVariable);
you could fix it by declaring the variable outside of the function's scope
var myVariable; // declare it outside of the function
function foo() {
myVariable = 0; // give it a value inside of the function
}
foo(); // call foo so that myVariable has a value
console.log(myVariable); // this will print 0. Success!

create method event in javascript class

In the wapp.js I have the following class in JavaScript:
function Wapp() {
this.page = function($page_name) {
this.onLoad = function($response) {
}
}
this.navigate = {
changePage: function(link) {
// Ajax request to load the page
$.post(link, {}, function(response) {
// Code to display the page
});
}
}
}
in the app.js script I have the following code:
var wapp = new Wapp();
and I want to do this:
wapp.page('home').onLoad(function() {
// doSomething();
}
// When I call the method 'changePage'
wapp.navigate.changePage('home');
// at the end of the page load 'home' I want to call the function 'doSomething()' inside the 'onLoad' method
how should I define the methods within the class to make sure that at the end of a certain action (in this case at the end of the ajax call) to run the code defined within the 'onLoad' method in app.js?
You are able to assign a function as variable to your class when constructing it. You'll be able to call assigned function later in your code (e.g. in end of the other function)
https://jsfiddle.net/L8c2s6xr/
function func (functionToCall) {
this.functionToCall = functionToCall;
this.doSomething = function () {
this.functionToCall();
}
}
var f = new func (
function() {
alert('this works');
}
);
f.doSomething();

How to invoke a function from both an outside and a sibling function in javascript / google app script

Basic question but I can't figure it out :(. A solution to one makes the other one break. Here is the specific case narrowed down, any help is appreciated.
function onOpen() { // first entry point
var helper = new level1Function();
helper.level2FunctionA();
}
function onFormSubmit() { // second entry point
var helper = new level1Function();
helper.level2FunctionC();
}
function level1Function() {
this.level2FunctionA = function() {
console.log('hi');
}
function level2FunctionB() {
// how do I invoke level2FunctionA from here w/o breaking onOpen entry point?
}
this.level2FunctionC = function() {
level2FunctionB();
}
}
onOpen();
onFormSubmit();
// looking for 2 hi's to the console, one through each flow
create a reference to a variable self, assign to this at the top of the function body
function level1Function() {
var self = this;
this.level2FunctionA = function() {
console.log('hi');
}
function level2FunctionB() {
self.level2FunctionA();
}
this.level2FunctionC = function() {
level2FunctionB();
}
}
Another solution, instead of creating a reference to self as that is error-prone in many situations, you could use Function.prototype.bind and create a function boundLevel2FunctionB, which has this bound to the current level1Function instance (I see you're calling it using the new keyword).
Code:
[...] // level2Function body
function level2FunctionB() {
this.level2FunctionA();
}
var boundLevel2FunctionB = level2FunctionB.bind(this);
this.level2FunctionC = function() {
boundLevel2FunctionB();
}
[...]
Cheers!

Passing functions in parameter, to be run on load

This is the global function that runs on load:
$.fn.loadfns = function(specificfns) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
specificfns;
})
})
});
};
Problem is, some pages require additional functions to be run after load (like inserting events into glDatePicker), so I'm trying to pass them as parameters for loadfns, like
$.fn.loadfns("alert('I won't be run');");
But nothing happens, it's not executed. If I do
... rest of function ...
$('#wrapper').fadeIn(600, function() {
alert(specificfns);
})
It alerts "alert('I won't be run');" (without brackets) which should work as a function.
To pass a function around, you pass a function around, not a string.
If you want to allow just one extra function (which can, of course, call others):
$.fn.loadfns = function(extraFunction) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
if (extraFunction) {
extraFunction();
}
})
})
});
};
Used like this:
$("....").loadfns(function() {
alert("Do something");
});
If you want to allow multiple extra functions, pass in an array:
$.fn.loadfns = function(extraFunctions) {
$('#wrapper').hide();
$('#load').fadeIn(400);
$(window).load( function() {
$('#load').fadeOut(400, function() {
$('#wrapper').fadeIn(600, function() {
var index;
if (extraFunctions) {
for (index = 0; index < extraFunctions.length; ++index) {
extraFunctions[index]();
}
}
})
})
});
};
(Of course, if you're in an ES5-enabled environment or using a shim, you might use forEach instead of the for loop.)
Used like this:
$("....").loadfns([doSomething, doSomethingElse]);
function doSomething() { /* ... */ }
function doSomethingElse() { /* ... */ }
// They don't have to be named, it's just clearer this way than with inline ones
You might consider putting try/catch blocks around the calls to the functions if you want to handle exceptions from them.

cannot access function within function in javascript

I need to know what I am doing wrong because I cannot call the internal functions show or hide?
(function()
{
var Fresh = {
notify:function()
{
var timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && (show(),setTimeout(hide(),timeout));
var show = function ()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
thanks, Richard
UPDATE
If you wanted to be able to do something like: Fresh.notify.showMessage(), all you need to do is assign a property to the function notify:
var Fresh = {notify:function(){return 'notify called';}};
Fresh.notify.showMessage = function () { return this() + ' and showMessage, too!';};
Fresh.notify();//notify called
Fresh.notify.showMessage();//notify called and showMessage, too!
This will point to the function object here, and can be called as such (this() === Fresh.notify();). That's all there is too it.
There's a number of issues with this code. First of all: it's great that you're trying to use closures. But you're not using them to the fullest, if you don't mind my saying. For example: the notify method is packed with function declarations and jQuery selectors. This means that each time the method is invoked, new function objects will be created and the selectors will cause the dom to be searched time and time again. It's better to just keep the functions and the dom elements referenced in the closure scope:
(function()
{
var body = $("body");
var notifyDiv = $("#notify-container div")[0];
var notifyDivEq0 = $("#notify-container div:eq(0)");
var show = function ()
{
body.animate({marginTop: "2.5em"}, "fast", "linear");
notifyDivEq0.fadeIn("slow");
};
var hide = function()
{//notifyDiv is not a jQ object, just pass it to jQ again:
$(notifyDiv).hide();
};
var timeout = 20000;
var Fresh = {
notify:function()
{
//this doesn't really make sense to me...
//notifyDiv.id.substr(7,1) == "1" && (show(),setTimeout(hide,timeout));
//I think this is what you want:
if (notifyDiv.id.charAt(6) === '1')
{
show();
setTimeout(hide,timeout);//pass function reference
//setTimeout(hide(),timeout); calls return value of hide, which is undefined here
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
It's hard to make suggestions in this case, though because, on its own, this code doesn't really make much sense. I'd suggest you set up a fiddle so we can see the code at work (or see the code fail :P)
First, you're trying to use show value when it's not defined yet (though show variable does exist in that scope):
function test() {
show(); // TypeError: show is not a function
var show = function() { console.log(42); };
}
It's easily fixable with moving var show line above the point where it'll be called:
function test() {
var show = function() { console.log(42); };
show();
}
test(); // 42
... or if you define functions in more 'traditional' way (with function show() { ... } notation).
function test() {
show();
function show() { console.log(42); };
}
test(); // 42
Second, you should use this instead:
... && (show(), setTimeout(hide, timeout) );
... as it's the function name, and not the function result, that should be passed to setTimeout as the first argument.
You have to define show and hide before, also change the hide() as they said.
The result will be something like this:
(function()
{
var Fresh = {
notify:function()
{
var show = function()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
},
timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && ( show(), setTimeout(hide,timeout) );
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
I think order of calling show , hide is the matter . I have modified your code . It works fine . Please visit the link
http://jsfiddle.net/dzZe3/1/
the
(show(),setTimeout(hide(),timeout));
needs to at least be
(show(),setTimeout(function() {hide()},timeout));
or
(show(),setTimeout(hide,timeout));

Categories

Resources