pjax losing the rails javascript - javascript

I have some javascript below which loads upon first page load, but then get lost by pjax.
Any way to solve this pls? I just have pjax running on the in application.html file so should i make it less aggressive or is there some js magic that will hold my js code.
$(document).ready(function() {
$("#note_label_tokens").tokenInput("/labels.json", {
crossDomain: false,
prePopulate: $("#note_label_tokens").data("pre"),
theme: "facebook"
});
});

Make the JS into a function, and then call it on document.ready and when the end.pjax event is fired.

Related

Javascript not working on page refresh

So I have this block of code:
$(document).ready(function() {
planSelectionForm.init($("form#new_account"));
});
And when I link to this page it works as expected. But when I refresh from the browser it doesn't get triggered. This seems like a common problem. Just for the record I'm using turbolinks. Any help on why this is happening would be great!
The only solution I could find after getting this problem was wrapping my script with:
document.addEventListener("turbolinks:load", function() {
planSelectionForm.init($("form#new_account"));
});
Wrap your .onready() functions into a function called initialize. The point, is to seperate the event-driven function calls such that the event driven function call calls a global function.
In there, add to your body or another element that supports onload.
$(document).ready(function() {
initialize();
});
function initialize()
{
}
<body onload="initialize(); return;"> </body>
Also, for Caleb, in my experiance, I believe jQuery ready events only get executed on either a fresh load, or a ctrl+f5 cache reload.

Rails Project: jQuery Plugin not loading until refresh

I building an app in Rails 4. I have the below JS plugins on my show page but they seem to work only when I manually reload the page.
I read that this might be due to turbolinks but since these plugins are in the body and not the head, it doesn't seem like a turbolinks issue.
I even tried pasting these in the head and the footer tags but these gave me the same issue. Sometimes, one of the plugins loads and the other doesn't.
The first plugin below are AddThis social buttons and the other is an image gallery.
Any suggestions?
Demo page http://mktdemo.herokuapp.com/listings/45
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ashfaaq">
</script>
<script>
jQuery(document).ready(function($) {
$('#gallery-1').royalSlider({
fullscreen: {
enabled: true,
nativeFS: true
},
controlNavigation: 'none',
autoScaleSlider: true,
autoScaleSliderWidth: 960,
autoScaleSliderHeight: 850,
imageScaleMode: 'fit-if-smaller',
navigateByClick: true,
numImagesToPreload:2,
arrowsNav:true,
arrowsNavAutoHide: true,
/* arrowsNavHideOnTouch: true, */
keyboardNavEnabled: true,
fadeinLoadedSlide: true,
globalCaption: false,
globalCaptionInside: false,
loop: true,
thumbs: {
appendSpan: true,
firstMargin: true,
paddingBottom: 4
}
});
});
</script>
You can find the answer to your question here:
Rails 4 turbo-link prevents jQuery scripts from working
Rails 4 is using Turbolinks, which load the page javascript and css only once and then replaces only the body and title in the header. This is why jQuery(document).ready will only work if you reload the page.
In order to trigger your javascript, you have to use Turbolinks events like
page:change the page has been parsed and changed to the new version and on DOMContentLoaded
or
page:load is fired at the end of the loading process.
More details here: https://github.com/rails/turbolinks/#events
Here you can just replace your
jQuery(document).ready(function($) {
...
By
$(document).on('page:load', function($) {
...
Sounds like turbolinks is the cause of your problems.
You can either install this gem: Jquery Turbolinks
Or you could replace
jQuery(document).ready(function(
....
));
with
$(document).on('page:load', function(
....
));
Here is a nice copy/paste of why turbolinks causes some problems with jquery.
TurboLinks is a PJAX like library that asynchronously requests the content of the next page and inserts it into the current page’s body instead of requiring a full page reload. It speeds up page load times nicely. However, because the page is reloaded, the DOMContentLoaded event is triggered and your jQuery document.ready event wont be triggered.
Source
I had the same issue with my jQuery image gallery on Rails 5. It would not load unless the page was refreshed. After a year of (on and off) trying, here's the hack that worked for me:
Wrap your jQuery gallery code in a function:
var delayLoad = function(){
$('#gallery-1').royalSlider({
...
})
}
Then call it with setTimeout:
setTimeout(delayLoad, 250)
This solved the issue for me every time without having to refresh the page.

How to determine when a page modified with JS is done loading?

I have a very bare HTML page that loads two JS files. One of these JS files then goes and loads a varying amount of content into the page.
I'm trying to get the equivalent of window.onload for this extra content. Obviously, window.onload actually fires very quickly, when the page is done loading the two JS files.
Any ideas? I know I can go and attach onload events to every image/script/etc on the page, but would rather not...
EDIT. If the callback won't help .load should do the job. I've added it to the example.
In this case you need a call back. Are you using a JavaScript library? if so what library?
In your existing code, after you append to the document you need to call a function that can execute the next bit of code.
something like this.
//FILE 1
$(function () {
$('body').append(someHTMLOrDOMNodes);
//I don't know what your second script does, but you should name this callback something relevant.
$('#idOfNewContent').load(function() {
callback();
});
});
//FILE 2
function callback() {
//next bit of code.
}

jQuery Basic problem

I have a page that display some data. It is loaded from a database using php and mysql, I use zend framework to handle all this.
On this page I have two things that use jquery. one is a paginator and the other is a thumps up function.
the paginator works fine. It receives the data as json and applys it to the view. all the functions that I need to handle this are located in one js file. In this file I listen for clicks...
$(document).ready(function() {
$("a#next").click(getProgramms);
$("a#previous").click(getProgramms);
$("a#page").each(function() {
$(this).click(getProgramms);
});
});
Now I have a problem with the thumps up function. It is located in another js file. Everytime the thumbs up button is clicked the script should just alert "click". actually when you click before you use the paginator a "click" appears, but when you do it after nothing happens. but the html in the dom inspector appears to be the same.
in my thumpsup.js I just have
$(document).ready(function() {
$("a.tp").click(thumpsUp);
});
function thumpsUp() {
alert("click");
}
I do not know where the problem is. maybe the js files are interferring each other!?
function thumpsUp() {
var url = window.location.hostname + '/programme/thumpsup/id/'
+ $(this).attr('page');
$.post(url, {
"format" : "json"
}, function(data) {
alert(data);
}, 'html');
return false;
}
I'm guessing the paginator is rewriting your elements and they are losing their click event binding. Try using live() for event binding instead:
$(document).ready(function() {
$("a.tp").live('click',thumpsUp);
});
function thumpsUp() {
alert("click");
}
You might have the Script files (which are included in your mark up) the wrong way round. That's the only solution I can think of...
I'm pretty sure you can get away with two $(document).ready()'s (even if it is frowned upon).

Jquery Fancybox not working after postback

I have a Fancybox (or more accurately) a number of fancy boxes on an asp.net page.
My Fancybox (jquery plugin) works fine until a postback occurs on the page then it refuses to work.
Any thoughts? Anyone experienced similar behaviour?
UPDATE : Some Code..
I have a databound repeater with a fancybox on each repeating item.
They are instanciated by (outside the repeater)
$(document).ready(function() {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
});
The anchor tag is repeated..
href="#watchvideo_<%#Eval("VideoId")%>"
As is a div with
id="watchvideo_<%#Eval("VideoId") %>
As is a script element that instanciates the flash movies
Yes the VideoIds are being output the the page.
UPDATE : It's not a problem with the flash..
It is not a problem with the flash as i've tried it without the flash, it wont even pop a window with a simple message in.
UPDATE : I wonder if it is the updatepanel.
Rebinding events in jQuery after Ajax update (updatepanel)
-- lee
The problem is in using $(document).ready() to bind the fancybox. This code is only executed once, when the page is originally loaded. If you want the fancybox functionality on every postback, synchronous or asynchronous, replace the $(document).ready() with pageLoad(sender, args). i.e.
function pageLoad(sender, args) {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
}
see this answer for more info
Could it be that the instantiating code is being inserted at a piece of code which is not run after a postback?
It was the Update panel as described
here.. Rebinding events in jQuery after Ajax update (updatepanel)
As suggested I simply replaced
$(document).ready(function() {
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
});
with
function pageLoad(sender, args)
{
if(args.get_isPartialLoad())
{
$("a.watchvideo").fancybox({
'overlayShow': false,
'frameWidth' : 480,
'frameHeight' : 400
});
}
}
and it worked!
-- Lee
This might help someone else, but FancyBox appends it's code to the <body> element... which is all fine and well, but resides OUTSIDE the asp.net <form> element. My postback problems went away when I modified FancyBox to append its dom objects to the <form> element:
$('body form:first').append( ... );
I had a similar problem with a paged grid-view. The first page of the grid was launching the fancybox while the remaing did not.
I thought it could be an issue related to the UpdatePanel which refreshes only a portion of the screen.
I solved the issue replacing this:
<script>
$(document).ready(function () {
$("a.small").fancybox();
});
</script>
with this:
<script>
function pageLoad(sender, args) {
$("a.small").fancybox();
};
</script>

Categories