JavaScript How to pass a parameter to a function - javascript

I am having trouble passing a parameter to a function.
Here is my code (edited to show flow and positioning in the html doc):
<!-- this src file precedes -->
// this resides in a js src file on its own and as is
function mySpecialFunction(thisIndex) {
alert(thisIndex); // shows as blank
}
<!-- this src file follows -->
$(document).ready(function() {
$(window).load(function() {
$(document).on('change', '.jq__pAC', function(event) {
var i = 1;
// some JavaScript code
mySpecialFunction(i);
// some more JavaScript code
}); // end jq__pAC
}); // end .load()
}); // end .ready()
my alert() event displays blank.
The 2 blocks of js code are in separate src files. Does that have anything to do with it?

If you say the functions are in different files, probably the order of the files in the problem.
Make sure that the calling method (mySpecialFunction(i);) comes after the declaration (function mySpecialFunction(thisIndex)).
EDIT:
In your edit you have $(document).ready and $(window).load. Remove the last one and it will work.
See jsfiddle.

Related

How to change the CSS of an HTML element with the output of a Javascript function? [duplicate]

In using CodePen, the JavaScript code in the JavaScript pane seems to execute just before the </body>. In my case I have some <script> tags embedded in my HTML where I refer to functions defined in the JavaScript pane. Since the JS pane is not evaluated until just before the </body>, I cannot refer to these JS functions in the <script> element.
Is there a way to tell CodePen to effectively, "put the contents of the JavaScript pane in the <head> rather than just before </body>"?
I originally wanted to be able to specify where the JS pane's content is included: In the <head> element or just prior to closing the </body>. By default, CodePen inserts your JS pane content just prior to the close of the </body> and there's nothing you can do about it for now (July, 2015).
There is something of a hack you can use to get around this though. Let's say your pen is at:
http://codepen.io/lanshen/pen/j7GB5q (I just made that up). Your JS pane has its own URL of:
http://codepen.io/lanshen/pen/j7GB5q.js
In the "Stuff for <head>" section in your pen's "Settings", add a tag that refers to your JS pane:
<script src="//codepen.io/lanshen/pen/j7GB5q.js"></script>
This will cause your JS pane's content to be included in the <head>. The obvious problem with this approach is that the JS pane's content will still be included just prior to the </body> (i.e., it will be included twice). To get around this problem, I structured my JS pane content into an if()/else() so that the if() piece will be loaded in <head> and the else piece will be loaded just prior to </body>. Below is the JS pane "template" I used. Again, make sure you reference the JS pane with a <script> tag in the HTML's "Stuff for <head>" section as I mentioned above.
var headLoad;
if(!headLoad) { // when loaded in HEAD, headLoad will be falsey
headLoad = {}; // when loaded before </body>, headLoad will be truthy
(function() {
// PUT YOUR JS TO BE EXECUTED IN HEAD HERE...
alert("I am executing in the HEAD!");
headLoad.doSomething = function(mssg) {
// ...
alert(mssg);
};
})();
} else { // this code is not executed until just prior to </body>
// PUT YOUR JS TO BE EXECUTED PRIOR TO </body> HERE...
alert("The BODY is about to close....");
doSomething = function(mssg) {
alert(mssg);
};
doSomething("789");
}
Here's a little HTML pane to test it out:
<p>ABC</p>
<script>
alert("I am in the HTML script tag.");
headLoad.doSomething("123"); // should alert
// The following will NOT execute because the "else" clause of the
// "if(!headLoad)" will not be executed until just prior to the </body>.
// the global doSomething() function is currently undefined.
doSomething("456"); // will NOT work, nor should it.
</script>
<p>XYZ</p>

how to know from javascript loading in page or not

