$(document).ready() & $(function(){} - javascript

I have two functions:
function func1(){}
and
function func2(){}
both of these functions requires the following to work
$(document).ready();
$(window).resize();
so I have implemented it to both the functions as follows:
$(document).ready(func1);
$(window).resize(func1);
and
$(document).ready(func2);
$(window).resize(func2);
The problem? there is two;
1) I already have $(function(){ wrapping the above two functions, but I still need need $(document).ready(); why? isn't both the same thing?!
2) I am trying to short-cut the code and only have $(document).ready();"if needed" and $(window).resize(); to appear once and then add functions to it, and not add it to functions. Confused? okay...
so I basically want to do this:
$(document).ready(func1,func2);
$(window).resize(func1,func2);
But it didn't work, any ideas?
My script:
$(function(){
//Prevent clicking on .active & disabled links
'use strict'; $('.active, disabled').click(function(e) {
e.preventDefault();
});
//Off-canvas menu
var $pages = $('#page, #secondHeader'),
$header = $('#header'),
$secondHeader = $('#secondHeader .menu-button');
$secondHeader.on('touchstart click', function(e) {
e.preventDefault();
$pages.toggleClass("pageOpen");
$header.toggleClass("headerOpen");
$(this).toggleClass("menu-button-active");
});
$('#page').on('touchstart click', function() {
$pages.removeClass("pageOpen");
$header.removeClass('headerOpen');
$secondHeader.removeClass("menu-button-active");
});
//Grid system
var gridElement = $(".gridElement", "#grid3");
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
function GalleryGrid() {
var grid3 = $('#grid3');
var width = $(window).width();
if (width < 1024 && width > 770) {
var grid1 = $('#grid1');
var grid2 = $('#grid2');
for (var i = 0; i < gridElement.length; i++) {
if (i < gridElement.length / 2) {
grid1.append(gridElement[i]);
} else {
grid2.append(gridElement[i]);
}
}
} else {
grid3.append(gridElement);
}
}
$(document).ready(fullScreen);
$(window).resize(fullScreen);
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
});

Use a wrapper function to call both functions on the same event:
function go(){
func1(); // Call function 1 and 2.
func2();
}
$(document).ready(go);
$(window).resize(go);
Or, to make absolutely sure the document is ready, you can even attach the resize event listener after the ready event:
$(document).ready(function(){
$(window).resize(go);
});

Do like this.
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
fullScreen();
GalleryGrid();
$(window).resize(function(){
fullScreen();
GalleryGrid();
});
Just call the function like fullScreen() no need to use $(document).ready.
For Gallery Grid
Remove from you code. No need to call (function(){}) twice.
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);

I'd suggest using an anonymous function to get this done.
For example:
$(document).ready(function() {
1();
2();
});
That should be a good starting point.

(function(){ ... })();
It is not equivalent to document.ready. Here it is not necessary DOM is ready. It is anonymous function it invoke itself as soon as possible when the browser is interpreting your ecma-/javascript.
Better and suggested to use document.ready():
$(document).ready(function(){
fullScreen();
//other code
});

