Can you use ons-postpush to find elements on pushed via javascript? - 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");
});
});

Related

Twig (or Symfony?) doesn't run my jQuery script

I currently am trying to create a website using Symfony 4. The issue is that one of my pages is in need of a jQuery script to work, part of it is working but functions like these aren't called, why ?
Example of code not being called :
$(document).ready(function(){
$(".someClass").click(function (event) {
event.preventDefault();
$(".active.focused").toggleClass("active");
$(".focused").toggleClass("focused");
$(this).toggleClass("active");
$(this).toggleClass("focused");
refresh_contents(); //this is another external function that I don't
//manage to call, even when called in the
//executed part
});
});
I am sure it doesn't come from my javascript as I tested it "off-symfony".
Thanks in advance, Crikripex
Alright, so after hours trying to figure out what and where the issue is, I came to the conclusion (thanks to #fyrye) that there might be compatibility issues between jQuery and Symfony4 or Webpack Encore.
I then decided to "translate" my code from jQuery to Javascript without any library and it worked fine.
To summarize, I went from :
$(document).ready(function(){
$(".someClass").click(function (event) {
event.preventDefault();
$(".active.focused").toggleClass("active");
$(".focused").toggleClass("focused");
$(this).toggleClass("active");
$(this).toggleClass("focused");
refresh_contents();
});
});
to :
for(i=0;i<maxId;i++){
document.getElementById("contain_" + i).onclick = function(event){
event.preventDefault();
document.getElementsByClassName("focused")[0].classList.remove("active");
document.getElementsByClassName("focused")[0].classList.remove("focused");
document.getElementById(this.id).classList.add("active");
document.getElementById(this.id).classList.add("focused");
refresh_contents();
}
}
I know it doesn't look as fancy, it's not as easy to code as jQuery, but so far that's the only solution I found that actually works.
Thanks for your help everybody.

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

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();
}
}

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()

How to execute jQuery function after Ajax page load

I'm building Wordpress website where all content pages are loaded using Ajax. This is causing me a problem with jQuery localScroll plugin. This plugin will add animated scroll to all anchor links on the page. Problem is that using script below I'm able to have animation on that page only after one of the links on the page is clicked.
I think I understand why is this happening. My guess is that after I click on the main menu script will execute but since Ajax content is not yet loaded events are not attached to Ajax loaded content links. Now I'm stuck, I have no clue how to fix this. Would you mind helping me with this one?
Thank you in advance.
$(function(){
$('a').live('click', function() {
$('#portfolioWrap').localScroll({// Only the links inside that jquery object will be affected
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
EDIT
Just a note to others after I managed to make this work. I tried all suggestions here. My guess is that solutions suggested by o.v. and Ohgodwhy should work, but probably due to website complexity and maybe plugin limitations I wasn't able to make them work. For example .on function didn't work at all although I'm using jQuery 1.7.1. At the end I implemente ajaxComplete suggested by Just_Mad and that worked. Thank you all for your help!
This is the code:
$(function() {
$('#wrapperIn').ajaxComplete(function() {
$('#portfolioWrap').localScroll({
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
If you use jQuery.ajax to load AJAX content you can try to bind to ajaxComplete event, to get the moment, when any ajax is complete.
Elaborating on what GoldenNewby said, listen/attach with the .on() method introduced in jQuery 1.7.
$(function(){
$('body').on('click', 'a', function() {
$('#portfolioWrap').localScroll({
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
No need to use AJAX for callbacks for listening/binding to elements. The above function will place a click function on all elements found within the body{1} at/after page load. This includes all dynamically created links.
{1} - Change 'body' to whatever Container has the ajax data. I.E. #portfolioWrap
Add a callback to the ajax load, good place to start is at http://api.jquery.com/jQuery.ajax/ under "success callback"
I would have given more specific advice, but your snippet is a bit isolated, maybe if you created a jsfiddle?

Open links in div container in JQuery Mobile

i have a multi-column layout where "#content-primary" is the div i want the actual content loaded, and "#content-secondary" holds a generated listview of links(effectively a navigation menu).
I'm using this code to change the page, pretty much following the JQM Docs, however the browser is following the links to entirely new pages, instead of loading the content from them into the "#content-primary" div. There's obviously something I'm missing.
$(function(){
$('#menu a').click(function() {
$.mobile.changePage($(this).attr('href'), {
pageContainer: $("#content-primary")
} );
});
});
Using Django on the backend, but it probably isn't relevant.
I finally found an answer here. JQuery Mobile's changePage() and loadPage() methods do too much post-processing and triggers a lot of events that really makes implementing your own dynamic loading more complicated than it should be.
The good old fashioned #("div#primary-content").load(); works, but I'm still struggling to apply JQM styles to it.
interestingly, this contradicts with this:
$.mobile.changePage() can be called
externally and accepts the following
arguments (to, transition, back,
changeHash).
And when tested this works: $.mobile.changePage("index.html", "slideup"); but this does not:
$.mobile.changePage("index.html", { transition: "slideup" });
Perhaps documentation is not quite right?
Update to the new beta 1 release

Categories

Resources