im trying to make a script that load content from a web service when user scroll to the bottom of the page this is my JS code :
var serviceURL = "http://projects.dev/work/";
var current_page = 1;
var total_pages = 1;
$(function() {
Init();
});
function Init() {
getPosts();
$(window).scroll(function(){
if((($(window).scrollTop()+$(window).height())+20)>=$(document).height()){
if(current_page <= total_pages){
getPosts();
}
}
});
}
function getPosts(){
$.ajax({
url:serviceURL+"api/posts?page="+current_page,
dataType: "json",
async : false,
cache : false,
}).then( function(data){
total_pages = data.last_page;
$.each(data.data, function(index, post) {
$('#newsList').append("<li>"+
"<aside><img src='"+serviceURL+"cdn/"+post.picture+"'></aside>"+
"<div>"+
"<a href='post.html?id="+post.id+"'><h3>"+post.title+"</h3></a>"+
"<h4>"+post.created_at.split(" ")[0]+"</h4>"+
"</div>"+
"</li>");
});
$("#loading").hide("slow");
current_page++;
});
}
<!DOCTYPE html>
<html dir="rtl">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div id="loading"><div id="loading-spin"></div></div>
<header><div id="brand">News</div>
</header>
<article style="width:100%;margin:0 !important;padding-right:0 !important;padding-left:0 !important;">
<ul id="newsList"></ul>
</article>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/posts.js"></script>
</body>
</html>
can you tell me whats wrong ? i can get only posts from the first time and then nothing happen when i scroll to the bottom of the page .
PS : i have a lot of posts , and the last_page variable is the total of pages i have on my DB .
i fixed it , i had to remove overflow:hidden from the container .
thanks .
Related
I have a site that should first load external js codes before it executes code in the dom but i wont work. Everytime my external codes load after the js in the body tag what caused problems like undefined classes and variables
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Site</title>
<link rel="stylesheet" href="./style.css">
<script src="./project/load.js"></script>
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="./script.js"></script>
</body>
</html>
./project/load.js
window.onload = function() {
var links = ["./project/script1.js", "./project/script2.js", "./project/script3.js"];
for(var link of links) {
var script = document.createElement("script");
script.src = link + "?0";
script.setAttribute("onerror", "reload(this)");
document.head.append(script);
}
}
I tried also with 'addEventListener('DOMContentLoaded', function() {...});' but it did work either.
I hope you can help me.
EDIT 1:
request order
./project/load.js
./script.js
./project/script1.js
./project/script2.js
./project/script3.js
Load your javascript with defer attribute. Replace your HTML with below. The "defer" attribute allows the javascript is run only after the page loading is complete. Meaning the DOM is available
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Site</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="./project/load.js" defer></script>
<script src="./script.js" defer></script>
</body>
</html>
References and further read
https://www.sitepoint.com/introduction-jquery-deferred-objects/
https://www.w3schools.com/tags/att_script_defer.asp
Here is what i've done. Please look at this below
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Site</title>
</head>
<body>
<h1>project</h1>
<div id="project"></div>
<script src="load.js" defer></script>
<script src="script.js" defer></script>
</body>
</html>
Javascript - load.js
(function(){
var dom = document.getElementById("project");
if( dom !== null ){
dom.innerHTML = "<p>Iam load.js " + new Date().toString() + "</p>";
console.log("Iam load.js " + new Date().toString());
}
})();
Javascript - script.js
(function(){
var dom = document.getElementById("project");
if( dom !== null ){
dom.innerHTML = dom.innerHTML + "<p>Iam script.js " + new Date().toString() + "</p>";
console.log("Iam script.js " + new Date().toString());
}
})();
Output
You can see that the order in which i've added the script loads first.
In one of my jsp file I am calling the "basicEn.js" in the head
<head>
<meta charset="UTF-8">
<meta name=viewport
content="width=device-width, initial-scale=1, maximum-scale=1">
<META http-equiv="Content-Style-Type" content="text/css">
<link rel="stylesheet" type="text/css" href="index.css">
<script src="javascript/jquery-3.1.0.min.js"></script>
<script src="javascript/basicEn.js"></script>
<title>Insert title here</title>
</head>
However when I checked from the firebug the "basic.js" is running. Probably, I am missing a tiny thing but I am really stuck.
//basicEn.jsp
$(document).ready(function() {
// Your event
$('li').click(function() {
var id = $(this).attr('id');
$.ajax({
url:'GetPhone',
data:{id : id},
dataType:"text",
type:'get',
cache:false,
success:function(data){
//alert(data);
var successUrl = "SelectedFeature-en.jsp";
window.location.href = successUrl;
},
error:function(){
alert('error');
}
}
);
});
});
I'm trying to redirect with javascript after a 3-second delay, but my code currently does nothing. index.html is supposed to redirect to menupage.html after a 3-second delay, but nothing happens. menupage.html has 4 buttons on it: "Device motion" uses Phonegap's accelerometer and compass to show the device's speed and direction, and the other 3 just open new pages in Phonegap's in-app browser. Here is the code:
EDIT: It was just a file location error. The redirect works. Thank you!
<!--index.html-->
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0" />
<head>
<meta charset="utf-8" />
<title></title>
<link href="JQueryMobile/jquery.mobile-1.2.0.css" rel="stylesheet" />
<script src="JQueryMobile/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="JQueryMobile/jqm-docs.js" type="text/javascript"></script>
<script src="JQueryMobile/jquery.mobile-1.2.0.js" type="text/javascript"></script>
<link rel="stylesheet" href="styles/styles.css" />
</head>
<body onload="redirect()">
<img id="load-img" src="loading.jpg" />
<script src="scripts/scripts.js"></script>
</body>
</html>
<!--menupage.html-->
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8" />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0" />
<head>
<title>Menu</title>
<script type="text/javascript" src="phonegap.js"></script>
<link href="styles/styles.css" rel="stylesheet" />
</head>
<body>
<button id="devmotion" onclick="getMotion()">Device Motion</button>
<button id="ucla" onclick="openUCLA()">UCLA</button>
<button id="espn" onclick="openESPN()">ESPN</button>
<button id="google" onclick="openGoogle()">Google</button>
<script src="scripts/scripts.js"></script>
<script src="scripts/jquery-2.1.1.min.js"></script>
</body>
</html>
<!--devicemotion.html-->
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=yes, initial-scale=1.0, maximum-scale=1.0" />
<head>
<title>Acceleration and Compass Direction</title>
<script type="text/javascript" src="phonegap.js"></script>
<link href="styles/styles.css" rel="stylesheet" />
</head>
<body>
<div id="accel"></div>
<div id="compassdirection"></div>
<button id="goback" onclick="backToMenu()">Back</button>
<script src="scripts/scripts.js"></script>
<script src="scripts/jquery-2.1.1.min.js"></script>
</body>
</html>
<!--scripts.js-->
// JavaScript source code
function redirect() {
window.setTimeout(function() {
window.location.replace("menupage.html");
}, 3000)
}
function getMotion() {
window.location = "devicemotion.html";
//window.open("devicemotion.html", "_self", "location=yes");
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
navigator.compass.getCurrentHeading(compassSuccess, compassError);
}
function backToMenu() {
window.location = "menupage.html";
}
function accelerometerSuccess(acceleration) {
acclrtn = 'Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n';
document.getElementById("accel").innerHTML = acclrtn;
};
function accelerometerError(error) {
alert("Accelerometer error: " + accelerometer.code);
}
function compassSuccess(heading) {
direction = "Direction: " + heading.magneticHeading;
document.getElementById("compassdirection").innerHTML = direction;
}
function compassError(error) {
alert("Compass error: "+error.code);
}
function openUCLA() {
window.open('www.ucla.edu', '_blank', 'location=yes');
}
function openESPN() {
window.open('www.espn.com', '_blank', 'location=yes');
}
function openGoogle() {
window.open('www.google.com', '_blank', 'location=yes');
}
it should be
window.location.href = "http://yoursite.com/menupage.html";
Update
Seems that the logic that leads up to the redirect is not working. You are defining an onload handle in the body tag <body onload="redirect()">, the catch is that when that command executes, the redirect function does not exist yet because you are loading the js at the end of the document (which is correct). You could do 2 things.
Given that your scripts are at the end, calling a function at the end of the script would only be executed after the browser has downloaded html and js, behaving similarly to an onload event.
// At the end of scripts.js
// ... omitted for brevity ...
function openGoogle() {
window.open('www.google.com', '_blank', 'location=yes');
}
// simply call the function
redirect();
To catch the window.onload event properly with cross browser compatibility is known to be a nightmare. Fortunately jQuery fixes this so you could use its initializer in case you have it or can include jQuery.
$(function(){
// this only happens when the document is ready!
redirect();
});
Finally your redirect function should look something like this
function redirect() {
window.setTimeout(function() {
window.location.href = "menupage.html";
// if you need to replace a part of the current url
// for example going from http://example.com/summer/index.html
// to http://example.com/winter/index.html you can
// window.location.href = window.location.href.replace('summer', 'winter');
}, 3000)
}
Have you tried using php to redirect? I believe it would be much easier to use.
header( "refresh:3;url=menupage.html" );
This is the code to get temperature of London from Open weather API. It works fine
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/body.css" />
<meta name="msapplication-tap-highlight" content="no" />
</head>
<body>
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script language="javascript" type="text/javascript">
<!--
function foo(callback) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: callback
});
}
function myCallback(result) {
var temp = JSON.stringify(JSON.parse(result.main.temp));
var Kelvin = 272;
var Centigrade = Math.round(temp-Kelvin);
if (Centigrade <= 25) {
//alert("Temperature : "+Math.round(Centigrade)+" C");
var temp = document.getElementById("temp");
temp.style.fontSize = "20px";
temp.innerHTML = Centigrade+"° C , Cool "+"<img src= \"img/Tlogo2.svg\"/>";
//document.getElementById("temp").innerHTML = Centigrade+"° C , Cool "+"<img src= \"img/Tlogo2.svg\"/>";
}
else if (Centigrade > 25) {
var temp = document.getElementById("temp");
temp.style.fontSize = "20px";
temp.innerHTML = Centigrade+"° C , Cool "+"<img src= \"img/Tlogo3.svg\"/>";
//document.getElementById("temp").innerHTML = Centigrade+"° C , It's Hot !!! "+"<img src= \"img/Tlogo3.svg\"/>";
}
}
</script>
<div style="position: absolute; left: 30px; top: 75px;">
<img src="img/temlogo.svg" width="35" height="35" onclick="foo(myCallback);"/>
</div>
<p id="temp"></p>
</body>
</html>
Now I tried with bootstrap for some nice visualization :
<!DOCTYPE html>
<html>
<body>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("[data-toggle='popover']").popover();
});
</script>
</body>
Temperature
</html>
It is dissmissable popover.
Now what I am trying is I want get temperature as popover element. ie. if I click on image button, it should trigger temperature acquiring function and then show the temperature and the image related to that in popover box. So here is two challenge I am facing.
Setting a image instead of the red button and then temperature data
List item and the image ie. Tlogo2.svg to be appeared in that pop
over box.
So can anyone suggest how to set that?
For more clarification I am adding another code. Here in data content shows function name. But I want the result of the function:
<!DOCTYPE html>
<html>
<body>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script language="javascript" type="text/javascript">
//Function
function foo(callback) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: callback
});
}
function myCallback(result) {
var temp = JSON.stringify(JSON.parse(result.main.temp));
var Kelvin = 272;
var Centigrade = temp-Kelvin;
alert("Temperature : "+Math.round(Centigrade)+" C");
//document.getElementById("temp").innerHTML = "Temperature : "+Math.round(Centigrade)+" C";
}
$(function() {
$("[data-toggle='popover']").popover(myCallback);
});
</script>
</body>
<a href="#" tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Temperature" data-content= "myCallback(result);" >Temperature</a>
</html>
Please Help me out.
Use the Popover's Options to beautify your popover. Using these options you can have complete control over the functionality and appearance of your popover.
http://getbootstrap.com/javascript/#popovers-usage
This fiddle only demonstrates a few of these options...
Js Code
$(document).ready(function(){
$(".popover-examples a").popover({
title : 'Weather App',
trigger: 'hover',
template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div><img src="http://lorempixel.com/100/100" /><span>Just an example of inserting image in a Popover...</span></div>'
});
});
HTML
<div class="bs-example">
<p class="popover-examples">
<a href="#" class="btn btn-lg btn-primary" data-toggle="popover" >Popover Example</a>
</p>
</div>
Checkout this demo.
function foo() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(result) {
var temp = JSON.stringify(JSON.parse(result.main.temp));
var Kelvin = 272;
var Centigrade = temp-Kelvin;
var temperature = "Temperature : "+Math.round(Centigrade)+" C";
$('span.temp-val').text(temperature);
}
});
}
$(document).ready(function(){
$(".popover-examples a").popover({
title : 'Weather App',
trigger: 'hover',
template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div><img src="http://lorempixel.com/100/100" /><span class="temp-val">Just an example of inserting image in a Popover...</span></div>'
});
$(".popover-examples a").hover(function() { foo(); })
});
You need to call the ajax function at hovering the trigger element. Also, set an identifier for the temperature in your template - this way you can set it to the obtained value using the ajax call.
I'm currently using the following code to pass parameters from my main page to a popup in jquery mobile:
<a onclick= DisplayEditIdPopUP('" . $row ['IdentificationTypeID'] ."','".$custid."','". $num."','".$row ['CustomerIdentificationId']."')>Edit</a>
however, Ive setup a zoom plugin which seems to break my on click. Is there a way to pass parameters through a regular anchor tag, without using the on click event? As calling the popup using the following code works, but obviously doesn't pass any parameters at the moment?
<a href='#addCustId' data-rel='popup' data-position-to='window' data-transition='pop' class='ui-btn ui-btn-c' >New</a>
Thanks
Several solutions exist:
Solution 1:
You can pass values with changePage:
$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
And read them like this:
$(document).on('pagebeforeshow', "#index", function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
$(document).on('pagebeforeshow', "#index",function () {
$(document).on('click', "#changePage",function () {
$.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });
});
});
$(document).on('pagebeforeshow', "#second",function () {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="index">
<div data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
<a data-role="button" id="changePage">Test</a>
</div> <!--content-->
</div><!--page-->
</body>
</html>
second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="second">
<div data-role="header">
<h3>
Second Page
</h3>
</div>
<div data-role="content">
</div> <!--content-->
</div><!--page-->
</body>
</html>
Solution 2:
Or you can create a persistent javascript object for a storage purpose. As long ajax is used for page loading (and page is not reloaded in any way) that object will stay active.
var storeObject = {
firstname : '',
lastname : ''
}
Example: http://jsfiddle.net/Gajotres/9KKbx/
Solution 3:
You can also access data from the previous page like this:
$(document).on('pagebeforeshow', '#index',function (e, data) {
alert(data.prevPage.attr('id'));
});
prevPage object holds a complete previous page.
Solution 4:
As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.
if(typeof(Storage)!=="undefined") {
localStorage.firstname="Dragan";
localStorage.lastname="Gaic";
}
Example: http://jsfiddle.net/Gajotres/J9NTr/
Find more about them here.