Previous divs with jQuery does not work after Ajax call - javascript

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/

Related

keep the scroll to bottom with appending text to it

I have created a chatbox which scrolls to bottom at first and the scroll bar remain their until user scrolls up.But a new text is inserted instead of scroll bar moving to downward it remain at the same position.
<script>
var currentID = null;
var chatTimer = null;
var scrolled=false;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
if(!scrolled){
$("#messages").animate({ scrollTop: $(document).height() }, "fast");
}
}
});
}
$(document).ready(function() {
$("#messages").on('scroll',function(){
scrolled=true;
});
fetch_data();
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
//clearTimeout(chatTimer);
fetch_chat();
});
function scrollToBottom() {
$("#messages").scrollTop(1e10); // Lazy hack
}
setInterval(function() {
fetch_chat();
}, 500);
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
scrollToBottom();
});
// alert(text);
});
//this will also trigger the first fetch_chat once it completes
});
</script>
I just want to keep that scroll at the bottom even after user enter a new text.
the scroll should always remain at bottom but should be scrollable when user wish to do so.
First read the height of current chat box using jQuery like this,
var scrollToheight = $("#message").height();
And then use this height to scrollTop jQuery function :
$("#message").scrollTop(scrollToheight);
This should work for you always.

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

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>

Add empty image tag with jQuery

I have a menu with sub menus and there is a + and _ image for about and close sub menus.
The problem that the menu that not have sub its align is different than other and to fix that must add image to the li that have no image close and open to fix the align here a screenshot for what I mean
This mean is create demoniacally with js here the code I can't fix it with css because it will effect the whole menu here the code
$(function () {
//this function to get , show and hide sub menu from this menu by use menu Id
$('.daymanicPageMenu').delegate('img', 'click', function () {
var checkSubMenuFound = $(this).parent().children(".daymanicPageSubMenu").length;
if (checkSubMenuFound != 0) {
//remove this div show fast
$(this).parent().children(".daymanicPageSubMenu").slideUp("fast", function () {
$(this).parent().children("img").attr('src', 'http://localhost:53188/Content/Images/CollectionImages/image.png');
$(this).remove();
});
} else {
$(this).parent().append("<div class='daymanicPageSubMenu'></div>");
var subMenuDiv = $(this).parent().children(".daymanicPageSubMenu");
//get menu Id to get sub menu by Ajax
var menuId = $(this).data('stuff');
// ajax request
$.ajax({
url: "GetSubMenu",
data: { menuId: menuId },
type: 'POST',
async: false,
success: function (data) {
subMenuDiv.append(data);
}
});
//show this div fast
subMenuDiv.hide().slideDown("fast", function () {
$(this).parent().children("img").attr('src', 'http://localhost:53188/Content/Images/CollectionImages/image2.png');
});
}
});
//List Indexing function
$('.listIndexing').delegate('label', 'click', function () {
var currentpage = $('.liIndexing').html();
var parent = $(this).parent();
var parentParent = parent.parent();
var removeClassLabel = parentParent.find('li[name=' + currentpage + ']');
removeClassLabel.children('label').removeClass("liIndexing");
if ($(this).html() == "Next") {
currentpage++;
var pagecount = $(this).attr('name');
}
else if ($(this).html() == "Prev") {
currentpage--;
} else {
currentpage = $(this).data('stuff');
}
if (currentpage < 1) { currentpage = 1; }
if (currentpage > pagecount) { currentpage = pagecount; }
//get list Id to get List News by Ajax
var newListdiv = $("#newsPage");
// ajax request
$.ajax({
url: "News",
data: { listId: currentpage },
type: 'POST',
async: false,
success: function (data) {
newListdiv.empty().append(data);
}
});
var addClassLabel = parentParent.find('li[name=' + currentpage + ']');
addClassLabel.children('label').addClass("liIndexing");
});
$("#newsPageListIndex li:eq( 1 )").children("label").addClass("liIndexing");
var tn1 = $('.mygallery').tn3({
skinDir:"skins",
imageClick:"fullscreen",
image:{
maxZoom:1.5,
crop:true,
clickEvent:"dblclick",
transitions:[{
type:"blinds"
},{
type:"grid"
},{
type:"grid",
duration:460,
easing:"easeInQuad",
gridX:1,
gridY:8,
// flat, diagonal, circle, random
sort:"random",
sortReverse:false,
diagonalStart:"bl",
// fade, scale
method:"scale",
partDuration:360,
partEasing:"easeOutSine",
partDirection:"left"
}]
}
});
});
to fix the align I must add image to the li
You, you don't need to. Use CSS for aligning them properly. Also, for a nested list menu you should actually nest list elements.

Add more items from database when scroll

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>

Categories

Resources