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
Related
I'm using Barba.js on my website. When the 'Portfolio' page is loaded via Barba.js, I run a function, let's call it get_portfolio_items(). There are some inline javascript variables that get_portfolio_items() needs to access the values of. If the 'Portfolio' page is the very first page to be loaded, then get_portfolio_items() accesses these variables just fine. However, if another page is loaded first, and then clicked into the Portfolio page, I get the error:
loadMoreVars is not defined.
Even though I can see loadMoreVars is in the DOM.
How can I access these variables in get_portfolio_items() ? Thank you!
This is the script in the actual HTML that appears on the new page:
<script type="text/javascript">
var loadMoreVars = {
postsPerPage : 9,
maxNumPages : 6,
};
</script>
This is the function that is called whenever a new page is loaded via Barba.js
function get_portfolio_items(){
alert(loadMoreVars.postsPerPage);
alert(loadMoreVars.maxNumPages);
}
This is the Barba.js code that triggers the function when a new page is loaded.
Barba.Dispatcher.on('newPageReady', function(current, prev, container) {
history.scrollRestoration = 'manual';
get_portfolio_items()
});
How can I get the function to see the variables and thus alert them out?
A bit late, but i managed to make it work. It's important to set the variable to the window object.
<!-- HTML FILE -->
<script class="loadInlineScript">
window.loadmoreurl='FOO';
</script>
// JS FILE
Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, container) {
var inlineScript = $(container).find('script.loadInlineScript')
inlineScript.each(function(i, elm) {
eval(elm.innerHTML);
})
});
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.
Strange situation:
I am building a menu bar using jQuery and CSS.
In my JavaScript file, I have an on-ready function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
Try on the window load event :
$(window).load(function() {
//Stuff here
});
To be sure, Try window load
$(window).load(function(e) {
mark_active_menu();
}
Before(sometimes, doesn't load absolutely at the beginning, a few milliseconds after(0-200ms about)):
$(document).ready(function(){
$('body').hide(0);
});
After:
$(window).load(function(){
$('body').delay(500).show(0);
});
In my situation of work with AJAX and HTML. I have the same problem with functions $(document).ready() and $(window).load(). I solved this problem by adding handler of my event (that should work at HTML DOC), to the jQuery function that runs right after AJAX reguest was finished. Read this: "
jQuery.post()" (third parameter in the function).
In my code it looks like this:
var RequestRootFolderContent = function(){
$.post(
'PHP/IncludeFiles/FolderContent.inc.php',
function(data){
$('[class~="folder-content"]').html(data);
//Here what you need
$('[class~="file"]').dblclick(function(){
alert("Double click");
});
}
)
}
This might be a very basic question but I'm trying to understand this behavior
This is my javascript code. I want to know why second call to foo does not work. Here is the JSFiddle link
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function"); //this works
});
$('#container').foo("outside"); //this does not
The DOM is not fully loaded .. Thats the reason it won't work..
So when you encase your code inside the DOM Ready handler it waits for the document to be loaded and then runs the code inside.
This makes sure the element is available before any code is run on it..
When the HTML document is parsed , it parses top down.
So if the script is included in the head section , then the scripts are loaded first and then the HTML structure.. When you try to the run the code , it obviously won't work cause the element was still not parsed..
So encasing that in the handler will make sure the element is available before calling the methods on them..
This is because $('#container').foo("outside"); is evaluated before the body is processed. $('#container') will return with a length of 0. This is demonstrated below.
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function");
});
var element = $('#container');
console.log(element.length); //prints 0
element.foo("outside");
If the script is at the beginning of the page the rest of the HTML document has not been parsed yet, so the document looks empty to the script, so there is no #container yet.
$(function() { ... });
is (roughly) equivalent to
Wait till the whole HTML file is loaded and ready
Then execute function
so #container will be there and it will work. Another way to make it work would be to put the script below the rest of the page or at least below #container.
Basically my app work like that :
Index.php manage call to other pages.
Each page contains 2 function onLoad() and onClose() which are redefined in each page
Index.php call the pages and execute the onLoad
Basically, i preload the page in a hidden div, i execute the predefined $.onLoad function and the i put the loaded content into a visible div
My question is only about the onLoad() scope, i want to remove code from the jquery eval seq when i change page, but i need a way to define it in the page.php file without knowing the container
The eval/seq is probably the eval queue of jquery, can't found info about that, just obtain with firebug...
In 2 words, i would like to be able to remove injected dom and script when i change context (pages)
index.php
$.onLoad = function() {}
$("#blabla").onChange(function() {
$("#data_iframe").load(chaineUrl, {}, function(responseText, textStatus, XMLHttpRequest) {
$("#data_iframe").ready(function() {
$("#data_div").children().remove();
$.onLoad();
$("#data_iframe").children().hide().appendTo($("#data_div")).show(); $("#data_iframe").children().remove();
$.onLoad = undefined;
}
});
});
page.php
<script>
$.onClose = (function(){
$('#container').blablabla();
//alert("test");
});
$.onLoad = (function(){
$('#container').blablabla();
}
</script>
The problem is that the jquery EVAL/SEQ keep growing each time a page is opened
and there are some side-effect like calling multiple time a function...
I guess its a scope problem so can you help me correct my code
(i've try with or without the $ but doesn't change anything)
just for information
<div id="data_div"></div>
<div id="data_iframe"></div>
Thanks
I usually use $(document).ready instead of onload. No need to do the "onload" trigger in load complete function. The ready function within the page.php will do the same job.
And how about direct load into data_div?
index.php
$("#blabla").onChange(function() {
$("#data_div").load(page.php);
});
page.php
<script>
$(document).ready(function() {
$('#container').blablabla();
});
</script>
I didn't try page close function before, may be it is not what you want. But you can try:
<script>
$(document).ready(function() {
$('#container').blablabla();
$(window).unbind('unload');
$(window).unload(function(){
$('#container').blablabla();
//alert("test");
})
});
</script>