include json data in the load more button function - javascript

how do i include json data in the load more button function at
load more button : Jsfiddle example
var index = 1;
$(document).on("pagecreate", "#page1", function(){
$("#btnAdd").on("click", function(){
var allItems = '';
for (var i = 0; i < 100; i++) {
allItems += '<li><a href="javascript:showDetails(' + (index + i) + ')" >item number ' + (index + i) + '</a></li>';
}
index += 100;
$("#ListTemp").empty().append(allItems).listview("refresh");
var element = $("#ListTemp li").detach();
$("#ListDspQry").append(element);
});
});
My json url is : http://www.beritanisma.com/category/superlawak/?json=get_category_posts
been trying for days but it ended up showing no results, please help me masters, thank you..

var index = 0;
$(document).on("pagecreate", "#page1", function(){
$("#btnAdd").on("click", function(){
var url = "http://www.beritanisma.com/category/superlawak/?json=get_category_posts"
$.getJSON(url, function(data){
var allItems = '';
for (var i = 0; i < data.posts.length; i++) {
console.log(data.posts[i].url);
allItems += '<li><a href="javascript:showDetails(' + (index + i) + ')" >'+data.posts[i].url+'' + (index + i) + '</a></li>';
}
index += 100;
$("#ListTemp").empty().append(allItems).listview("refresh");
var element = $("#ListTemp li").detach();
$("#ListDspQry").append(element);
});
});
});

Related

Pure Js onclick element doesn't work

I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}

Fetching data in chunks

I have a carousel which I have built, which gets a list of products from my API and then each product is created as a slide in a carousel. This is all working perfectly.
When the current slide becomes active I download all of the images for that slide and populate the slide. This data also comes from the API.
What I want to do is have a speedier way to do this. At the moment I am loading these one at a time as they become "active". Ideally I want to be able to load 5 in straight away. So that the start of the array (0) is in the center of the loading array. Then when a user navigates left or right through the carousel I want to call in the next one forward or back.
So far my code is working so that when a slide is active it will have all images loaded, the code I have used for this is here:
module.carousel = (function(){
"use strict";
var exports = {};
exports.details = {};
exports.init = function (options) {
var defaultOptions = {
speed: 1500,
next: {},
back: {},
target: {}
};
if(options == null) options = {};
options = $.extend(defaultOptions, options);
exports.details.targetLength = options.target.children('li').length - 1;
exports.details.position = 0;
exports.details.products = options.target.children('li');
options.target.children('li:nth-child(' + (exports.details.position + 1) + ')').addClass('active');
exports.details.position += 1;
getMedia();
function removeActive() {
options.target.children('li.active').removeClass('active');
}
function addActive() {
options.target.children('li:nth-child(' + (exports.details.position) + ')').addClass('active');
}
function nextItem() {
if(exports.details.position >= exports.details.targetLength + 1) {
exports.details.position = 1;
} else {
exports.details.position += 1;
}
removeActive();
addActive();
getMedia();
}
function getMedia() {
var id = options.target.children('li.active').attr('data-id');
$.ajax({
url: "/beta/api/v1/watches/id/" + id + "/media",
dataType: "json",
async: false,
success: function(data) {
var mediaItems = "";
for(var x = 0, tot = data.length; x < tot; x++) {
mediaItems += "<div class='box'><img src='" + data[x] + "' class='intro-image'></div>";
}
$('#' + id + '_media').html(mediaItems);
}
});
}
function previousItem() {
if(exports.details.position === 1) {
exports.details.position = exports.details.targetLength + 1;
} else {
exports.details.position -= 1;
}
removeActive();
addActive();
getMedia();
}
$('html, body').on('swipeleft', function(event) {
event.stopPropagation();
nextItem();
});
$('html, body').on('swiperight', function(event) {
event.stopPropagation();
previousItem();
});
};
return exports;
}());
That is how my carousel works, and this is how I start it :
$(document).ready(function() {
$.getJSON("/beta/api/v1/watches", function(data) {
var productArray = [];
for(var i = 0, tot = data.length; i < tot; i++){
var productItem = "";
if(i === 0) {
productItem += "<li data-id='" + data[i].id + "' class='product active'>";
} else {
productItem += "<li data-id='" + data[i].id + "' class='product'>";
}
productItem += "<div class='product-header'><h3>"
+ data[i].name + "</h3><h3>" + data[i].case_finish
+ "</h3><h3>" + data[i].id + "</h3><h3>£" + data[i].price + "</h3></div>";
var product = data[i];
productItem += "<div id='" + data[i].id + "_media'></div>";
productItem += "</li>";
productArray.push(productItem);
}
$('#carousel').html(productArray);
$(document).on('swipeleft swiperight', function(event) {
event.stopImmediatePropagation();
});
module.carousel.init({
target: $('#carousel'),
next: $('#next'),
back: $('#back')
});
});
});

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

javascript inline code link generating chrome extension

I'm trying to make an extension for chrome that grabs data from a website and I'm having trouble making the links clickable. I CAN NOT use javascript inside the link (ex: href="javascript:myfunction(param);")
I need to create a div for each title, then create a onclick function that handles the div's innerhtml, and I can't get it to work.
here is my code so far:
document.addEventListener('DOMContentLoaded', function () {
$().ready(function () {
var url = 'http://somewebsite';
$.get(url, function (data) {
data = data.split("<tr name=\"hover\">");
var name;
var link;
var count = data.length;
count++;
for(var i = 1; i < data.length; i++){
data[i] = data[i].replace("<br>","<br />");
data[i] = data[i].replace("class=\"thread_link\"", "");
data[i] = data[i].replace("<td class=\"forum_thread_post\" align=\"center\">0</td>","");
data[i] = data[i].replace("<td class=\"forum_thread_post\">","");
data[i] = data[i].replace("</td>","");
data[i] = data[i].replace('<td class="forum_thread_post" align="center">0</td>','');
if(i != data.length-1){
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div><br /><br />");
}else{
data[i] = data[i].split("</table>")[0];
data[i] = data[i].replace("<a href=\"", "");
data[i] = data[i].replace("</a>", "");
data[i] = data[i].split("\" >");
data[i][1] = data[i][1].split("<");
document.write('<div id="' + data[i][1][0] + '">' + data[i][1][0] + data[i][0] + "</div>");
}
}
//document.body.innerHTML = '';
//console.log(data);
});
});
});
document.write('</script>');
function getshow(url){
alert(url);
document.body.innerHTML = '';
$.get("http://somewebsite" + url, function (dat) {
document.write(dat);
});
}

get text from attribute and format it

I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
​
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE

Categories