I have to javaScript files named as Js1, Js2. I would like to know from the Js2, is the Js1 is loaded on html page or not. Please share an example . Thank you.
at the beginning of your js1 add this code:
var js1Loaded=true; //if your js1 is not wrapped in a function scope
window.js1Loaded=true //if your js1 is wrapped in a function scope
and in your js2 check the condition with this code:
if(js1Loaded){ //or window.js1Loaded
//js1 is loaded
}
UPDATE
another way to achieve this is using DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function(event) {
//all the scripts are loaded
//write your js2 code here
});
Building on the comment
when do i need to write window.js1Loaded=true ? is this statement is end of the javascript ?
you need to write window.js1Loaded=true inside your js1 file (at the beginning or the end, actually doesn't matter).
if i create boolean value in Js1, can able to access sample variable in Js2 alos ?
as I mentioned before if your js files are not wrapped in a function scope then yes you can simply write var js1Loaded=true; and access it from all the js files that loads after js1.
by function scope I mean this:
(function(){
//your code here
}());
if your code is inside a function scope then you have to define your js1Loaded variable globally using window.js1Loaded=true;
Quick Example
html
<html>
<head></head>
<body>
//some html elements here
<script type="text/javascript" src="/Script/js1.js"></script>
<script type="text/javascript" src="/Script/js2.js"></script>
</body>
</html>
js1
var js1Loaded=true;
//some js code here
js2
//some js code here
if(js1Loaded){
alert('js1 is loaded');
}
but at the end I would really suggest that you use DOMContentLoaded event, it is more efficient!

Jquery function not executing properly

Okay, so here is my code:
//Other Jquery codes
// show_popup_crop : show the crop popup
function show_popup_crop(url) {
alert("Called show_popup_crop!");
// change the photo source
$('#cropbox').attr('src', url);
// destroy the Jcrop object to create a new one
try {
jcrop_api.destroy();
} catch (e) {
// object not defined
}
// Initialize the Jcrop using the TARGET_W and TARGET_H that initialized before
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [ 100, 100, TARGET_W, TARGET_H ],
onSelect: updateCoords
},function(){
jcrop_api = this;
});
// store the current uploaded photo url in a hidden input to use it later
$('#photo_url').val(url);
// hide and reset the upload popup
$('#display_pic_input_first').val('');
// show the crop popup
$('#popup_crop').show();
}
// crop_photo :
function crop_photo() {
var x_ = $('#x').val();
var y_ = $('#y').val();
var w_ = $('#w').val();
var h_ = $('#h').val();
var photo_url_ = $('#photo_url').val();
// hide thecrop popup
$('#popup_crop').hide();
// display the loading texte
$('.loading').css('display','inherit');
// crop photo with a php file using ajax call
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, photo_url:photo_url_, targ_w:TARGET_W, targ_h:TARGET_H},
success: function(data){
// display the croped photo
}
});
}
// updateCoords : updates hidden input values after every crop selection
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
//document.ready function calls
What is happening:
The function show_popup_crop(url){} ain't working.
Now the function is being called, because the alert("Called show _popup_crop!"); is being executed. But it isn't executing the rest of the code that is the part where it needs to change the attributes of the image tag and the divisions.
I have tried changing the position of this script in the JS file but it doesn't help.
A PHP code automatically generates a script which is included in the body:
<script type="text/javascript">window.top.window.show_popup_crop("some url")</script>
PHP code within the script tag in the php page:
echo '<script type="text/javascript">window.top.window.show_popup_crop("'.$target_file.'")</script>';
Now it does call the function when the page is loaded as the alert function
alert("Called show_popup_crop!"); is executed. In fact it executes all the alert functions included but it doesn't execute anything else included in the method.
I have tried removing everything else and just executing the code below, but it still doesn't work:
function show_popup_crop(url) {
alert("Called show_popup_crop!");
$('#cropbox').attr('src', url); //change the photo source
$('#popup_crop').show();
}
However when I included $('#cropbox').attr('src', "some url"); in another document.ready method in the same JS file, it does execute the code. I don't understand what is the problem.
All the other functions that are called in index.php page are executed.
However one more weird thing is, it doesn't execute all the functions in $(document).ready(function(){...});.
It just executes the first function and stops... but it executes all the other functions in all the other pages?
Console Error:
At first it gave me this console error:
Uncaught TypeError: undefined is not a function
but now it is giving me this:
Uncaught ReferenceError: jQuery is not defined
Files included in header (where position.js is the name of the file):
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/position.js"></script>
P.S: Often when chrome is refreshed and the js document is changed, the chrome loads old js document no matter how many times it is refreshed?
Change your PHP code to this:
echo '<script type="text/javascript">$(window).on("load",function(){window.top.window.show_popup_crop("'.$target_file.'");});</script>';
The result in JavaScript will be this:
<script type="text/javascript">
$(window).on("load",function(){
window.top.window.show_popup_crop("url/to/image.jpg");
});
</script>
What was happening in your code, was that show_popup_crop() was being called before the image-element #cropbox had been fully loaded on the page.
Because of that, this line $('#cropbox').attr('src', url); tried to change the src tag of an element that didn't exist yet.
And by the time the image-element had finally been loaded, the code had tried to execute that line long ago (in computer-time, this all happens within a second or less) without any success.
So nothing happened.
What the $(window).on("load",function(){...}); does, is wait until all elements on the page are fully loaded, before executing the code within it's handler-function.
This happens after document.ready. Read here what the difference between the two is, and why it's important to use window.load especially for images (I always recommend it over document.ready).
So now, this line $('#cropbox').attr('src', url); is executed only after all elements - including the image - have been loaded on the page. So the image-element exists, and the source can be successfully changed.
did you wrap all your code around the
$(document).ready(function(){
//jquery code here
});
I kind of have the feeling your problem is related to this.
.ready is an event thrown by jquery when its API has loaded and is ready for use

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Problems Getting jQuery to Work in External js File

