Guys I have a script that shows blogger articles, only the images of the articles are of poor quality.
Looking at the script the only part that refers to the image is this
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
css code:
.itemposts img {
float:left;
height:90px;
width:200px;
margin:2px 10px 2px 0px;
-webkit-box-shadow:none;
-moz-box-shadow:none;
box-shadow:none;
background-color:#fafafa;
border:1px solid #dcdcdc;
padding:4px;
}
Does anyone know which part of the code needs to be changed to show the image with the original quality?
added full code full code
<script>
var showPostDate = true,
showComments = true,
idMode = true,
sortByLabel = false,
labelSorter = "Games",
loadingText = "Loading...",
totalPostLabel = "Jumlah posting:",
jumpPageLabel = "Halaman",
commentsLabel = "Komentar",
rmoreText = "Selengkapnya ►",
prevText = "Sebelumnya",
nextText = "Berikutnya",
siteUrl = "https://elfenliedbrazil.blogspot.com/",
postPerPage = 6,
numChars = 370,
imgBlank = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC";
</script>
<script type='text/javascript'>
//<![CDATA[
// -----------------------------------------------------------------------------------------
//
// Original:
// Modified by Taufik Nurrohman
//
// -----------------------------------------------------------------------------------------
var minpage = 6; // Minimum number to display the page
var maxpage = 10; // The maximum number of pages to display
var firstpage = 0; // Detect the first time it is executed
var pagernum = 0; // Contain the page number where we
var postsnum = 0; // Start the first page
var actualpage = 1; // Starting value of the current page (it will change if you click the pagination).
// This is the container template that will be used to insert the posts template, pagination and the posts count
document.write('<div id="toc-outer"><div id="results"></div><div id="itempager" style="position:relative;"><div id="pagination"></div><div id="totalposts"></div><a title="Taufik Nurrohman" style="display:block!important;visibility:visible!important;opacity:1!important;position:absolute;bottom:10px;right:14px;font:normal bold 8px Arial,Sans-Serif!important;color:#666;text-shadow:0 1px 0 rgba(255,255,255,.1);text-decoration:none;" href="http://hompimpaalaihumgambreng.blogspot.com/2012/03/daftar-isi-blogger-dengan-navigasi.html" target="_blank">►TN</a></div></div>');
var _results = document.getElementById('results');
var _pagination = document.getElementById('pagination');
var _totalposts = document.getElementById('totalposts');
// Build the table of contents framework
function showPagePosts(json) {
var entry, posttitle, posturl, postimg, postsumm, replies, monthnames, timepub, output = "";
if (pagernum === 0) {
postsnum = parseInt(json.feed.openSearch$totalResults.$t);
pagernum = parseInt(postsnum / postPerPage) + 1;
}
for (var i = 0; i < postPerPage; i++) {
if ("entry" in json.feed) {
if (i == json.feed.entry.length) break;
entry = json.feed.entry[i];
posttitle = entry.title.$t; // Get the post title
// Get rel="alternate" for truly post url
for (var k = 0, elen = entry.link.length; k < elen; k++) {
if (entry.link[k].rel == "alternate") {
posturl = entry.link[k].href; // This is your real post URL!
break;
}
}
// Get the comments count
for (var l = 0, clen = entry.link.length; l < clen; l++) {
if (entry.link[l].rel == "replies" && entry.link[l].type == "text/html") {
var commentsnum = entry.link[l].title.split(" ")[0]; // This is your comments count
break;
}
}
// If the Blogger-feed is set to SHORT, then the content is in the summary-field
postsumm = ("summary" in entry) ? entry.summary.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : ""; // Get the post summary
// Reduce post summaries to "numChars" characters.
// "numChars" is a variable. You determine the value
if (postsumm.length > numChars) {
postsumm = (numChars > 0 && numChars !== false) ? postsumm.substring(0, numChars) + '...' : "";
}
// Get the post date (e.g: 2012-02-07T12:56:00.000+07:00)
var _postdate = entry.published.$t,
_cdyear = _postdate.substring(0, 4), // Take 4 characters from the "postdate" beginning, it means the year (2012)
_cdmonth = _postdate.substring(5, 7), // Take 2 character 5 step from "postdate" beginning, it mean the month (02)
_cdday = _postdate.substring(8, 10); // Take 2 character 8 step from "postdate" beginning. it means the day (07)
// Month array template
monthnames = (idMode) ? ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"] : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The final product of the post date = (07 Feb 2012) (cdday monthnames cdyear)
timepub = (showPostDate) ? _cdday + ' ' + monthnames[parseInt(_cdmonth, 10) - 1] + ' ' + _cdyear + ' - ' : '';
// The final product of the comments count & comments label (10 Komentar) (commentsnum commentsLabel)
replies = (showComments) ? commentsnum + ' ' + commentsLabel : '';
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
}
}
// Put the whole template above into <div id="results"></div>
_results.innerHTML = output;
_create_pagination();
}
// Build the pagination
function _create_pagination() {
output = "";
var starter = 0;
output += ((actualpage > 1) ? '<a title="' + prevText + '" class="prevjson" href="javascript:_init_script(' + (actualpage - 1) + ')">' + prevText + '</a>' : '<span class="prevjson hidden">' + prevText + '</span>') + '<em style="font:inherit;color:inherit;" class="pagernumber">';
if (pagernum < (maxpage + 1)) {
for (starter = 1; starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
} else if (pagernum > (maxpage - 1)) {
if (actualpage < minpage) {
for (starter = 1; starter < (maxpage - 2); starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else if (pagernum - (minpage - 1) > actualpage && actualpage > (minpage - 1)) {
output += '1';
output += '2';
output += ' ... ';
for (starter = actualpage - 2; starter <= actualpage + 2; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else {
output += '1';
output += '2';
output += ' ... ';
for (starter = pagernum - (minpage + 1); starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
}
}
output += '</em>' + ((actualpage < starter - 1) ? '<a title="' + nextText + '" class="nextjson" href="javascript:_init_script(' + (actualpage + 1) + ')">' + nextText + '</a>' : '<span class="nextjson hidden">' + nextText + '</span>');
_pagination.innerHTML = output;
_totalposts.innerHTML = totalPostLabel + ' ' + postsnum + ' - ' + jumpPageLabel + ' ' + ((actualpage * postPerPage) - (postPerPage - 1)) + ((actualpage < starter - 1) ? ' - ' + (actualpage * postPerPage) : "");
}
// Functions to remove and append the callback script that has been manipulated in the `start-index` parameter
function _init_script(n) {
var parameter = (n * postPerPage) - (postPerPage - 1), old, s,
head = document.getElementsByTagName('head')[0],
url = (sortByLabel) ? siteUrl + '/feeds/posts/summary/-/' + labelSorter + '?start-index=' + parameter : siteUrl + '/feeds/posts/summary?start-index=' + parameter; // Optional: Sort posts by a specific label
if (firstpage == 1) {
// Jump to top
document.documentElement.scrollTop = _results.offsetTop - 30;
document.body.scrollTop = _results.offsetTop - 30;
// Remove the old callback script
old = document.getElementById("TEMPORAL");
old.parentNode.removeChild(old);
}
_results.innerHTML = '<div id="loadingscript">' + loadingText + '</div>';
_pagination.innerHTML = '';
_totalposts.innerHTML = '';
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&max-results=' + postPerPage + '&orderby=published&alt=json-in-script&callback=showPagePosts';
s.id = 'TEMPORAL';
head.appendChild(s);
firstpage = 1;
actualpage = n;
}
// Execute the _init_script() function with parameter as `1` on page load
// So it will show the first page.
window.onload = function() {
_init_script(1);
};
//]]>
</script>
Thumbnails are reduced-size versions of pictures or videos
https://en.wikipedia.org/wiki/Thumbnail
So you need to get the original image
In some cases you have the size in the url, like in this one at the end of url
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs=w720-h110-rw
You can simply remove that part and get the full size of the image
https://lh3.googleusercontent.com/mC69w8Asl2c4y8it_gEb0-2CcwxKWUvz1fs4gOwVfxUkvSN7qAAl41VohsqSdVG-dZs
update
In your case you have a url like this
https://1.bp.blogspot.com/xxxxxxx/s72-c/xxxxx.jpg
you can change to
https://1.bp.blogspot.com/xxxxxxx/s640/xxxxx.jpg
This post explain very well how you can use List of all the App Engine images service get_serving_url() URI options
Related
I've trying to build out a table from a start time until the end of day in defined increments.
eg: if the user selects 15 minute increment starting from 8:10am, the times goes
8:10,8:25,8:40,8:55,9:10...
My current code does not correct work out we've changed to the next hour and then start the offset again, eg i get:
815,830,845,905,935,1025,1125,1225,1325...
Here is a JSFiddle
https://jsfiddle.net/inboxdesign/c8f2dhng/13/
Here is the code I have so far;
// from select:
let $first_hour = 8;
let $first_minute = 10;
let day_count = 1; // don't worry about this;
let duration = 15; // increment
var offset = 0;
var current_time = parseInt($first_hour + $first_minute);
for (var i = 0; i < 120; i++) {
if (current_time < 2400) {
var time_string = ('' + current_time);
var time_minutes = parseInt(time_string.substring(time_string.length - 2));
if (time_minutes < 60) {
// offset = 0;
times += '<tr>';
for (var d = 1; d <= day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_string.substring(time_string.length - 2) + ' offset: ' + offset +'</td>';
}
times += '</tr>';
} else {
offset = (time_minutes - 60);
// times += '<tr>';
// times += '<td>o:' + offset + ' tm: ' + time_minutes + '</td>';
// time_minutes = offset;
// times += '</td>';
}
}
console.log('current_time: ' + current_time);
current_time = parseInt(current_time + duration + offset);
In this line your else offset has to be reset to 0
for (var d = 1; d <= SP.new_conference.day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_minutes + ' offset: ' + offset +'</td>';
}
// times += '</tr>';
} else {
offset = 0;
and then your current time and offset should look like this
current_time = parseInt(current_time + SP.new_conference.duration );
offset+=SP.new_conference.duration
I have fixed this issues in the jsfiddle if you want to have a look
Here is the jsfiddle for my question.
http://jsfiddle.net/jaribhai/wncwqerj/1/
This is the code.
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("summary" in entry[i]) ? (entry[i].summary.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for(var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
This is the demo of random posts widget from blogger. It is showing thumbnails from only those posts where images are linked from blogger but its not showing thumbnails for those images which are linked from external sources.
What can I do so that images from external hosts also appear in the thumbnails.
As the image is hosted externally , it won't be present in the media$thumbnail field of the feed. We will have to parse the HTML content of the post to extract the URL of the image. Two changes need to be done to make this work -
Firstly switch from the summary feed to default feed URL. This is necessary for getting the HTML content of the post (summary feed only contains the limited summary text of the post not the full HTML). Change every instance of
/feeds/posts/summary?alt=json-in-script
to
/feeds/posts/default?alt=json-in-script
Secondly change the condition for finding the image in the post from
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
to
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
Refer to the working example below -
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length,
j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("content" in entry[i]) ? (entry[i].content.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for (var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
/**
* `document[dot]write` is disallowed in JSFiddle envioriment and might break your fiddle.
*/
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
body {
margin: 0;
padding: 50px;
background-color: white;
font: normal normal 11px/1.4 Arial, Sans-Serif;
color: black;
}
#random-post-container {
width: 400px
}
#random-post-container ul,
#random-post-container li {
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
}
#random-post-container img {
display: block;
float: left;
border: 1px solid;
margin: 2px 7px 5px 0;
}
#random-post-container a {
font-weight: bold;
font-size: 110%;
}
#rancom-post-container .clear {
display: block;
clear: both;
}
<h2>Random Post</h2>
<div id='random-post-container'>Memuat…</div>
This code show this type of pagination
1 2 3 4 5 6 7 8 9 10 11 12 next>>
I want show want show only first two digits and last And next button. Does first 2 values need to change on next click.
1 2 .... 12 next>>
This is my code:
_paginationOutput: function(currentPage, totalPages) {
this.writeDebug('_paginationOutput',arguments);
currentPage = parseFloat(currentPage);
var output = '';
var nextPage = currentPage + 1;
var prevPage = currentPage - 1;
// Previous page
if( currentPage > 0 ) {
output += '<li class="bh-sl-next-prev" data-page="' + prevPage + '">' + this.settings.prevPage + '</li>';
}
// Add the numbers
for (var p = 0; p < Math.ceil(totalPages); p++) {
var n = p + 1;
if (p === currentPage) {
output += '<li class="bh-sl-current" data-page="' + p + '">' + n + '</li>';
}
else {
output += '<li data-page="' + p + '">' + n + '</li>';
}
}
// Next page
if( nextPage < totalPages ) {
output += '<li class="bh-sl-next-prev" data-page="' + nextPage + '">' + this.settings.nextPage + '</li>';
}
return output;
},
You'll want to check if the p variable is one of the pages you would like ignored.
EDIT:
To add the ..., put it in the if condition, and check if you already printed the dot.
Try this code. Put this in the beginning of the for loop.
And, create a new variable called dotsAdded before the for loop.
if (p >= 2 && p < totalPages - 1) {
if (!dotsAdded) {
output += "...";
dotsAdded = true;
}
continue;
}
That will continue the loop if and only if p is between 2 and the "second to last page."
I'm making a paging on list of products. When i clicked on "Next" button and show in console value of "tranght" (My code only show value of "tranght") then type of "tranght" is converted to NaN. Help me, i'm newer in Jquery.
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
var ds = [];
var tranght = 1;
var sobanghi = 0;
var sotrang = 0;
$(document).ready(function(){
$('#btnshow').click(function(){
$.ajax({
type : 'GET',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
url : '${pageContext.request.contextPath }/findall.html',
success : function(result) {
ds = result.dssp;
sobanghi = result.dssp.length;
if ((sobanghi % 3) === 0){
sotrang = Math.floor(sobanghi / 3);
} else {
sotrang = Math.floor(sobanghi / 3) + 1;
}
var s = "";
s = s + "<table border=\"1\"><tr class=\"title\"><td>Ma sp</td><td>Ten sp</td><td>Gia</td><td>So luong</td><td>Ngay sx</td><td>Tinh trang</td><td>Mo ta</td><td>Hinh anh</td><td>Danh muc</td></tr>";
for (var i=0; i<3; i++){
s = s + "<tr><td>" + result.dssp[i].masp + "</td><td>" + result.dssp[i].tensp + "</td><td>" + result.dssp[i].gia + "</td><td>"+ result.dssp[i].soluong +"</td><td>"+ result.dssp[i].ngaysx + "</td><td>"+ result.dssp[i].tinhtrang +"</td><td>"+ result.dssp[i].mota +"</td><td>"+ result.dssp[i].hinhanh +"</td><td>"+ result.dssp[i].danhmuc.tendm +"</td></tr>" ;
}
s = s + "</table>";
$('#result').html(s);
var s1 = "<div class='prev'>Prev</div>";
s1 += "<div class='index clicked'>" + 1 + "</div>";
for (var i=2; i<=sotrang; i++){
s1 += "<div class='index'>" + i + "</div>";
}
s1 += "<div class='next'>Next</div>";
$('#result1').html(s1);
}
});
});
//select a page
$(".index").live('click', function(){
$("#result1 > div").removeClass('clicked');
$(this).addClass('clicked');
tranght = parseInt($(this).html());
var startpoint = (tranght - 1)*3;
var endpoint = startpoint + 3;
sobanghi = ds.length
if (endpoint > sobanghi){
endpoint = sobanghi;
}
var s = "";
s = s + "<table border=\"1\"><tr class=\"title\"><td>Ma sp</td><td>Ten sp</td><td>Gia</td><td>So luong</td><td>Ngay sx</td><td>Tinh trang</td><td>Mo ta</td><td>Hinh anh</td><td>Danh muc</td></tr>";
for (var i=startpoint; i<endpoint; i++){
s = s + "<tr><td>" + ds[i].masp + "</td><td>" + ds[i].tensp + "</td><td>" + ds[i].gia + "</td><td>"+ ds[i].soluong +"</td><td>"+ ds[i].ngaysx + "</td><td>"+ ds[i].tinhtrang +"</td><td>"+ ds[i].mota +"</td><td>"+ ds[i].hinhanh +"</td><td>"+ ds[i].danhmuc.tendm +"</td></tr>" ;
}
s = s + "</table>";
$('#result').html(s);
});
// click "next" button
$(".next").live('click', function(){
console.log("value of tranght: " + tranght);
console.log("Type of: " + typeof tranght);
if (tranght === sotrang){
tranght = sotrang;
console.log("Type of: " + typeof tranght);
} else {
tranght = parseInt(tranght,6) + 1;
console.log("value: " + tranght);
console.log("Type of: " + typeof tranght);
}
});
});
</script>
We are missing some code, is the html object with the class 'index' an input? if so, you need to change
tranght = parseInt($(this).html());
to
tranght = parseInt($(this).val());
to capture the value and not the content.
I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.
Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});