Add more items from database when scroll - javascript

I have a problem, I can not run this script, the problem is that I use mcustomscrollbar
and so I did not read the Scroll event;
the scroll event is not executed.
<script type="text/javascript">
var page = 1;
$("#my_div").scroll(function () {
$('#more').hide();
$('#no-more').hide();
if($("#my_div").scrollTop() + $("#my_div").height() > $("#my_div").height() - 200) {
$('#more').css("top","400");
$('#more').show();
}
if($("#my_div").scrollTop() + $("#my_div").height() == $("#my_div").height()) {
$('#more').hide();
$('#no-more').hide();
page++;
var data = {
page_num: page
};
var actual_count = "<?php echo $actual_row_count; ?>";
if((page-1)* 12 > actual_count){
$('#no-more').css("top","400");
$('#no-more').show();
}else{
$.ajax({
type: "POST",
url: "../data.php",
data:data,
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
}
}
});
</script>
How can I adapt this script to this plugin,
mcustomscrollbar http://manos.malihu.gr/jquery-custom-content-scroller/
The event
$(document).on('scroll',"#my_div",function () {
is not recognized on this plugin mcustomscrollbar manos.malihu.gr/jquery-custom-content-scroller. Help me please!

Maybe because you aren't waiting for DOM ready. Try this:
<script type="text/javascript">
var page = 1;
$(function () { //DOM ready handler
$(document).on('scroll',"#my_div",function () {
//all your code here
});
});
</script>

Related

Javascript functions stops working on loaded html with ajax in shopify infinite scroll on collection page

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

Previous divs with jQuery does not work after Ajax call

I have two scripts:
The first one is image carousel. It uses jQuery slick slider.
The second one is an Ajax script that loads contents as page scrolls down.
Here is my code:
function slider () {
var $arrows = $('.arrows');
var $next = $arrows.children(".slick-next");
var $prev = $arrows.children(".slick-prev");
var slick = $('.your-class').slick({
appendArrows: $arrows
});
$('.slick-next').on('click', function (e) {
var i = $next.index( this )
slick.eq(i).slickNext();
});
$('.slick-prev').on('click', function (e) {
var i = $prev.index( this )
slick.eq(i).slickPrev();
});
}
$(document).ajaxComplete(slider);
Below is the scroll content load with Ajax:
$(document).ready(function(){
function slider () {
var $arrows = $('.arrows');
var $next = $arrows.children(".slick-next");
var $prev = $arrows.children(".slick-prev");
var slick = $('.your-class').slick({
appendArrows: $arrows
});
$('.slick-next').on('click', function (e) {
var i = $next.index( this )
slick.eq(i).slickNext();
});
$('.slick-prev').on('click', function (e) {
var i = $prev.index( this )
slick.eq(i).slickPrev();
});
}
$(document).ajaxComplete(slider);
var flag = 0;
$.ajax({
type: "GET",
url: "getdata.php",
data: {
'offset': 0,
'limit': 10
},
success: function(data){
$('.rowmasonry').append(data);
flag += 10;
},
});
$(window).scroll(function(){
if($(window).scrollTop() >= $(document).height() - $(window).height()-500){
$.ajax({
type: "GET",
url: "getdata.php",
data: {
'offset': flag,
'limit': 10
},
success: function(data){
$('.rowmasonry').append(data);
flag += 10;
},
});
}
});
});
The problem is that the first 10 contents that are loaded work properly. However, as I scroll down, and another 10 contents come, the first 10 contents that were loaded do not respond.
How do I bind the image slider to Ajax, so that all contents on the page work with jQuery?
Thanks for your help.
You are just appending new elements to DOM. In order to update slick you need to reInit slick carousel or if you are sure about the slide markup then you can use slickAdd method provided by plugin.
$.ajax().done(function(data){
$('.your-class').slick('slickAdd', data);
});
ref: http://kenwheeler.github.io/slick/

Jquery doesn't work after loading a PHP by ajax

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>

Initialize Anonymous function after ajax call

Hi I have a template where the scripts are initialized in this file like this
;(function ($) {
"use strict";
var $body = $('body');
var $head = $('head');
var $header = $('#header');
var transitionSpeed = 300;
var pageLoaded = setTimeout(addClassWhenLoaded, 1000);
var marker = 'img/marker.png';
The problem is i have tried to name the function and call it in my ajax code, with no luck
here is my ajax code, how can i initialize again so tabs and bootstrap progress bar work again. in the loaded code?
$(document).ready(function(){
var form = $('#prevjob_form');
var submit = $('#prevjob_submit');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: '<?php echo $this->make_url("user/prevjobs/"); ?>',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Añadiendo...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data);
$('.prevjobs').empty().append(item);
//ready();
// progress();
//I try to name it progress and call it here, but this wont work
var objDiv = document.getElementById("prevjobs");
objDiv.scrollTop = objDiv.scrollHeight;
// reset form and button
form.trigger('reset');
submit.val('Añadir Gol').removeAttr('disabled');
},
error: function(e){
console.log(e);
}
});
});
});
I try to wrap the progress bar code just to test, and name a function.
like this
<script>
function progress(){
$('.progress-bar').each(function () {
var $this = $(this),
progress = $this.data('progress');
if (!$this.hasClass('no-animation')) {
$this.one('inview', function () {
$this.children('.progress-bar-inner').children('span').css('width', progress + '%');
});
} else {
$this.children('.progress-bar-inner').children('span').css('width', progress + '%');
}
if ($this.hasClass('toggle')) {
$this.children('.progress-bar-toggle').on('click', function (event) {
event.preventDefault();
if (!$this.hasClass('active')) {
$this.children('.progress-bar-content').slideDown(250, function () {
$this.addClass('active');
});
} else {
$this.children('.progress-bar-content').slideUp(250, function () {
$this.removeClass('active');
});
}
});
}
});
}
</script>
But again after the Ajax call progress bar are not working.
Your issue is that your function and the call to it are in different scopes.
When you define a function or a variable inside an on load function like this $(document).ready(function(){ .... or like this ;(function ($) {... you can only access those function or variables from within the scope of that closure.
Here is an example:
$(document).ready(function(){
function myFunction(msg){
console.log(msg);
}
myFunction('this will work')
});
$(document).ready(function(){
myFunction('but this never will');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You'll need to move the function to the global scope or move the call to it to the same scope as the function itself
Another solution would be to access the function through the document object like this:
;(function ($) {
$.fn.myFunction = function (msg) {
console.log(msg);
}
})(jQuery);
$(document).ready(function(){
$(document).myFunction('called from outside the original scope');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Append more content when scroll to end of page

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/

Categories

Resources