jquery getscript causing loop - javascript

I am using .load to call content from a section of my site when someone clicks a link. I am then using getscript to load in any scripts that are needed that .load strips out.
However, the content call function is needed on links that are loaded from this loaded content.
I am therefore in a situation where there is a loop being created and multiple executions.
This isn't an issue if the user clicks on one or two links to load content from other pages, but if they do it for several links then I get a spike in CPU, and therefore need to find a solution.
I am not sure why there is this issue, as the script executions are done through user clicks, so there shouldn't be continual execution.
The script looks like this:
$(document).ready(function () {
$('.Select a').one("click", function () {
var toLoad = $(this).attr('href') + ' .containerPlus';
$("body").append($("<div class='loadedcontent'>").load(toLoad, function () {
$.getScript("scripts required for loaded content", function () {
$.getScript("load this script again");
}));
});
});
basically the user clicks on a link, this calls the content and loads it into a new container, scripts needed on that page are then loaded, and then finally this code is applied to any links within this loaded content that need it.
This is a loop, but as there is a click element, I wouldn't have thought the second execution wouldn't take place until another click event.
Thanks for any advice
Richard

Related

Anchor click even not firing after PJAX page load

I am having a pretty strange problem with a website I am messing around with, and I can't wrap my head around what may be going wrong. I am using PJAX on the site, and the have a div in my body with the id of #page-contents.
The code I am using to setup PJAX is as follows...
<script type="text/javascript">
$(function(){
$(document).pjax('a', '#page-contents', {
fragment: '#page-contents',
timeout: 2000
});
});
</script>
I know that the setup is correct because I edited the PJAX file to fire an alert whenever it swapped out the content of my #page-contents div, and I do see that alert when I would expect to (i.e., on link clicks).
I have a navbar along the top (a bootstrap navbar) and I was initially having trouble keeping track of which navbar item would be marked as active. I have solved this problem using the following javascript code.
<script type="text/javascript">
$("a").click(function() {
$(".navbar-nav li").removeClass("active");
var nextPage = $(this).attr("href");
nextPage = nextPage.substring(nextPage.indexOf(window.location.hostname) + window.location.hostname.length);
switch(true) {
case nextPage == "/about":
$("#about-nav").addClass("active");
break;
case nextPage == "/contact":
$("#contact-nav").addClass("active");
break;
case nextPage == "/resume":
$("#resume-nav").addClass("active");
break;
case nextPage.indexOf("/projects") != -1:
$("#projects-nav").addClass("active");
break;
default:
break;
}
});
</script>
This works fine for all links I have in my navbar, but I have found that any links I have inside my #page-contents div will not trigger my above script. I know that PJAX is still working as the page changes and the alert I inserted displays.
A few things I have found in my own testing:
I have also found that if I directly load an address that contains a non-navbar link and then click that link, it will work. But coming back to that page via a pjax reload and then clicking the link will not fire my event.
Adding a test class to one of my anchors and then associating some event with that class has the same problems.
Does anybody know why my script would not be getting executing? Or maybe I am just missing something obvious.
Thank you in advance!
P.S.: The website in question is my personal site I am working on, the link is http://rosshays.me, the page I first noticed this on was my about page. (The site is a work in progress as you'll clearly see.) As mentioned about, going to the about page directly and clicking the link will work, but if you navigate to the about page and then try to click the link in the page, it will not work.
Ross-
I had a similar issue and I know how to solve this; this script is not binding to the new elements because it is not being re-ran on the new elements once they are loaded.
Please put your function in an external .js file. Once complete, you can add this script to your header:
$(document).on('pjax:complete', function() {
$.ajaxSetup({ cache: true});
$.getScript("YOUR SCRIPT FILE PATH HERE', true);?>");
});
You will have to add more $.getScript calls for any other javascript/jQuery that is needed in order to enable the events you want to take place. (Example: you may need to reload jQuery)
This will re-apply the jquery and javascript to the new elements that are loaded via PJAX.
*One thing to note: If you are using twitter bootstrap, do not re-call the bootstrap script with $.getScript as it will cancel itself out on every other re-load.

JQuery Mobile do X to every div with given class

I'm building a JQuery mobile site which has an image slider on 2 pages. The sliders are activated using the following JS:
$(function () {
$("#slider").excoloSlider();
});
where '#slider' is the name of the div that gets rendered as the slider.
I have this slider on the 2 pages and have given both the same id, and don't want to insert the above code into both pages. To make things easy I want to be able to make add the above code into a.js file that I'm referencing at the top of both pages.
However, the script only kicks in when one of the pages are the first page to be navigated to. So, I assume this means the code is only being called in the once, and due to the AJAX loading of the subsequent page, it isnt called when this new page loads.
So, how can I run the code to affect any/all pages which feature the slider?
I dont know how many times you have to call .excoloSlider(); function. In case you have to call it each time the page is visited, then you need to use any of these page events, pagecontainershow or pagecontainerbeforeshow.
If you use pagecontainershow, you can run .excoloSlider(); on #slider even if you have the same id in a different page. This way, you specify in which page to look for #slider.
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
/* check if #slider is within active page */
var slider = activePage.find("#slider").not(".slider");
if(slider) {
slider.excoloSlider();
}
});
Update
I have added .not(".slider") selector to exclude already rendered slider. The function .excoloSlider() will be called on new sliders only.
Demo
Try to use class instead of id since id is unique, then you can change your jQuery code to:
$(function () {
$(".slider").excoloSlider();
});
Use jQuery Mobile API for the navigation system
$(window).on( "navigate", function( event, data ) {
$("#slider").excoloSlider();
});
Edit
Use pageinit
From the jQM docs:
Important: Use $(document).bind('pageinit'), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.

