Run function on page load (Refresh RSS feed with new URL) Javascript - javascript

I have an app where I want to display different RSS feeds on one page, when the corresponding team is clicked.
For example, when I click "Aberdeen" I want the page to show the RSS for Aberdeen.
When I click "Celtic", i want the same page to display the RSS for Celtic.
I will attach my code in one section - basically when the page #feed loads, I need to run the getFeed() function.
I am using jQuery Mobile.
HTML for "feed" page
<div data-role="page" id="feed">
<div data-role="header">
<h1 id="fheader">Header</h1>
</div>
<div data-role="content">
Add to My Teams
<ul data-role="listview" class="list" data-inset="true" >
</ul>
</div>
</div>
Function to getFeed
var feedURL="http://www.football365.com/arsenal/rss";
var n = 12;
function getFeed(url, success, n){
url= feedURL.replace("??", n.toString());
if(window.navigator.onLine) {
$.jGFeed(url, function(feeds) {
// Check for errors
if(!feeds){
// there was an error
return;
} else {
localStorage.setItem(url, JSON.stringify(feeds));
success(feeds.title, feeds.entries);
}
},n );
} else {
// Get the fall-back...
var feed = JSON.parse(localStorage.getItem(url));
if(feed && feed.length > 0) {
success(feed.title, feed.entries);
}
}
}
$(document).on('pagebeforeshow',function(){
getFeed(feedURL,function(title,items){
$("#title").text(title);
for(var index=0; index<items.length; index+=1){
$("#list").append(formatItem(items[index]));
}
$("#list").listview('refresh');
},20);
} );
Function to find RSS URL based on team
function getIndex(teamlist, teamname){
for(var i = 0; i<teamlist.length; i++){
if(teamlist[i].teamname == teamname){
return i; // if found index will return
}
}
return -1; // if not found -1 will return
}
var a = getIndex(teamlist,name); // will give a as 0
console.log(a);
feedURL = teamlist[a].rss_url;
console.log(feedURL);
As you can see, the RSS URL for a specific team is found via index in array. Once it has found the array, it assigns it to the feedURL variable. This part works fine
However, when the page opens, it does not take into consideration the change in variable. I need to refresh or rerun the getFeed() function to take into account the new value of feedURL.
Hope this clears things up :) Thanks :)

