Hi I only started working on JQuery Mobile a month ago and my starting project was to build an app to load my blog posts. After spending days and night researching and support from SO, I did manage to get my blog posts loaded and also added a Load More link to append new contents.
My intention no is rather than use a link, I want the new contents appended when I scroll to end of page. I do not plan to use a plugin for now but was hoping I could write a simple code to do that for me. This is my current code (First function to load initial contenst while the 2nd function is to append more contents. Not sure if this is the best approach but like I said, I am still in learning process)
$(document).on('pagebeforeshow', '#blogposts', function () {
$.ajax({
url: "http://howtodeployit.com/?json=recentstories",
dataType: "json",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
},
success: function (data) {
$('#postlist').empty();
$.each(data.posts, function (key, val) {
//Output data collected into page content
var rtitle = $('<p/>', {
'class': 'vtitle',
html: val.title
}),
var rappend = $('<li/>').append(rtitle);
$('#postlist').append(rappend);
return (key !== 5);
});
$("#postlist").listview().listview('refresh');
},
error: function (data) {
alert("Service currently not available, please try again later...");
}
});
});
$(document).on("click", ".load-more", function () {
$.getJSON("http://howtodeployit.com/?json=recentstories", function (data) {
var currentPost = $('#postlist');
console.log(currentPost);
loadMore = currentPost.parent().find('.load-more');
var currentPostcount = $('#postlist li').length;
console.log(currentPostcount);
var desiredPosts = 3;
newposts = data.posts.slice(currentPostcount, currentPostcount + desiredPosts);
$.each(newposts, function (key, val) {
var rtitle = $('<p/>', {
'class': 'vtitle',
html: val.title
}),
var rappend = $('<li/>').append(rtitle);
$('#postlist').append(rappend);
$("#postlist").listview('refresh');
});
});
});
Sorry if this type of question had been answered else where. Please post link
This is a typical approach with jquery,
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
/*end reached*/
$('.content').html($('.content').html()+"more</br></br></br></br>");
}
});
example with jqm,
http://jsfiddle.net/F5McF/
Try this example it works.
function loaddata()
{
var el = $("outer");
if( (el.scrollTop + el.clientHeight) >= el.scrollHeight )
{
el.setStyles( { "background-color": "green"} );
}
else
{
el.setStyles( { "background-color": "red"} );
}
}
window.addEvent( "domready", function()
{
$("outer").addEvent( "scroll", loaddata );
} );
Fiddle is
http://jsfiddle.net/wWmqr/1/
Related
I am facing an issue after using infinite scroll. the scroll works fine but when the next page is loaded with ajax.. My all javascript related functions stops working. My code is below
<script type="text/javascript">
function ScrollExecute() {
if($(document).height() - 800 < ($(document).scrollTop() + $(window).height())) {
scrollNode = $('#more').last();
scrollURL = $('#more p a').last().attr("href");
h = $("#count").val();
if(h>2){
scrollURL = scrollURL.replace("page=2", "page="+h);
//alert(scrollURL);
}
// alert(scrollURL);
if(scrollNode.length > 0 && scrollNode.css('display') != 'none') {
$.ajax({
type: 'GET',
url: scrollURL,
context: document.body,
beforeSend: function() {
scrollNode.clone().empty().insertAfter(scrollNode).append('<center>Loading products.....</center>');
scrollNode.hide();
},
success: function(data) {
scrollNode.next().remove();
//$(data).find("script").each(function(i) {
//eval($(this).text());
// alert($(this).text());
//});
var filteredData = $(data).find(".product");
filteredData.insertBefore($("#product-list-foot"));
$("#more").show();
u = parseInt($("#count").val())+parseInt(1);
$("#count").val(u);
},
dataType: "html"
});
}
}
}
$(document).ready(function (e) {
$(window).scroll(function(){
//$.JQUERY.doTimeout( 'scroll', 200, ScrollExecute);
ScrollExecute();
});
e.preventDefault();
});
</script>
here is the link: https://sspeyewear.com/collections/infinite-products..
Any guess let me know plz
On first page
Ajax loaded product is look like this
I'm trying to include this snippet of code:
;(function($) {
'use strict'
var ajaxContactForm = function() {
// http://www.bitrepository.com/a-simple-ajax-contact-form-with-php-validation.html
$('.contact-form').each(function() {
var $this = $(this);
$this.submit(function() {
var str = $this.serialize();
$.ajax({
type: "POST",
url: $this.attr('action'),
data: str,
success: function(msg) {
// Message Sent? Show the 'Thank You' message and hide the form
var result;
if(msg == 'OK') {
result = '<div class="notification_ok">Thank you! Your message has been sent!</div>';
} else {
result = msg;
}
result = '<div class="result">' + result + '</div>';
$this.find('.note').html(result);
}
});
return false;
}); // submit
}); // each contactform
}; // contact
// Dom Ready
$(function() {
ajaxContactForm();
// Initialize responsive menu
ResponsiveMenu.initial($(window).width());
$(window).resize(function() {
ResponsiveMenu.menuWidthDetect($(this).width());
});
// Detect elements into viewport
$('[data-waypoint-active="yes"]').waypoint(function() {
$(this).trigger('on-appear');
}, { offset: '90%' });
$(window).on('load', function() {
setTimeout(function() {
$.waypoints('refresh');
}, 100);
});
});
})(jQuery);
Into this file:
http://rocketgram.co/js/custom.js
However whenever I try and merge the two correctly (Or what I thought) I can only get one or the other working at once. Not both. Can anyone share any light on why these are conflicting?
Here's a few reference links on both of them working, singularly:
rocketgram.co/mainjs.html
rocketgram.co/customjs.html
And here's the file in the snipped above:
rocketgram.co/js/main.js
I try to load a php file by ajax.
This works fine by this code:
<body id="top">
<div id="loadajaxhere"></div>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("loadajaxhere").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "myfile.php", true);
xmlhttp.send();
</script>
But in my php file are jquery plugins, which dont work after loading via ajax...
Maybe the solution is to using the ajax by jquery syntax. Is it right?
I tried it, but my Ajax didn't load the php...
It should load the php automaticlly by loading the page in a defined div.
Many thanks in advance!
use Jquery ajax in stead. for example:
$.ajax({
url: 'myfile.php',
type: 'GET',
data: {'submit':'true'}, // An object with the key 'submit' and value'true';
success: function (result) {
document.getElementById("loadajaxhere").innerHTML = result;
}
});
A small part a solved
a small script in myfile.php works now:
<script type="text/javascript">
//$('.triggermore').click(function(){ //<- This is the old line
$('body').on('click', '.triggermore', function(event){ //<- This is the new one
$(".weitere").slideDown();
$(".weitere").addClass("open");
$(".triggermore").addClass("bye");
$('html, body').animate({ scrollTop: $("#weitere").offset().top }, 1000);
});
</script>
Source of this solution: JQuery effect doesnt work for ajax content
But this huge script is stil not working:
<script type="text/javascript">
$(document).ready(function() {
//http://webdesign.tutsplus.com/tutorials/javascript-tutorials/create-a-sticky-navigation-header-using-jquery-waypoints/
var nav_container = $(".menu");
var nav = $("nav");
var top_spacing = 0;
var waypoint_offset = '40%';
var first_section = '0%';
nav_container.waypoint({
handler: function(event, direction) {
if (direction == 'down') {
nav_container.addClass("sticky")
.stop()
.css("top", -nav.outerHeight())
.animate({"top" : top_spacing});
} else {
var inputPos = $( 'input:first' ).position();
nav_container.stop().removeClass("sticky").css("top",first_section).animate({"top":first_section});
}
},
offset: function() {
return -nav.outerHeight()-waypoint_offset;
}
});
var sections = $("section");
var navigation_links = $(".menu li a");
var links = $("nav a");
sections.waypoint({
handler: function(event, direction) {
var active_section;
active_section = $(this);
if (direction === "up") active_section = active_section.prev();
var active_link = $('.menu li a[href="#' + active_section.attr("class") + '"]');
navigation_links.removeClass("selected");
if(active_section.attr("class") != "top") {
active_link.addClass("selected");
}
},
offset: waypoint_offset
})
links.click( function(event) {
$.scrollTo(
$(this).attr("href"),
{
duration: 1500,
offset: { 'left':0, 'top':0 }
}
);
});
});
</script>
**The Jquery Scripts are in my index.php not in myfile.php.
only the html markup an in the myfile.php
Okay, I found an answer by myself.
Im using this:
$.ajax({
url: 'myfile.php',
type: 'GET',
data: {'submit':'true'}, // An object with the key 'submit' and value'true';
success: function (result) {
document.getElementById("loadajaxhere").innerHTML = result;
}
});
And pasting my scripts in the succes function. But not everything is working.
I'm on it.
<script>
$.ajax({
url: "myfile.php",
success: function(result){
$("#loadajaxhere").html(result);
}
});
</script>
I have 2 javascripts that are conflicting with eachother, the newer one (Zeroclipboard) conflicts with the older one (delete row) and won't let the delete row one work. The moment i removed the zeroclipboard one, delete worked.
Tried adding jQuery.noConflict(); but didn't seem to work. By reading few solutions, I decided to remove $ signs, but still no.
I have a files.php file, including the header.php file. I am adding the custom.js file in header.php, which holds many functions for operations across the project, including the delete row function. Whereas, the newer script for ZerClipboard is in files.php itself.
Older one, to delete a table row on delete icon click, which won't work after I add the next:
custom.js
function deleteRow()
{
var current = window.event.srcElement;
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete?"))
{
var fid = $(this).parent().parent().attr('fid');
var str=$(this).attr('rel');
var data = 'fid=' + $(this).attr('rel') + '&uid=' + $(this).parent().attr('rel');
var deletethis = '#tr' + $(this).attr('rel');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "delete.php",
data: data,
cache: false,
success: function(msg)
{
$(deletethis).fadeOut('slow', function() {$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
ZeroClipboard's JS and SWF, along with this js to copy some text on clipboard on Share icon click:
files.php
<script type="text/javascript" src="js/ZeroClipboard.js"></script>
<script language="JavaScript">
var clip = null;
function $(id) { return document.getElementById(id); }
function init()
{
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
}
function move_swf(ee)
{
copything = document.getElementById(ee.id+"_text").value;
clip.setText(copything);
if (clip.div)
{
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id); }
else{ clip.glue(ee.id); }
clip.receiveEvent('mouseover', null);
}
</script>
I used this blog post for implementing multiple zerclipboard - http://blog.aajit.com/easy-multiple-copy-to-clipboard-by-zeroclipboard/
And, here's the HTML source generated by the files.php page - http://jpst.it/tlGU
Remove the follow function definition of your second script:
function $(id) { return document.getElementById(id); }
Because this is redefining your $ object in window context, due when you use $ in your first script you're not using jquery, instead you're using your new function definition.
Hope this helps,
Here is how you should use noConflict() :
function deleteRow()
{
var current = window.event.srcElement;
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
jQuery.noConflict(); // Reinitiating $ to its previous state
jQuery(document).ready(function($) // "Protected" jQuery code : $ is referencing jQuery inside this function, but not necessarily outside
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete?"))
{
var fid = $(this).parent().parent().attr('fid');
var str=$(this).attr('rel');
var data = 'fid=' + $(this).attr('rel') + '&uid=' + $(this).parent().attr('rel');
var deletethis = '#tr' + $(this).attr('rel');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "delete.php",
data: data,
cache: false,
success: function(msg)
{
$(deletethis).fadeOut('slow', function() {$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
And in files.php:
<script src="js/ZeroClipboard.js"></script>
<script>
var clip = null;
function $(id) {
return document.getElementById(id);
}
function init() {
clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
}
function move_swf(ee) {
copything = document.getElementById(ee.id + "_text").value;
clip.setText(copything);
if (clip.div) {
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id);
} else {
clip.glue(ee.id);
}
clip.receiveEvent('mouseover', null);
}
</script>
This code read the pms, that is stored inside a php file and print them on the screen every 0.01 second to be in realtime or work dynamic, but i'm using a "CSS Emoticons plugin", it works and show the emoticons, but i can't use the animate one or i can, but it would not finish, it would restart every 0.01 second unless i turn it off. I want to use it with the dynamic text, but i dont know how. Please help me out guys
function updateStats(stat) {
var stat = ["MSG", "NAME"];
var url = "POST.php";
$.each(stat, function (i, key) {
$.post(url, {
stats: key
}, function (data) {
$("#" + key).html(data);
$('div.icon').emoticonize({
//delay: 800,
//animate: false
});
});
});
}
setInterval(function () {
updateStats("updateStats");
}, 10);
Try with this...
var to;
function updateStats(stat) {
var stat = ["MSG", "NAME"];
var url = "POST.php";
clearTimeout(to);
$.each(stat, function (i, key) {
$.post(url, {
stats: key
}, function (data) {
$("#" + key).html(data);
$('div.icon').emoticonize({
//delay: 800,
//animate: false
});
to = setInterval(function () {
updateStats("updateStats");
}, 10);
});
});
}
to = setInterval(function () {
updateStats("updateStats");
}, 10);