I'm coding a wordpress theme and I want to increment a load more button.
I'm not using wordpress always and this is the first time I've this problem with a javascript variable. The variable pull_page in fact will not increment and every time the script will run it will fetch only two pages. Is there any error in the code, and how I can fix it?
$('#load-more').on('click', function(e){
e.preventDefault();
var pull_page = 1;
var jsonFlag = true;
if(jsonFlag){
pull_page++;
$.getJSON("/beta/wp-json/portfolio/all-posts?page=" + pull_page, function(data){
if(data.length){
$.each(data, function(i, item){
var html = '<div class="card">';
html += '<a href="'+ item.permalink +'">';
html += '<img class="card-img-top w-100" src="'+ item.featured_img_src +'" id="case-studies" />';
html += '<div class="overlay"><h4 class="text-center" id="client-name">'+ item.title +'</h4></div>';
html += '</a>';
html += '</div>';
$('body').find('.card-columns')
.append(html);
});
}
else{
jsonFlag = false;
}
}).done(function(data){
if(data.length >= 4){
jsonFlag = true;
}
else{
jsonFlag = false;
}
});
}
}); // end load more
You're resetting pull_page to 1 each and every time the load more button is clicked.
Move it outside.
var pull_page = 1;
$('#load-more').on('click', function(e) {
...
Related
BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, page);
Im using JSON and passing data through the href tag and using a click event to show specific items from a product database. My question is that I have code in the script that assigns a unique window hash to each product. It takes the product name and strips the spaces.
How can I show the correct item on the page if the hash tag matches the item when linking from an external url?
For example, when one of the items is clicked on the page the url will show something like www.website.com#CherryTomatoes.
Obviously I cant link to this from another website because the hash only exists when the click event is fired. I want to be able to automatically show the correct item when using an external link. Below is my code hope someone can help me out with this!
//display product category based on click
$("#displayall").click(function(event){
displayAll();
});
//display all products function
function displayAll() {
var categoryImage = '';
$.each(json, function (i, item) {
categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '' + '</div>';
});
$('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
//show individual product function on click
$(".showProduct").click(function(event){
//hide all current products
$('#productCategories').hide();
//get passed data from other function
var clickedItemName = '<h1>' + $(this).data('itemname') + '</h1>';
var clickedItemUPC = $(this).data('itemupc');
var clickedItemOZ = '<h2>' + $(this).data('itemoz') + '</h2>';
var clickedItemDescription = '<p>' + $(this).data('itemdescription') + '</p>';
var clickedItemImage = '<img class="img-responsive img-rounded center-block" src="' + $(this).data('itemimage') + '">';
var clickedItemGluten = $(this).data('itemgluten');
var clickedItemBPA = $(this).data('itembpa');
var clickedItemGMO = $(this).data('itemgmo');
var clickedItemPageURL = $(this).data('itempageurl');
//check if clicked data equals correct item
$.each(json, function (i, item) {
if (item.itemName === clickedItemName) {
clickedItemName
}
if (item.itemFullUPC === clickedItemUPC) {
clickedItemUPC
}
if (item.itemPackSize === clickedItemOZ) {
clickedItemOZ
}
if (item.itemDescription === clickedItemDescription) {
clickedItemDescription
}
if (item.imageURL === clickedItemImage) {
clickedItemImage
}
if (item.itemGlutenFree === clickedItemGluten) {
clickedItemGluten
}
if (item.itemBPAFree === clickedItemBPA) {
clickedItemBPA
}
if (item.itemGMOFree === clickedItemGMO) {
clickedItemGMO
}
//assign window hash to each product
if (item.itemName === clickedItemPageURL) {
event.preventDefault();
clickedItemPageURL = clickedItemPageURL.replace(/\s/g, '');
window.location.hash = clickedItemPageURL;
}
});
//remove extra characters from UPC
var originalUPC = clickedItemUPC;
var strippedUPC = '<h2>' + originalUPC.slice(1, -1); + '</h2>';
//show individual product information
$('#productSocialShare').show();
$('#individualProduct').show();
$('#relatedProducts').show();
//append product information to appropriate DIV
$('#productTitle').html(clickedItemName);
$('#productUPC').html(strippedUPC);
$('#productOZ').html(clickedItemOZ);
$('#productDescription').html(clickedItemDescription);
$('#productImage').html(clickedItemImage);
//check if gluten free is true and show image
if (clickedItemGluten == "Y") {
clickedItemGluten = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gluten_free_test.jpg">';
$('#productGlutenFree').html(clickedItemGluten);
$('#productGlutenFree').show();
} else {
$('#productGlutenFree').hide();
}
//check if bpa free is true and show image
if (clickedItemBPA == "Y") {
clickedItemBPA = '<img class="img-responsive img-rounded img-margin" src="../images/misc/bpa_free_test.jpg">';
$('#productBPAFree').html(clickedItemBPA);
$('#productBPAFree').show();
} else {
$('#productBPAFree').hide();
}
//check if gmo free is true and show image
if (clickedItemGMO == "Y") {
clickedItemGMO = '<img class="img-responsive img-rounded img-margin" src="../images/misc/gmo_test.jpg">';
$('#productGMOFree').html(clickedItemGMO);
$('#productGMOFree').show();
} else {
$('#productGMOFree').hide();
}
});
closeNav();
}
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
{
console.log(index + " first item");
html = "<div class='item active'>";
} else {
console.log(index + " its not 0");
html = "<div class='item'>"
}
console.log(json.length); // this will show the info it in firebug console
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
I need to generate 5 of these but the first one needs to be have 'item active'
If there is a better way, please let me know
Thank you for pointing out that my html was being overwritten. I updated my code but jQuery isn't actually placing my HTML into the body. so thats another question
You can add an index into the $.each method; this will span from 0 to data.length - 1
$.getJSON("./data/data.json", function(json) {
$.each(json, function(index, data) {
var html = "";
html += '<div class="item' + (index == 0 ? ' active' : '') + '">';
html += '<blockquote>...</blockquote>';
html += '</div>';
$('body').append(html);
});
});
<script>
var index = 0;
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = "";
if(index == 0)
html = "<div class='item active'>";
else
html = "<div class='item'>";
html += "<blockquote><div class='row'><div class='col-sm-3 text-center'><img class='img-circle' src='images/obama.jpg' style='width: 100px;height:100px;'></div><div class='col-sm-9'><p>Change will not come if we wait for some other person or some other time. We are the ones we've been waiting for. We are the change that we seek.</p><small>President Barack Obama</small></div></div></blockquote></div>";
$('body').append(html);
index++;
});
});
</script>
New on here and a beginner at code. I have this code I am using as a Karaoke search. However, the JSON contains about 40 000 lines of info, and the search is set up to tigger on keyup, so it is very laggy sometimes. I'm hoping someone can help me alter this code so that it only searches when a submit button is pressed... Any ideas? Greatly Appreciated
$(window).load(function(){
$('#search').keyup(function(){
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
var count = 1;
$.getJSON('data.json', function(data) {
$.each(data, function(key, val){
if ((val.name.search(regex) != -1) || (val.location.search(regex) != -1)) {
//output += '<div class="col-md-6 well">';
//output += '<div class="col-md-7">';
output += '' + val.name + ' - ';
output += '' + val.location + '';
output += '</div>';
output += '</div>';
output += '<div class="col-md-7"><img class="img-responsive" src="send.png" /></div>';
if(count%2 == 0){
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#results').html(output);
});
});
});
Assuming you placed your submit button within a form, give your form an ID.
<form id="search-form">
Change line
$('#search').keyup(function(){
to
$('#search-form').on('submit', function (e) {
e.preventDefault();
The search logic should not be implemented on the client side. It would be painful for the browser to do that kind of iteration. Transfer your search logic in the backend. : )
if you're going to fixed that on front end, please add timeout/debounce during keyup
var delay = null;
$( el ).keyup( function () {
if ( delay ) clearTimeout( delay );
var delay = setTimeout( function () {
// your search logic
} );
} );
This the page I'm working on:
http://gacc.nifc.gov/gbcc/predictive/PSA_ERCmap/Dev/PSAERCmap1.html
When you click on a shaded area the chart associated with the area pops up. What I'm trying to figure out is how to get the "Next PSA" link at the bottom to advance the chart in the popup to the next PSA every time you click it. I've figured out how to get it to advance by one PSA, but can't get it past that one. You'll see if you click on the link.
I have a function (called replace) that replaces the image source for the chart with a link to the next PSA number up. However, I can't figure out how to get it to increment. I tried PSA++ and PSA=PSA1 but neither of them work.
Here's my code:
<title>DEV PSA ERC Map DEV</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function overlay(a) {
PSA = a.id;
var numeric = a.id.replace('GB', '');
PSAnum = Number(numeric)
PSA1 = PSAnum + 1;
nextPSA = ('0' + PSA1).slice(-2);
var overlayContent = '';
overlayContent += '<div id="overlay">';
overlayContent += '<div>';
var imgsrce = '';
imgsrce += 'Charts/WebCharts/GB';
imgsrce += numeric;
imgsrce += '/ERCGraph.PNG';
overlayContent += '<img id="chartimage" src="';
overlayContent += imgsrce;
overlayContent += '" />';
overlayContent += '<br /><b><h1> Close</b></h1>';
overlayContent += '<b><h1> Next PSA</b></h1>';
overlayContent += '</div>';
overlayContent += '</div>';
$("#overlay").replaceWith(overlayContent);
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
if (el.style.visibility == "visible") {
//el.style.visibility="hidden";
}
} //end of overlay function
function replace(a) {
image = document.getElementById('chartimage');
console.log(image.src);
console.log(PSA);
image.src = 'Charts/WebCharts/GB';
image.src += nextPSA;
image.src += '/ERCGraph.PNG';
PSA++;
console.log(PSA);
} //end of replace function
$('.overlay-bg').click(function() {
closePopup();
});
function closePopup() {
el = document.getElementById("overlay");
el.style.visibility = "hidden";
}
$(function() {
$.get("getDate.php", function(data) {
document.getElementById("timestamp").innerHTML = "<b>RAWS observations updated on " + data + "</b>";
});
});
var file;
file = 'GB_PSAdata_Real.js';
$.getJSON(file, function(events) {
var gbname = Object.keys(events);
var divContent = '';
divContent += '<div id="map">';
divContent += '<map name="mapmap">';
for (i = 0; i < gbname.length; i++) {
var PSA = (gbname[i]);
JSONcoords = events[PSA][0].Coords;
JSONcoordString = JSONcoords.toString();
divContent += '<area id="' + PSA + '" href="#" shape="poly" coords="';
divContent += JSONcoordString;
divContent += '" onclick="overlay(this)">';
// console.log(divContent)
}
divContent += '</map>';
divContent += '<img src="GetPSAavg.php" width="826" height="1005" usemap="#mapmap" />';
divContent += '</div>';
$("#map").replaceWith(divContent);
//$("#overlay").replaceWith(overlayContent);
;
})
</script>
</head>
<div id="overlay">
</div>
<body>
<div id="header">
<img src="PSlogo.png" style="height:75px">
<img src="GBlogo.png" style="height:75px">
<span><b>Great Basin ERC Percentiles</b> *Experimental*</span>
</div>
<div id="main">
<div id="map"></div>
<div id="timestamp">RAWS Observations Updated</div>
<div id="legend">
<img src="LegendFull2.png" id="legendIMG">
</div>
</div>
</body>
</html>
You need to move the code that increments the number into the replace() function, so it gets executed each time replace() is called. Currently it is executed only once when the overlay() function is called.
First, explicitly declare a global variable (outside of any function):
var currentPSANum = null;
Place this line inside the overlay() function:
currentPSANum = Number(a.id.replace('GB',''));
Then use the following for the replace() function:
function replace(a) {
currentPSANum++;
var image = document.getElementById('chartimage');
image.src = 'Charts/WebCharts/GB' + ('0' + currentPSANum).slice(-2) + '/ERCGraph.PNG';
}