pageLoad function in master page and content page

I have a pageLoad js function in master page,
and another one inside content page.
Does the first one (in master page) prevent the second one (in content page) from firing ?
It's the other way round. The one on the Content Page will be fired first. To know if one is messing with the other, simply debug it on Firebug or even on Visual Studio.
You can use the jQuery syntax to chain functions to run on page load in both Master and Child pages like this:
$().ready(function() {
// Do stuff
}
Contents will be execute in the order that the appear on the page, from top to bottom.
You could force items to be run in a specific order with a construct like this in your MasterPage:
<script>
$().ready(function() {
// Do MasterPage stuff
if (onChildPageLoad) onChildPageLoad();
});
</script>
and in the child page place a script block like this:
<script>
var onChildPageLoad = function() {
// Do childpage stuff
}
</script>

jQuery Mobile Binding Spinner To ChangePage

After a lot of google'ing and reading forums I've not found a suitable answer.
So far all I have found is something like below:
show loading message
call change page
hide loading message
This would work but I would have to do this every time I call load/change page (which is a lot).
Which would leave me either to make a middle man function like below:
function customLoader(url){
showLoader();
$.mobile.changePage(url);
hideLoader();
}
Is there anyway of binding it to the change page event?
So that it shows from the second changePage is called but hides once changePage is away...
I know the above middle man method would work but would like something more tidy and nicer to implement as there's a lot of html/js files.
Something like this:
$('#index').live('pagebeforeshow',function(e,data){
$('#test-button').live('click', function(e) {
$.mobile.showPageLoadingMsg(true);
setTimeout(function () {
$.mobile.changePage('#second');
}, 1000);
});
});
$("#second").live('pageshow', function () {
$.mobile.hidePageLoadingMsg();
});
Timeout is here only so you can see it's working successfully. This is a light example so transition is fired quickly. Remove it in your real code.
And here's an example: http://jsfiddle.net/Gajotres/arrHd/
Every change page event cycle has a order of events occuring when a page A is transiting to a page B. No matter which action is used to trigger a change page you can always disable it when page B i successfully loaded. If you want to find more about page load order take a look at this link: https://stackoverflow.com/a/14010308/1848600. There you will find a lot about jQM page dynamics.
In case you want to implement this into every page transition use this:
$('[data-role="page"]').live('pageshow', function () {
$.mobile.hidePageLoadingMsg();
});
This will hide a ajax loader (if it is open) every time a different page is successfully loaded and shown.
Maybe it's too much for many, but I found a solution different than the written in the comments of this question.
I use the jquery mobile router and in the 'show' event of a page, I do $.mobile.loading("show");, so when the page appears it does with the loading spinner showing.
I use Jquery Mobile Router for a lot more, but it solved this issue.
Though to hide the spinner, I had to use $('.ui-loader').hide();, which is weird, I know...
(Maybe just listening to the proper event and triggering the spinner would also work, as this is what JQMR does...)
I'm using JQM 1.4.2...

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources