How to add a js function to ONSEN page load? (monaca) - javascript

I would like an animation to autostart on page load. I'm in the Onsen UI V2 JS Splitter example within the ons-template in an ons-page.
I found that adding a script tag between the "/ons-page" and the "/ons-template" tags gets read (this took me quite some time... (-; )
I followed the guide
<script>
document.addEventListener("init", function(event) {
if (event.target.id == "score.html") {
Progress1();
}
}, false);
</script>
But nothing happened.
I changed it to:
.... html stuff
</ons-page>
<script>
$(document).ready(function() {Progress1()});
</script>
</ons-template>
But now it cannot find a component from the HTML file and it says
Uncaught Error: container does noet exist #container1 www/lib/jquery-3.1.0.slim.min.js:2
What can i do? I solved it now with a button. That proves it works, but is of course no auto start.
Any ideas...?
thanks

I see this one is old, but anyway.
Onsen UI documentation says:
There are several events you can listen to. 'init' or 'show' will do the trick. Make sure you load the script as an external file, not inline script. Cordova templates are added and removed on navigation. Inline script is not efficient at all
document.addEventListener('init', function(event) {
if (event.target.matches('#yourpage')) {
ons.notification.alert('Page is initiated.');
// Set up content...
}
}, false);

This doesn't look a good way to achieve your goal. You should use Cordova Events or, if you need to wait for Onsen to be loaded, ons.ready function. Here is an example:
<script>
ons.ready(function() {
//execute your code
});
</script>
Hope it helps!

With a lot of help, this is a solution that works. It is an interval that checks if the container 'exists'. It repeats until the container is there and then it calls the function. In the function the interval is cleared (so it stops checking).
See also here: http://www.w3schools.com/js/js_timing.asp
var tryForContainer;
function progression1Test(){
tryForContainer = setInterval(checkIfContainerIsReady, 100);
}
function checkIfContainerIsReady(){
//alert(document.getElementById('container1'));
if(document.getElementById('container1') !== null){
Progress1();
}
}

Related

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

Can you use ons-postpush to find elements on pushed via javascript?

I am using Onsen UI for app development. This app makes use of the JQuery UI slider. This slider needs to be initialized via javascript, but when I load the next page the javascript code gets executed before the page is fully loaded. Therefore the javascript code is not able to find the div in which the slider will be loaded.
My question: Can you use the ons-postpush attribute to solve this? And how do you use it? Since this isn't specified in the Onsen UI docs...
Thank you so much in advance!
You need Onsen UI 1.3 to do this:
$(document).on('ons-navigator:postpush', 'ons-navigator', function(event) {
console.log("Pushed!");
});
Hope it helps!
--- Edit:
Fixed by #jasper for this case:
ons.ready(function() {
myNavigator.on('postpush', function(event) {
console.log("test");
});
});
Adding a point to the answer posted by #fran-dios
to prevent multiples binds you need to use once method.
ons.ready(function() {
myNavigator.once('postpush', function(event) {
console.log("test once method");
});
});

Hide div when URL contains

I want to hide the slider (and a bit more) if someone uses the search module on my Joomla site and tried several solutions mentioned here on stackoverflow like: https://stackoverflow.com/a/1760605/1641903
Currently my code looks like this:
<script>
if (/\/search\//.test(window.location)) {
$('#hideonsearch').hide();
}
</script>
I wrapped the slider in <div id="hideonsearch> and tried mentioned jquery in both the body and head (just to be sure), but it doesn't seem to work as you guys can see here.
Any idea on how to get in working?
I saw in your web site that the jquery is not loaded when your code is being executed.
You must put your code in the "onload" function, or make sure the jquery is loaded before doing this.
window.onload = function () {
if (/\/search\//.test(window.location)) {
jQuery('#hideonsearch').hide();
}
};
Or you can use the pure javascript code that is better.
window.onload = function () {
if (/\/search\//.test(window.location)) {
document.getElementById("hideonsearch").style.display = "none";
}
};
I saw another error in your web site now, related to this code:
jQuery(document).ready(function(){
jQuery('.hasTooltip').tooltip({"html": true,"container": "body"});
});
error:
undefined is not a function
And it is related to the same problem, jQuery is not loaded, so you can use "window.onload".

Going to a page anchor after load adding transition

I'm quite new at using jquery but learning a bit everyday. I have solved many problems searching this web but I can't seem to find any solution for this one:
The web I'm workign at the moment use quite a lot of page anchors.
I have localscroll and scrollto as jquery libraries.
I animated the transition with this little script:
<script type="text/javascript">
$(document).ready(function () {
$('.scrolllento').localScroll({ duration: 1000 });
});
</script>
and it works fine whatever I add the class "scrolllento" to the cointainer of my links.
Now the problem I have is when a link jumps to an anchor of inside different page. my client has asked me if it's possible to load the page first then move to the anchor with same web transition.
I have been working on it with my little knowdlege and this is what I have atm:
<script type="text/javascript">
$(document).ready(function () {
var nosalto = $(location).attr('href');
if (nosalto.indexOf("HistoriaBMG") > 0) {
$.fn.gotoAnchor = function (anchor) {
location.href = this.selector;
}
$('#historia').gotoAnchor();
}
});
</script>
"HistoriaBMG" is the new page and "#historia" is the anchor I want to go inside that page.
and it seems again that it works...
the problem is I have no idea how to implement now the transition as the class "scrolllento" in the container of the link going to ../HistoriaBMG is ignored.
could anyone help me? thanks so much in advance and excuse my english, hope this question is clear enough.
According to the localScroll docs:
The plugin also adds a function, $.localScroll.hash() , that checks the URL in the address bar, and if there's a hash(#an_id), it will scroll to the element. It accepts a hash of settings, just like $.localScroll. You will likely call it on document ready. Check the regular example to see it in action.
So you simply need to call $.localScroll.hash()on $(document).ready()

Check if iframe is loaded inside $(document).ready

I want to check if iframe is loaded with the following code:
$(document).ready(function() {
jQuery('#iframeID').ready(somefunction);
}
It seems that 'somefunction' is called before iframe is loaded (the iframe is empty - just empty html-head-body).
Any idea why this happens?
Thank you.
Try this instead.
$('#iframeID').load(function() {
callback(this);
});
While dealing with iFrames, it is good enough to use load() event instead of $(document).ready() event.
This is because you're checking if the iFrame is ready, not the document inside.
$(document.getElementById('myframe').contentWindow.document).ready(someFunction);
should do the trick.
I have tried:
$("#frameName").ready(function() {
// Write you frame on load javascript code here
} );
and it did not work for me.
this did:
$("#frameName").load( function() {
//code goes here
} );
Even though the event does not fire as quickly - it waits until images and css have loaded also.

Categories

Resources