Don't
Don't call $(document).ready() inside $(document).ready(), it doesn't make sense. The code inside of $(document).ready(/* the code here */) is not executed immediately. It is scheduled for execution sometime later (when the document is ready).
Calling
$(document).ready(function() {
//do this
$(document).ready(some_function)
//do that
});
Is like saying "wait until the document is ready, do this, wait until the document is ready to do some_function, do that."
Document ready event:
$(function(){})
Is just a shortcut/shorthand for:
$(document).ready(function(){})
ready is an event. It belongs to the document object and it is triggered when the document is ready.
To register two functions to be called when the document is ready just do either:
$(document).ready(function() {
func1();
func2();
});
Or
$(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(document).ready(func3);
Or
function func3() {
func1();
func2();
}
$(func3);
Window resize event:
resize is an event. It belongs to the window object and it is triggered when the window is resized.
To register two functions to be called when the window is resized just do:
$(window).resize(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(window).resize(func3);

Related

Function doesn't run when I click on the button

So I have a simple JQuery code:
$(function () {
var podatoci;
var i;
$(".front").on("load", init());
$("#remove").on("click", toggleRemove());
function init() {
load();
}
function load() {
$.get("data.json", function (data, status) {
podatoci = data;
fill();
})
}
function toggleRemove() {
console.log("Yes");
$(".likse-dislikes").toggle();
}
function fill() {
for (i = 0; i < podatoci.length; i++) {
$("#container").append("<div class='wrap'><img class='img' src='"+podatoci[i].url+"'/><div class='likes-dislikes'><img class='like' src='sources/like.png'/><img class='dislike' src='sources/dislike.png'/></div></div>");
}
}
});
When I click on the button with ID: remove it runs the toggleRemove() function.
However when I run the web page and when I got to to the console when I click on the button the function doesn't run, instead it does Console.log("OK") only once presumably when the page is loaded. Can anyone please explain where is the problem and how do I fix it?
Thank you in advance!
This doesn't do what you think it does:
$("#remove").on("click", toggleRemove());
This executes toggleRemove once, when the page loads, and sets the handler to the result of that function. (Which is undefined because the function doesn't return anything.)
You want to set the handler to the function itself, not the result of the function:
$("#remove").on("click", toggleRemove);
Additionally, if your element is being added to the page after this code executes (we don't know, though the code shown implies some dynamic elements being added) then you'd need to delegate the event:
$(document).on("click", "#remove", toggleRemove);
You spelled the class name incorrectly on your remove function.
$(".likse-dislikes").toggle();
Change it to
$(".likes-dislikes").toggle();
As I can see here $(".front").on("load", init()); $("#remove").on("click", toggleRemove()); you call your call back in time when you register event listener. Try this: $(".front").on("load", init); $("#remove").on("click", toggleRemove);
You could use $scope.apply(handler)
$scope.apply(function () {
// Angular is now aware that something might of changed
$scope.changeThisForMe = true;
});

How can i add $(document).ready(function(){}) after a function in java script

What I want to do is I have a code like below :
$(document).ready(
function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
}
)
And now I want to add this code to add and get work with other code. I need to add this code after this one:
function () {
/* If there are forms, make all the submit buttons in the page appear
disabled and prevent them to be submitted again to avoid accidental
double clicking. See Issue 980. */
jQuery(function() {
/* Delegate the function to document so it's likely to be the last event
in the queue because of event bubbling. */
jQuery(document).delegate("form", "submit", function (e) {
var form = jQuery(this);
if (form.hasClass("form_disabled")) {
e.preventDefault();
return false;
}
else {
form
.addClass("form_disabled")
.find(":submit")
.addClass("disabled");
}
// Reactivate the forms and their buttons after 3 secs as a fallback.
setTimeout(function () {
form
.removeClass("form_disabled")
.find(":submit")
.removeClass("disabled");
}, 3000);
});
});
}
How can I get this done. Please help me out to solve this problem.
You can create document.ready() anywhere in script. It is not necessary all of your code should be in ready function.
You can create instance variable for function and call it where you need:
$(document).ready(
var myFunc = function(){
var currentPage = window.location.pathname;
//other code
}
...
//and invoke it where you need
myFunc();
)
First, name the long function in your code section, for example, launchFormControls(). And then define the function outside of the document ready event. A good practice would be to do so and keep the ready event body clean.
For example:
function launchFormControls() {
//function code
}
Or, in other syntax:
var launchFormControls = function() {
//function code
}
Second, call your function from within the document ready event. Your function will be defined and able to call once the document is loaded. This code can be placed at the top or bottom of your javascript section or file.
For example:
$(document).ready(function(){
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');
launchFormControls();
});

Simplify code with named self invoking function

I have this script:
function fixHeight () {
$(".sidebar-mainbox-container").height($(window).height());
})
fixHeight();
$(window).on("resize", function() {
fixHeight();
})
I'm looking for a way to simplify it using a self invoking function and then call it in the resize event.
I've tried this one:
var fixHeight = (function () {
$(".sidebar-mainbox-container").height($(window).height());
})();
$(window).on("resize", function() {
fixHeight();
})
But in this way the value of the self-invoked function is assigned to fixHeight, and this can't work.
If I remove the self-invoking part...
var fixHeight = (function () {
$(".sidebar-mainbox-container").height($(window).height());
});
$(window).on("resize", function() {
fixHeight();
})
Then the function works only when I call it on resize, and this is not good.
How can I simplify this code to avoid 3 elements for such a simple task?
What's wrong with
$(window).on("resize", function() {
$(".sidebar-mainbox-container").height( $(this).height() );
});
?
To avoid an extra function call just trigger the event immediately after registering it.
$(window).on("resize", /* ... */).trigger("resize");

Javascript .setTimeout() how to refer to a function

I have these codes:
$(function(){
$('.btn').click(function(){
$title = $(this).attr('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout(// $('.btn').click(), 100);
});
});
})
I want to repeat the click event of the button. But my main question is, how would you refer the right function or event in setTimeout() ??
You can wrap it into an anonymous function.
setTimeout(function() {
$('.btn').click();
}, 100);
In case you want to trigger the event in the specific element you've clicked before, you'll need to store the current element in a variable since this value inside the anonymous function would be different.
$('.btn').click(function() {
var $el = $(this);
// ...your code...
setTimeout(function() {
$el.click();
}, 100);
});
You could wrap the time out call back in an anonymous function and just real call the click function in there.
setTimeout(function() {
$(".btn").click();
}, 100);
You can bind this inside the anonymous function with $.proxy() to be compatible with IE8 or use .bind() for modern browers.
setTimeout($.proxy(function(){
// this.click(); // if this = $(".btn")
}, this), 100);
To explain it properly:
$(function(){
var btn = $('.btn');
btn.click(function(ev){
var el = $(ev.currentTarget), // same as $(this) but too many "thisses" can be confusing ^^
title = el.prop('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout($.proxy(function(){
this.click();
}, el), 100);
});
});
});
Instead of triggering the click event again, you may be better off naming the click event handler function and calling it again from within your setTimeout.
var handleButtonClick = function() {
$title = $(this).attr('title');
$.get('getOutput', {}, function() {
// success ajax get
setTimeout(handleButtonClick , 100);
});
};
$(function() {
$('.btn').click(handleButtonClick);
});

calling Jquery function from javascript

How can i call a jQuery function from javascript?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
jQuery functions are called just like JavaScript functions.
For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:
$("#orderedlist").addClass("red");
As opposed to a regular line of JavaScript calling a regular function:
var x = document.getElementById("orderedlist");
addClass() is a jQuery function, getElementById() is a JavaScript function.
The dollar sign function makes the jQuery addClass function available.
The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.
In your code
$(function() {
// code to execute when the DOM is ready
});
Is used to specify code to run when the DOM is ready.
It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.
So, to answer your question, just call functions you defined as you normally would.
//create a function
function my_fun(){
// call a jQuery function:
$("#orderedlist").addClass("red");
}
//call the function you defined:
myfun();
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
<script>
$.myjQuery = function() {
alert("jQuery");
};
$(document).ready(function() {
alert("Welcome!");
});
function display() {
$.myjQuery();
};
</script>
<input type="button" value="submit" onclick=" display();">
Hope this will work for you!

Categories