I have just started messing with jQuery and have had luck getting it to work within actual aspx and html files, but I'm now trying to get it working in an external js file.
In my html file in the head I have:
<!--Declare jQuery files-->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1-vsdoc.js"></script>
<!--Declare external java files-->
<script type="text/javascript" src="javascript/SiteFunction.js"></script>
I have tried adding this to avoid multiple document ready instances, it hasn't effected anything either way, having in or not:
<script type="text/javascript">
$(document).ready(function() { });
</script>
In my external file I have (it is in an if statement and my function just literally skips over all the jQuery .append and .animate stuff as if it were not even there):
$(document).ready(function() {
$('<p>Test</p>').append("#" + newPage);
});
jQuery(function($) {
alert(newPage);
$('<p>Test</p>').appendTo(newPage);
$(newPage).animate({ left: '0px' }, 2000, function() {
// Animation complete.
alert("animated newPage");
});
$(currentPage).animate({ right: '0px' }, 2000, function() {
// Animation complete.
});
});
The first jQuery append is just a simple test to see if I could do something simple. This is all contained in an if statement. I am not receiving any errors and the code is preceding through the first jQuery ready, going into the jQuery function, my alert(newPage) is working, but my alert("animated newPage") is not so I know that I am not even entering into any of the jQuery functions.
If my terminology is incorrect, please forgive me, again I have just started working with Query over the past 3-4 days.
My variables, newPage and currentPage are the id's of divs contained in the main html page. I am accessing and manipulating them fine with javascript in the same external js file.
I tried with the first jQuery .append to see if I needed to add the "#" before my div id to reference as a string.
I've tried with the rest wrapping them in the jQuery(function($) {});. Leaving them as just stand alone, which worked directly from my html file.
Example of working code from html file. Same setup in the head of the file
$(myContent).animate({
width: '0px'
}, mySpeed, function() {
// Animation complete.
});
$('#contentH4').animate({
width: myLeft
}, mySpeed, function() {
// Animation complete.
});
So, I'm at a complete loss!
First, you should only include jQuery once. Those files you're linking to all have the same JS code (except one is minified and the other has additional comments).
This is all you need:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
Also, it would help to see where you're defining newPage and currentPage. If you could link to a demo page that would be ideal.
Also, this does nothing:
<script type="text/javascript">
$(document).ready(function() { });
</script>
And if newPage is simply an ID, then this:
$('<p>Test</p>').appendTo(newPage);
Should be this:
$('<p>Test</p>').appendTo('#' + newPage);
When linking external javascript/jquery files, the type="" does not have to be declared.
Also have them load at the bottom of all body content for better load times.
I use ASP.NET with nested MasterPages and this got to be a real issue for me. I was getting document.ready's lost all the time. I figured I needed a better way and what I came up with was creating an array to hold all of my functions that I wanted to call, and in one document.ready, loop through that array, calling each function in the order in which it was added. If you use many external files that are included at different points for different reasons, this will allow you to do that without any hassle:
<!-- your external javascript file -->
<script type="text/javascript">
// create array to hold a list functions to run once
var oneTimeFunctions = new Array;
// create variable to store first function
var test1 = function() { $('<p>Test</p>').append("#" + newPage); };
// add first function to the end of the array
oneTimeFunctions[oneTimeFunctions.length] = test1;
// create variable to store second function
var test2 = function() {
alert(newPage);
$('<p>Test</p>').appendTo(newPage);
$(newPage).animate({ left: '0px' }, 2000, function() {
// Animation complete.
alert("animated newPage");
});
$(currentPage).animate({ right: '0px' }, 2000, function() {
// Animation complete.
});
};
// add second function to the end of the array
oneTimeFunctions[oneTimeFunctions.length] = test2;
// call document.ready only once
$(function(){
// call each function that was added to the oneTimeFunctions array
$.each(oneTimeFunctions, function(index, func) { func(); });
});
</script>
Now, like I said, you can split this up into multiple external files. This just shows it how it would be processed in order. You just need to create the array first, then create your functions and add them to the array in your various external files, and lastly, run the document.ready portion that loops through calling each function.

Categories

Resources