I have a function that already defined. I need to to call the function with parameters when the jQuery swipe event occurs.
Here is the code
$( document ).ready(function() {
$("#next").on("swiperight",myFunction('right'));
$("#next").on("swipeleft",myFunction('left'));
function myFunction(direction) {
var dir = direction;
console.log(dir);
}
});
But id doesn't works onswipe. Instead it works twice on page load and prints right and left in console.
It works when the function is called without arguments like,
$("#next").on("swipeleft",myFunction);
What is the problem here ? Appreciate for any help.
Callback functions have no name. Wrap your named functions inside it:
$("#next").on("swiperight",function(){myFunction('right')});
$("#next").on("swipeleft",function(){myFunction('left')});
Related
I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.
I have a function that is I think is self invoked and I'm trying to figure out how to call it again.
This is how the function is declared:
jQuery(function setupFormInputHandlers(){
...
}
I try to put setupFormInputHandlers() in the developer tools console but I get an undefined error.
See jQuery document ready
// Passing a named function instead of an anonymous function.
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
$( document ).ready( readyFn );
//invoke again
readyFn()
$ is just used as alias to jQuery so when you say $('x') you mean jQuery('x')..the main function is overloaded to make it familiar and to allow working with ease... also what you are asking about the function (may be you missed pasting other part)
$(function(){}); or
jQuery(function(){});
both are methods of calling anonymous function shorthand for
$(document).ready(function()
{
//your code
}
);`
in simple words it means "When the document loading complete register your an anonymous function"
I want to execute a function which was defined in the start of the script, lets call this function initialize. This function also uses a variable, lets call it login, which is defined by a php file that includes my jquery script file after defining the variable login.
php/html:
<script type="text/javascript">
login = '<?php echo $login; ?>';
...
</script>
<!-- script is included -->
<script type="text/javascript" src="script.js"></script>
jquery:
function initialize(){
$("." + login).remove();
}
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
the moreContent function is then loaded, I can see more content appearing on my screen but initialiye is not loaded. only if I use a function like resize (in the end of the script.js file) it works
jquery (in the end of script):
//load function initialize
initialize();
//this function doesnt work too, I tested if it even loads and it does (used a number that was increased by one whenever function was loaded which actually happened...)
//however the wished element with the class of variable login is not removed
//resize function
$(window).resize(initialize);
//this one suddenly works
...
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
You need to wrap your code and make it run once the document is ready, like this:
$(document).ready (function(){
// run all your functions here
});
Maybe the variable login is empty in the other function, or you are giving thst a different value.
Try with a global variable to test it, like
window.login = script_php
And try again, in this ways, the login variable is global, or pass this variable as a parameter in the function.
the moreContent function is then loaded, I can see more content appearing on my screen but initialize is not loaded.
That is not exactly what happened. You have attached a function as method directly to jQuery object but did not invoke it,
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
You won't get any fruitful benefit from doing it this way. You have just added a method to an object (jQuery in this case) which is not invoked yet. In any case you do not need to add it as a method to jQuery object itself. You can do it easily without this as following.
function initialize(){
$("." + login).remove();
}
// this is a global function right now, use it anywhere you want.
function moreContent()
{
//more content is loaded
...
initialize();
}
// document ready...
$(function(){
moreContent();
});
You can rearrange the code and remove the unnecessary function layers (depends upon your code structure) and use it like this.
$(function(){
// more content...
initialize();
});
if I use a function like resize (in the end of the script.js file) it works
It worked because it is attached directly to window by jQuery on resize event.
$(window).resize(function(){
// The code inside will work whenever user resizes the window.
// It does not need to be hooked up inside document ready.
});
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
The reason it worked inside event handlers is because you hooked up your functions to run as a callback function to them. You have set it up correctly in click or resize event but not in load event. In load event you just created a function and added the it as a method to jQuery object but did not invoke it. The only and only way a function runs inside JavaScript is when you suffix parenthesis.
function demo()
{
// do something...
return "Done";
}
// a named function "demo" got created, but not invoked.
demo; // returns the whole function literal, not invoked yet.
demo(); // invoked, returns Done
So continuing from this, adding it as a method to jQuery will not load it, until you invoke it e.g.
jQuery.myNewMethod = function myNewMethod() {
return "Hey there :)";
}
// jQuery loaded, but where is my method ?? (#__#)
// let's invoke it then...
jQuery.myNewMethod(); // invoked the function using parenthesis!
// returns "Hey there :)"
// Now i can see you go (^__^)
I have a function that I want to use in order to expand menus in various places. I expect it to be triggered on a click of menu associated button, but at the moment it is being called on page load (I assume from within document ready), and class 'expanded' is added without clicking on a buton. I am confused to why this happens, as it should be called .on('click' ..
jQuery(document).ready(function ($) {
'use strict';
$('#btn-expand-mobile-nav').on('click', showMenu('#side-navigation'));
});
function showMenu(menu) {
var x = $(menu),
y = 'expanded';
if (x.hasClass(y))
x.removeClass(y);
else
x.addClass(y);
}
You are calling the function immediately. Instead defer the execution using an anonymous function:
$('#btn-expand-mobile-nav').on('click', function(){
showMenu('#side-navigation')
});
If there were no parameters you could have done this:
$('#btn-expand-mobile-nav').on('click', showMenu);
Simplistic explanation for #skobaljic:
By using the function name alone, you are pointing at the variable showMenu and saying call this later as a function.
By using function(){} you are saying, here is a temp variable, containing a function, that you can call later.
e.g. it is the same as:
var temp = function(){
showMenu('#side-navigation')
}
$('#btn-expand-mobile-nav').on('click', temp); // No parenthesis on temp
As #Dave Newton rightly points out, this can be simplified using toggleClass:
$('#btn-expand-mobile-nav').on('click', function(){
$('#side-navigation').toggleClass("expanded");
});
I have a number of javascript plugins which are included in my HTML file, and are included successfully because I have checked.
Heres the problem;
Basically I want to create a function outside the HTML file, and then inside the HTML file load that particular function when the document is ready.
this is the function (outside) of the HTML file. As a stand alone JS file:
function do_anchor_scrolling() {
$('#back_to_top').anchorScroll();
$("#landing_link").anchorScroll();
$("#menu_link").anchorScroll();
$("#sauces_link").anchorScroll();
$("#ranches_link").anchorScroll();
$("#order_link").anchorScroll();
$("#about_link").anchorScroll();
$("#franchise_link").anchorScroll();
});
the function is called do_anchor_scrolling
How in JQuery can I say when the document is ready perform the do_anchor_scrolling function.
When the document is ready, call the function.
$(document).ready(function(){
do_anchor_scrolling();
});
Pass it as a handler into the ready method:
$(document).ready(do_anchor_scrolling);
Or even shorter:
$(do_anchor_scrolling);
Notice the function is not executed right there (no invoking parenthesis) - the function object itself is passed into the ready function.
You can just do:
$.getScript("yourfile.js");//it grabs and executes yourfile.js
//so your function is now defined
do_anchor_scrolling(); //and you can call it
You can go without the $_getScript() call by just putting yourfile.js inside a <script> tag in <head>.