If you want to run your function when the page has loaded just use:
$(document).ready(function(){
getFeed();
};
This will run your function when the page has fully rendered and the #feed element is available.

Related

start second page where first page end in javascript

I have some issue with the window scroll.
I created a news feed like page using angularjs with database and pagination and ng-repeat.
I want that when user click on load more button window will scroll to last position of the page 1 and then page 2 start, but I tried all option but it not working like what I want.
But it always send me last of the document.
Here is the code for reference...
$scope.feedCopy=function(){
$scope.loader=false;
$http.get('http://web.com/app/get_feeds/1/'+$scope.member_id+'?page='+$scope.feeds_current_page).then(function(response){
$scope.feeds = $scope.feeds.concat(response.data.data);
$scope.feeds2=angular.copy($scope.feeds);
$current_index=$scope.feeds2[0].feed_id;
var i=0;
$scope.showLess=true;
$scope.showMore=false;
for(i;i<$scope.feeds2.length;i++)
{
$scope.feeds2[i].show_less=1;
if($scope.feeds[i].feed_text!=null)
{
$scope.original_length=$scope.feeds2[i].feed_text.length;
$scope.feeds2[i].feed_text=$scope.feeds[i].feed_text.substring(0,40);
$scope.temp_length=$scope.feeds2[i].feed_text.length;
if($scope.temp_length>=$scope.original_length)
{
$scope.feeds2[i].show_less_button=1;
}
}
else
{
$scope.feeds2[i].show_less=-1;
}
}
$scope.feeds_total_page=response.data.total_pages;
if($scope.feeds_total_page>$scope.feeds_current_page)
{
$scope.feeds_current_page+=1;
$scope.load_more=true;
}
$scope.feed_condition_current_page++;
});
$scope.iframeHeight = document.documentElement.scrollHeight;
window.scrollTo(0,($scope.iframeHeight))
//alert($scope.iframeHeight);
}
Inject $window service in to your controller.
$window.open("your_path/", "_blank")

Preventing reloading Ajax data when back-button is clicked in both Chrome and IE

I am currently working on a website in which the home page displays the most recent 10 blog entries. When I scroll down, and when I reach almost the end of the last item on screen, another 10 blog entries are automatically loaded, and so on (this is the infinite scrolling feature).
If a user clicks on any blog entry, then he/she is taken to another page to display the details about that blog entry. When the user clicks the back button, he/she is taken to the home page that has the entries displayed.
Please note, the home page loads the data using Ajax.
Assume the following scenario:
A user goes to the site, and entries 1 to 10 are loaded (via Ajax).
The user scrolls down, and the next 10 entires, specifically entries 11 to 20 are loaded (via Ajax as well). Note that the page now has entires 1 to 20 displayed.
The user scrolls further down, and now entries 21 through 30 are loaded, for a total of 1 through 30 blog entries being displayed on the page.
The user clicks on entry 25, and the page for entry 25 is displayed.
The user clicks the back button, and all items, 1 through 30 are displayed.
Now, if the users uses FireFox, Opera, or Safari, and when that user performs step 5 (i.e, clicks the back button to go back to the home page) then the blog entries are just displayed on screen, and without being re-loaded. However using IE and on Chrome, when the user clicks on the back button, the page is reloaded, and only items 1 through 10 are displayed.
I do not like the IE and Chrome behaviour. The user should see items 1 though 30. How can I ensure all browsers behave like FireFox?
Thanks.
Update
Here is the code I am using
First, hers is my html
<html>
<body>
<section id="content">
<section id="articles">
<!-- This section is filled by jQuery/Ajax -->
</section>
<section id="loading-spinner">
<img src="ajax-loader.gif" />
</section>
</section>
</body>
</html>
And here is my jQuery
/**
*
* This file uses a bunch of programming concepts, but the most important one is ensuring ajax calls run as a critical section
* ... (this means if ajax is already called, then another instance of JavaScript cannot get into the critical section)
*
* .. For more details, please read: http://stackoverflow.com/questions/22150960/critical-section-in-javascript-or-jquery
*
*/
load_more_posts = function () {
// If we almost reach the bottom of the document, then load more posts
if ( jQuery(window).scrollTop() >= jQuery(document).height() - jQuery(window).height() - 300) {
// If the value of the promise is not pending, then we can call the load_posts function (the load_posts function will change the status to pending when it is executing the ajax request)
if (ajax_status.state() !== "pending") {
load_posts();
}
}
};
function load_posts() {
ajax_status = jQuery.ajax({
type: 'post',
dataType: 'json',
beforeSend: function(xhr) {
if(jQuery.data(document.body, 'load_page') == false) {
xhr.abort();
}
else {
// Show the spinner
jQuery('#loading-spinner').visible();
}
},
url: '../link/to/get_poasts.php',
data: {
action: 'load_posts',
js_query_data: query_data,
js_page: jQuery.data(document.body, 'page_to_load')
},
success: function (response) {
if (response.isSuccessful) {
var number_of_post_items = response.posts_array.length;
for (var i = 0; i < number_of_post_items; i++) {
// If the item is already returned from the database and posted. then we skip it, otherwise, keep insert a new record
if (jQuery('#articles').find('#article-' + response.posts_array[i].post_id).length == 0) {
// Add 'article'
jQuery('#articles').append('<article id="article-' + response.posts_array[i].post_id + '"></article>');
// More code here to add details about each article, such as title, excerpt...etc.
}
}
// Increase the value of the page to load by 1, and save it.
page = jQuery.data(document.body, "page_to_load");
page = page + 1;
jQuery.data(document.body, "page_to_load", page);
jQuery(window).on('scroll', load_more_posts);
}
else {
// Display error message
jQuery('#articles').append('<div>' + response.message + '</div>');
// Make sure no further AJAX requests are made
jQuery.data(document.body, 'load_page', false);
}
}
}).always(function() {
// Hide the spinner
jQuery('#loading-spinner').invisible();
});
return ajax_status;
}
// Create a new promise. This will be used to ensure that no two calls hit the critical section at the same time
// ... (the critical section in this case is the time when we retrieve data from the database. We only want one call at a time)
var ajax_status = new jQuery.Deferred();
jQuery(document).ready(function() {
// Hide the loading spinner first
jQuery('#loading-spinner').invisible();
// We resolve the promise, making sure it is ready (this is an intial state)
ajax_status.resolve();
// Initial values that are used
jQuery.data(document.body, 'page_to_load', 1);
// This parameter is used to stop loading pages when no more items are available to be displayed
jQuery.data(document.body, 'load_page', true);
// Initial loading of poasts
load_posts();
// Enable on scrolling to load more pasts (to allow infinite scrolling)
jQuery(window).on('scroll', load_more_posts);
});
You'll find some information about how it works in the "good" browsers in this answer:
Is there a cross-browser onload event when clicking the back button?
Here you'll find a way to emulate it in IE:
Differences in Internet Explorer and Firefox when dynamically loading content then going forward and back
Not quite sure why it doesn't work in Chrome though.
Just so everyone knows, here is the solution I came up with that is consistent in all browsers. Unfortunately this solution requires a reloead/refresh button to reload the data. I tried to avoid that but could not. Until both IE and Chrome tackle the bfcache issue, I will stick to this solution.
First, here is the new html
<html>
<body>
<section id="content">
<a id="refresh">
<img src="link/to/refresh.png" title="Refresh" alt="refresh" />
</a>
<section id="articles">
<!-- This section is filled by jQuery/Ajax -->
</section>
<section id="loading-spinner">
<img src="ajax-loader.gif" />
</section>
</section>
</body>
</html>
And this is the javascript
/**
*
* This file uses a bunch of programming concepts, but the most important one is ensuring ajax calls run as a critical section
* ... (this means if ajax is already called, then another instance of JavaScript cannot get into the critical section)
*
* .. For more details, please read: http://stackoverflow.com/questions/22150960/critical-section-in-javascript-or-jquery
*
*/
load_more_posts = function () {
// If we almost reach the bottom of the document, then load more posts
if ( jQuery(window).scrollTop() >= jQuery(document).height() - jQuery(window).height() - 300) {
// If the value of the promise is not pending, then we can call the load_posts function (the load_posts function will change the status to pending when it is executing the ajax request)
if (ajax_status.state() !== "pending") {
load_posts();
}
}
};
function load_posts() {
ajax_status = jQuery.ajax({
type: 'post',
dataType: 'json',
beforeSend: function(xhr) {
if(jQuery.data(document.body, 'load_page') == false) {
xhr.abort();
}
else {
// Show the spinner
jQuery('#loading-spinner').visible();
}
},
url: '../link/to/get_poasts.php',
data: {
action: 'load_posts',
js_query_data: query_data,
js_page: sessionStorage.getItem("page_to_load")
},
success: function (response) {
if (response.isSuccessful) {
var number_of_post_items = response.posts_array.length;
for (var i = 0; i < number_of_post_items; i++) {
// If the item is already returned from the database and posted. then we skip it, otherwise, keep insert a new record
if (jQuery('#articles').find('#article-' + response.posts_array[i].post_id).length == 0) {
// Add 'article'
jQuery('#articles').append('<article id="article-' + response.posts_array[i].post_id + '"></article>');
// More code here to add details about each article, such as title, excerpt...etc.
var history_session = get_history_session_name();
var history = sessionStorage.getItem(history_session);
var article_content = jQuery('#articles').find('#aarticle-' + response.posts_array[i].post_id)[0].outerHTML;
sessionStorage.setItem(history_session, history + article_content);
}
}
// Increase the value of the page to load by 1, and save it.
page = parseInt(sessionStorage.getItem("page_to_load"));
page = page + 1;
sessionStorage.setItem("page_to_load", page);
jQuery(window).on('scroll', load_more_posts);
}
else {
// Display error message
jQuery('#articles').append('<div>' + response.message + '</div>');
// Make sure no further AJAX requests are made
jQuery.data(document.body, 'load_page', false);
}
}
}).always(function() {
// Hide the spinner
jQuery('#loading-spinner').invisible();
});
return ajax_status;
}
function get_history_session_name () {
session_name = 'history___' + escape(location.href);
return session_name;
}
// Create a new promise. This will be used to ensure that no two calls hit the critical section at the same time
// ... (the critical section in this case is the time when we retrieve data from the database. We only want one call at a time)
var ajax_status = new jQuery.Deferred();
jQuery(document).ready(function() {
// Hide the loading spinner first
jQuery('#loading-spinner').invisible();
// We resolve the promise, making sure it is ready (this is an intial state)
ajax_status.resolve();
// This parameter is used to stop loading pages when no more items are available to be displayed
jQuery.data(document.body, 'load_page', true);
// Get the name of the history session
var history_session = get_history_session_name();
if (sessionStorage.getItem(history_session) === null) {
// Set the history session storage
sessionStorage.setItem(history_session, "");
// Initial values that are used
sessionStorage.setItem("page_to_load", 1);
// Load the posts
load_posts();
}
// Load from history when the back button is clicked
else {
jQuery('#articles').append(sessionStorage.getItem(history_session));
}
// Enable on scrolling to load more pasts (to allow infinite scrolling)
jQuery(window).on('scroll', load_more_posts);
// Reload data when the refresh button is clicked
// ... We are using a refresh button because if we go to a page that already had history, ...
// ... and even though we went to that page without using the back button (i.e, via links or directly via the url), ...
// ... then the history session will be displayed. ...
// ... Therefore a reload button is needed to overcome this problem if you like to reload data
jQuery("#refresh").click(function () {
// Reset/clear the articles section first
jQuery('#articles').html("");
// reset the 'load_page' variable
jQuery.data(document.body, 'load_page', true);
// Reset/clear the history session storage
sessionStorage.setItem(history_session, "");
// Start with loading page 1
sessionStorage.setItem("page_to_load", 1);
// Load the posts
load_posts();
});
});
Hope this helps.

Angular Data updating

Good afternoon I'm developing a project with angular js
and i have a page with a list of items that gets updated depending on the gps coordinates of the smartphone.
When I stay on the same page everything works perfectly and the page gets updated with the correct items
But when I change to a different page and then go back to the page with the list then the data gets updated in the model (checked with a console.log -> there are items in the array) but then when you look at the web page the list is still empty
snippet from html page (the list)
<label class="item item-radio" ng-repeat="project in projectsAtLocation">
<input type="radio" name="projects" ng-model="info.currentProject" ng-value="project.id">
<div class="item-content">
{{project.name}} - {{project.customer}}
</div>
<i class="radio-icon ion-checkmark"></i>
</label>
methods in the controller which adjusts the data for the list (these methods are called when the controller gets created and when the gps coordinates change)
$scope.clearCurrentProjectsAtLocations = function () {
console.log("current projects cleared");
while ($scope.projectsAtLocation.length > 0) {
$scope.projectsAtLocation.pop();
}
//$scope.projectsAtLocation = null;
};
$scope.updateCurrentProjects = function (locationId, callback) {
//$scope.projectAtLocation = [];
ProjectLocationDbService.getAllByLocationId(locationId,
//Success
function (tx, results) {
//Success
if (results.rows.length != 0) {
//Track on a project
//Update the list of projects at the current location
TrackingService.setProjectsAtLocation(results.rows);
for (var i = 0; i < results.rows.length; i++) {
$scope.projectsAtLocation.push(results.rows.item(i));
}
//If we only 1 project at the current location ==> start automatically tracking at it
if (results.rows.length == 1) {
$scope.info.currentProject = results.rows.item(0).id;
}
$scope.$apply();
}
callback();
},
//Error
function () {
}
);
};
I think the code is quite self explanatory but if you got a question about the code ill do my best to answer
And i will greatly appreciate any feedback to help solve this problem
Regards,
Bavo

How Can I Insert My Javascript Into My Drupal Site/Node

I'm trying to insert a cookie that is provided by a video host that will resume a video where the user left off. They have an example that obviously works. When trying to insert this into my Drupal site, the cookie won't work. The video just starts back at the beginning.
I have enabled "PHP input filter", as I read that I needed to do that for drupal to insert the script. Please see the code that is in my node below.
Can anyone help me figure out why this isn't working, how to get it to work, or a better way of doing this with Drupal?
Thank you,
<script type="text/javascript">
wistiaEmbed.ready( function() {
var all_cookies = document.cookie.split(';'), // gets the value of the cookies on the page
cookie_str = "resume_video=",
resume_cookie = does_resume_cookie_exist(all_cookies);
function does_resume_cookie_exist(cookie_arr) {
var i, curr_string, found;
for (i = 0; i < cookie_arr.length; i++) {
curr_string = cookie_arr[i];
if (curr_string.substring(0,5) === cookie_str.substring(0,5)) {
// we've found it!
found = curr_string;
break;
}
}
return found;
}
function set_cookie_time(t) {
document.cookie = cookie_str + t.toString(); // this takes the time (t) and sets the cookie with that time
}
if (resume_cookie) {
num = resume_cookie.split('=')[1];
start_time = parseInt(num);
wistiaEmbed.time(start_time).play(); // plays the video at the specific time defined in the cookie upon return to the page
} else {
set_cookie_time(0); // places a cookie on the visitor
wistiaEmbed.play(); // starts the video from the beginning
}
wistiaEmbed.bind("timechange", function(t) { // on timechange, reset cookie
set_cookie_time(t);
});
wistiaEmbed.bind("end", function() { // if person has watched the entire video, sets the video to beginning upon retun
set_cookie_time(0);
});
});
</script>
<div id="wistia_npcc5k96s9" class="wistia_embed" style="width:640px;height:508px;"> </div>
<script charset="ISO-8859-1" src="http://fast.wistia.com/assets/external/E-v1.js"> </script>
<script>
wistiaEmbed = Wistia.embed("npcc5k96s9");
</script>**strong text**
What version of drupal are you using? Does the code that you gave actually output in your request response?
There are several solutions to this (IMO).
If the code is showing up in the response, it could be some other javascript error that preventing your code from executing.
If that snippet of code is applicable to all nodes of that type you can use the node_view hook in order to inject your code on that node type, for example (I am assuming D7):
function mymodule_node_view($node, $view_mode)
{
if($node->type =='video_page')
{
drupal_add_js('resume_video.js'); // this js holds your code snippet
}
}
Here's a reference that could help you out
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7
You can similarly inject that snippet of code at the theme layer using a theme hook, probably hook_preprocess https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7
Hope that helps.

Count number of rows to generate a certain number of tabs

So I have something which allows the user to add tabs and take away tabs... however how would I go about generating the default number of tabs based on data from my sql database. For example if they were 4 rows with the same id in the id filed, it would generate 4 tabs as there is 4 rows with the same id.
here is the tab thing I found.
<script>
$(function() {
var total_tabs = 0;
// initialize first tab
total_tabs++;
addtab(total_tabs);
$("#addtab, #litab").click(function() {
total_tabs++;
$("#tabcontent p").hide();
addtab(total_tabs);
return false;
});
function addtab(count) {
var closetab = '×';
$("#tabul").append('<li id="t'+count+'" class="ntabs">Session '+count+' '+closetab+'</li>');
$("#tabcontent").append('<p id="c'+count+'">Tab Content '+count+'</p>');
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#t"+count).bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
});
$("#close"+count).bind("click", function() {
// activate the previous tab
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+count).prev().fadeIn('slow');
$(this).parent().remove();
$("#c"+count).remove();
return false;
});
}
});
</script>
<ul id="tabul">
<li id="litab" class="ntabs add">Add tab + </li>
</ul>
Thanks James
Please refer to this answer, Basically, you have to follow the same principle.
Then, call addtab(rowId) in a for loop by using the returned data from your database.
Still not sure what you meant by rows with the same ID, though.

Categories

Resources