Generate HTML with JavaScript and jQuery - JavaScript not executing? - javascript

Following to this post, I recreated the code with jQuery. jsFiddle says, that everything should be find and I can't find any mistakes either. Here's the Code:
function generatePost(title, time, text) {
var postCount = 0;
$('#postcontainer').append('<div></div>').attr('post_' + postCount).attr('class', 'content');
$('#post_' + postCount).append('<h3>' + title + '</h3>').attr('id', 'post_h3_' + postCount);
$('#post_h3_' + postCount).append('<span>' + time + '</span>');
var paragraphs = text.split("||");
for (var i = 0; i < paragraphs.length; i++) {
var paragraphCount = 0;
$('#post_' + postCount).append('<p>' + paragraphs[i] + '</p>').attr('id', 'post_p_' + postCount + '_' + paragraphCount);
paragraphCount++;
}
postCount++;
}
Now the problem might be that the JavaScript is not even executed, my HTML looks like this:
<head>
<?php include 'components/_head.php';?>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-migrate-1.2.1.min.js"></script>
<script src="js/postGen.js"></script>
<script type="application/javascript" src="postGen.js">
document.addEventListener('DOMContentLoaded', function() {
generatePost("Testing Title", "I don't know", "This is || a paragraph");
}
</script>
</head>
<body>
<header>
<?php include 'components/header.php';?>
</header>
<main>
<?php include 'components/main.php';?>
<div class="fullscreencontainer">
<img class="background" src="img/background.jpg">
<div class="title">
<h2>Der Bürger als Edelmann</h2>
<h4>von Moliére</h4>
</div>
</div>
<div class="container">
<div id="postcontainer">
/* ? */
</div>
<div class="sidebar">
</div>
</div>
</main>
<footer>
<?php include 'components/footer.php';?>
</footer>
</body>
The structure of the files:
index.php
js/jquery-1.11.3.min.js
js/jquery-migrate-1.2.1.min.js
js/postGen.js This file contains the code written in the first code-box
Inspector shows nothing new.
Console shows:
Syntax Error: Missing ) after argument list
EDIT:
The final Code:
<script type="application/javascript">
$(document).ready(function() {
function generatePost(title, time, text) {
var postCount = 0;
$('#postcontainer').append('<div id=' + "post_" + postCount + '></div>')
$('#post_' + postCount).attr('class', 'content');
$('#post_' + postCount).append('<h3>' + title + '<span>' + time + '</span></h3>');
var paragraphs = text.split("||");
for (var i = 0; i < paragraphs.length; i++) {
$('#post_' + postCount).append('<p>' + paragraphs[i] + '</p>');
}
postCount++;
}
generatePost("Testing Title", "I don't know", "This is || a paragraph");
generatePost("Testing Title", "I don't know", "This is || a paragraph");
generatePost("Testing Title", "I don't know", "This is || a paragraph");
generatePost("Testing Title", "I don't know", "This is || a paragraph");
});
</script>

Seems you were calling the generatePost() function too early (when document loads, but at the same time, thats also when you load your jQuery... why you were getting the ")" Missing error..).
So I changed the HTML to:
<head>
</head>
<body>
<main>
<div class="container">
<div id="postcontainer">
</div>
</div>
</main>
</body>
And the jQuery to:
$(document).ready(function() {
function generatePost(title, time, text) {
var postCount = 0;
$('#postcontainer').append('<div id=' + "post_" + postCount + '></div>').attr('class', 'content');
$('#post_' + postCount).append('<h3>' + title + '</h3>').attr('id', 'post_h3_' + postCount);
$('#post_h3_' + postCount).append('<span>' + time + '</span>');
var paragraphs = text.split("||");
for (var i = 0; i < paragraphs.length; i++) {
var paragraphCount = 0;
$('#post_' + postCount).append('<p>' + paragraphs[i] + '</p>').attr('id', 'post_p_' + postCount + '_' + paragraphCount);
paragraphCount++;
}
postCount++;
}
generatePost("Testing Title", "I don't know", "This is || a paragraph");
});
Just calling the function at the end of the document.ready. Also, as you can see, I also ran into some issues about how the post's id was being assigned, so ended up switching that up as well, assigning it with some simple string interpolation.
Cheers,
PG

Related

generate a tag foreach loop

i am trying to make a simple pagination with jquery. My goal is put a page number in function "paginate();" then it will just append +5 times with 5 page number. I mean it will generate always +5 page a tag dynamically. I already tried with code bellow but its not looping though 5 times. again my goal is: generate 6,7,8,9,10 not 1,2,3,4,5
function paginate(pageNumber) {
for (var i = 0; i < pageNumber; i++) {
//alert(i);
$(".inner").append("<a href="
"index?page=" + i + > "" + i + ""
"</a>");
}
}
paginate(5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Pagination</h2>
<div class="container">
<div class="inner"></div>
</div>
Use should write it like
$(".inner").append("" + i + "");
You need to use \ to escape the extra ", if you dont use \ to escape, then the code with either think your starting or ending a string.
function paginate(pageNumber) {
for (var i = 6; i <= (pageNumber + 5); i++) {
//alert(i);
$(".inner").append("" + i + "");
}
}
paginate(5);
function paginate2(pagestart, pageNumber) {
for (var i = pagestart; i < (pagestart + pageNumber); i++) {
//alert(i);
$(".inner").append("<br>" + i + "");
}
}
paginate2(6,5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Pagination</h2>
<div class="container">
<div class="inner"></div>
</div>
write this way
$(".inner").append("" + i + "");
function paginate(pageNumber) {
for (var i = 0; i < pageNumber; i++) {
$(".inner").append("" + i + "");
}
}
paginate(5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Pagination</h2>
<div class="container">
<div class="inner"></div>
</div>
You just have a syntax in your code. This code will work correctly:
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<h2>Pagination</h2>
<div class="container">
<div class="inner"></div>
</div>
<script>
function paginate(pageNumber) {
for (var i = 0; i < pageNumber; i++) {
$(".inner").append("" + i + "")
}
}
paginate(5);
</script>

JavaScript string doesn't get displayed on the page

pretty new to javascript and doing some examples from a book, can't understand why this isn't producing any text strings on the page when loaded.
function init()
{
var sum = 80 + 20;
var sub = sum - 50;
var mul = sum * 5;
var div = sum / 4;
var mod = sum % 2;
var inc = ++sum;
var dec = --sum;
var str = "Sum: " + sum;
str += "<br>Subtraction: " + sub;
str += "<br>Multiplication: " + mul;
str += "<br>Division: " + div;
str += "<br>Modulus: " + mod;
str += "<br>Increment: " + inc;
str += "<br>Decrement: " + dec;
document.getElementById( "Panel" ).innerHTML = str;
}
document.addEventListener("DOMContentLoaded" , init , false);
And the html5 code;
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="arithmetic.js"></script>
<title>Doing Arithmetic</title>
</head>
<body>
<div id="panel"> </div>
</body>
</html>
Your <div> has an id of panel, not Panel. The IDs need to match. So you can either change the JavaScript code:
document.getElementById( "panel" )
or the HTML:
<div id="Panel"> </div>
Replace
<div id="panel"> </div>
with
<div id="Panel"> </div>
and it will work. P in panel should be capital.

Having some trouble with jQuery mobile code

I am developing a jquery mobile webpage. In one of the pages i would like to implement an RSS reader. I found an RSS reader online that looks like this :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<link rel="stylesheet" href="themes/CustomTheme.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<style type='text/css'>
.ui-footer .ui-btn-right {
}
.articleContent > table > tbody > tr > td > font > br {
display: none;
}
.articleContent > table > tbody > tr > td > font > br + div {
display: none;
}
.articleContent * {
font-size: medium !important;
}
</style>
</head>
<body>
<script type='text/javascript'>//<![CDATA[
// ISCPA added search filter, home icon, updated CDN-Hosted links
// forked from sumukh1's "forked: RSS Reader with jQuery Mobile" http://jsdo.it/sumukh1/4Ton
/* configuration */
var maxLength = 20; /* writing HTML */
document.write('<div data-role="page" id="list">' + ' <div data-role="header" data-position="fixed">' + ' <h1><span id="widgetTitle">...</span> ' + ' <span style="font-size: x-small">(HTML)</span></h1>' + ' </div>' + ' <div data-role="content">' + ' <ul data-role="listview" data-filter="true" id="articleList">');
for (var i = 1; i <= maxLength; i++) {
document.write('<li id="list' + i + '"> </li>');
}
document.write(' </ul>' + ' </div>' + '</div>');
for (i = 1; i <= maxLength; i++) {
document.write('<div data-role="page" id="article' + i + '">' + ' <div data-role="header" data-position="inline">' + ' Home' + ' <h1 id="articleHeader' + i + '"> </h1>' + ' Open' + ' </div>' + ' <div data-role="content">' + ' <div id="articleContent' + i + '" class="articleContent"></div>' + ' <div data-role="controlgroup" data-type="horizontal">' + ' Prev' + ' Next' + ' </div>' + ' </div>' + '</div>');
} /* JSONP */
$(function() {
// getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
/*
getOnlineFeed('http://www.engadget.com/rss.xml');
getOnlineFeed('http://www.fremont.k12.ca.us/site/RSS.aspx?DomainID=1&ModuleInstanceID=4613&PageID=1');
getOnlineFeed('http://news.google.com/news?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=atom&topic=h');
getOnlineFeed('http://www.appbank.net/feed');
getOnlineFeed('http://japanese.engadget.com/rss.xml');
getOnlineFeed('http://www.bebit.co.jp/index.xml');
getOnlineFeed('http://www.ntt.com/rss/release.rdf?link_id=ostop_service_rss');
getOnlineFeed('http://feeds.feedburner.com/gapsis');
getOnlineFeed('http://octoba.net/feed');
getOfflineFeed('google_news_jsonp.js');
*/
}); /* functions */
var listEntries = function(json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength = json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength; i++) {
var entry = json.responseData.feed.entries[i - 1];
$('#link' + i).text(entry.title);
$('#articleHeader' + i).text(entry.title);
$('#openButton' + i).attr('href', entry.link);
$('#articleContent' + i).append(entry.content);
}
$('#article1 .prevButton').remove();
$('#article' + articleLength + ' .nextButton').remove();
if (articleLength < maxLength) {
for (i = articleLength + 1; i <= maxLength; i++) {
$('#list' + i).remove();
$('#article' + i).remove();
}
}
};
var getOnlineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', 'http://ajax.googleapis.com/ajax/services/feed/load?callback=listEntries&hl=ja&output=json-in-script&q=' + encodeURIComponent(url) + '&v=1.0&num=' + maxLength);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
var getOfflineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
//]]>
</script>
</body>
</html>
Ok this is a javascript that will dynamically create the page and everything. However i already have the page (in which i have a panel too) and what i am trying to do is integrate the code there. The page i have looks like this:
<div data-role="page" id="news" data-theme="a">
<div data-role="panel" id="mypanel">
<ul data-role="listview" data-inset="false">
<li data-role="list-divider">Espacio Joven</li>
<li>News</li>
<li>Agenda</li>
<li>Info</li>
<li>Activities</li>
<li>Al Dia</li>
<li data-role="list-divider">La Noche Es Joven</li>
</ul>
</div><!-- /panel -->
<div data-role="header">
<h1>News</h1>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true" class="RSSclass">
</ul>
</div> <!-- /content -->
</div>
Can someone help me configure the RSS code so that it creates the posts inside the
<ul data-role="listview" data-inset="true" class="RSSclass">
</ul>
that i have? I tried to tweak the code , eg i deleted the lines that create a page (i have a page so i dont need it) , instead of document.write i used append , so that to append the albums inside the listview , but still i have many many problems with it and it doesnt look good.
In case someone wonders , i tried to change the code to something like this :
$(document).on("pageshow", '#news', function() {
// ISCPA added search filter, home icon, updated CDN-Hosted links
// forked from sumukh1's "forked: RSS Reader with jQuery Mobile" http://jsdo.it/sumukh1/4Ton
/* configuration */
var maxLength = 20; /* writing HTML */
alert("Hello World!");
//Not sure if .listView('refresh'); is needed. Check it!
for (var i = 1; i <= maxLength; i++) {
$(".RSSclass").append('<li id="list' + i + '"> </li>');
}
for (i = 1; i <= maxLength; i++) {
document.write('<div data-role="page" id="article' + i + '">' + ' <div data-role="header" data-position="inline">' + ' Home' + ' <h1 id="articleHeader' + i + '"> </h1>' + ' Open' + ' </div>' + ' <div data-role="content">' + ' <div id="articleContent' + i + '" class="articleContent"></div>' + ' <div data-role="controlgroup" data-type="horizontal">' + ' Prev' + ' Next' + ' </div>' + ' </div>' + '</div>');
} /* JSONP */
$(function() {
// getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
/*
getOnlineFeed('http://www.engadget.com/rss.xml');
getOnlineFeed('http://www.fremont.k12.ca.us/site/RSS.aspx?DomainID=1&ModuleInstanceID=4613&PageID=1');
getOnlineFeed('http://news.google.com/news?hl=ja&ned=us&ie=UTF-8&oe=UTF-8&output=atom&topic=h');
getOnlineFeed('http://www.appbank.net/feed');
getOnlineFeed('http://japanese.engadget.com/rss.xml');
getOnlineFeed('http://www.bebit.co.jp/index.xml');
getOnlineFeed('http://www.ntt.com/rss/release.rdf?link_id=ostop_service_rss');
getOnlineFeed('http://feeds.feedburner.com/gapsis');
getOnlineFeed('http://octoba.net/feed');
getOfflineFeed('google_news_jsonp.js');
*/
}); /* functions */
var listEntries = function(json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength = json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength; i++) {
var entry = json.responseData.feed.entries[i - 1];
$('#link' + i).text(entry.title);
$('#articleHeader' + i).text(entry.title);
$('#openButton' + i).attr('href', entry.link);
$('#articleContent' + i).append(entry.content);
}
$('#article1 .prevButton').remove();
$('#article' + articleLength + ' .nextButton').remove();
if (articleLength < maxLength) {
for (i = articleLength + 1; i <= maxLength; i++) {
$('#list' + i).remove();
$('#article' + i).remove();
}
}
};
var getOnlineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', 'http://ajax.googleapis.com/ajax/services/feed/load?callback=listEntries&hl=ja&output=json-in-script&q=' + encodeURIComponent(url) + '&v=1.0&num=' + maxLength);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
var getOfflineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
//]]>
});
and added the CSS in the head of my html document but looks terrible...
Also i have an error : Uncaught TypeError: undefined is not a function in line :
$(function() {
// getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
getOnlineFeed('http://www4.lehigh.edu/news/rss/LUnews_rss.xml');
Any ideas?
You have/had to amend the listEntries function as that was the one that the JSOP was calling on callback.
var listEntries = function (json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength = json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength; i++) {
var entry = json.responseData.feed.entries[i - 1];
$(".RSSclass").append('<li id="list' + i + '">' + entry.title + '</li>');
}
$('.RSSclass').listview('refresh');
};
Also you had to add your custom page setup into the body of the page like so:
<div data-role="page" id="news" data-theme="a">
<div data-role="panel" id="mypanel">
<ul data-role="listview" data-inset="false">
<li data-role="list-divider">Espacio Joven</li>
<li>News
</li>
<li>Agenda
</li>
<li>Info
</li>
<li>Activities
</li>
<li>Al Dia
</li>
<li data-role="list-divider">La Noche Es Joven</li>
</ul>
</div>
<!-- /panel -->
<div data-role="header">
<h1>News</h1>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true" class="RSSclass"></ul>
</div>
<!-- /content -->
</div>
Then you had to delete the content that the above script generated automatically with document.write
Here's a JsBin of it working. http://jsbin.com/APojAlu/1/edit?html,output
Hope that helps.
I copied your code and had two error messages
listEntries undefined
maxLength undefined
If you put the following code before the statement $(document).on("pageshow", '#news', function() { they are both known and the content from your feed is displayed:
<script type='text/javascript'>//<![CDATA[
var maxLength = 20; /* writing HTML */
function listEntries (json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength = json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength; i++) {
var entry = json.responseData.feed.entries[i - 1];
$('#link' + i).text(entry.title);
$('#articleHeader' + i).text(entry.title);
$('#openButton' + i).attr('href', entry.link);
$('#articleContent' + i).append(entry.content);
}
$('#article1 .prevButton').remove();
$('#article' + articleLength + ' .nextButton').remove();
if (articleLength < maxLength) {
for (i = articleLength + 1; i <= maxLength; i++) {
$('#list' + i).remove();
$('#article' + i).remove();
}
}
};
$(document).on("pageshow", '#news', function() {
// rest follows here
This should get you going.

problems trying to get tweets from different zip codes

I am trying to get tweets from different zip codes.For doing this, I am using latitude and longitude values for each zip code. So far I want to get 3 tweets for each zip code(I have 2 zip codes), but it is working only for one zip code.
Any suggestion will be appreciated. Thank you in advance!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat=[41.9716,42.0411];
var lng=[-87.7026,-87.6900];
$(document).ready(function() {
for(var i=1; i<2; i++)
{
$.getJSON('http://search.twitter.com/search.json?q=business&geocode='+lat[i]+','+lng[i]+',5mi&lang=en&callback=?', function(data) {
var data = data.results;
var html = "";
for(var j=0; j<3;j++){
html += "<div style='width:600px;border:solid thin blue'><img src='"+data[j].profile_image_url+"'/><a href='http://twitter.com/" + data[j].from_user + "'>#"+ data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content'+i).html(html);
}); }
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
I found 2 problems with your code:
1) If you want to iterate 2 times, your for function should be like this: for (var i = 0; i < 2; i++)
2) You must have in consideration that the function that gets called in $.getJSON runs asynchronously, so when that function gets called the for will have already finished, therefore you can't use the i value with that purpose inside that function.
So, after correcting those 2 things in your code you should be able to get what you want. Try with something like this:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat = [41.9716, 42.0411];
var lng = [-87.7026, -87.6900];
var count = 1;
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$.getJSON('http://search.twitter.com/search.json?q=business&geocode=' + lat[i] + ',' + lng[i] + ',5mi&lang=en&callback=?', function (data) {
var data = data.results;
var html = "";
for (var j = 0; j < 3; j++) {
html += "<div style='width:600px;border:solid thin blue'><img src='" + data[j].profile_image_url + "'/><a href='http://twitter.com/" + data[j].from_user + "'>#" + data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content' + count++).html(html);
});
}
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
</html>

Rss feed items get pulled in several times

I'm having a problem pulling in a RSS feed in my phonegap application. The code works and the feed gets pulled in correctly, but each item is displayed 3 times. What am I doing wrong here?
function getEvents() {
showLoading();
$.getFeed({
url: 'http://thisismyfeedurl.com',
success: function(feed) {
var html = '';
for(var i = 0; i < feed.items.length; i++) {
var item = feed.items[i];
html += '<li><p><a class="title" href="#">' + item.title + '</a>' + item.description + '</p></li>';
$('#eventscount').text(i);
}
$('#eventsfeed').append(html);
hideLoading();
$('object').show();
}
});
};
I tested your code. It works fine. Ps, comics.xml is http://www.reddit.com/r/comics.xml
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/jfhovinne/jFeed/master/build/dist/jquery.jfeed.js"></script>
<div id="eventscount"></div>
<div id="eventsfeed"></div>
<script type="text/javascript">
$(document).ready(function () {
$.getFeed({
url: 'comics.xml',
success: function(feed) {
var html = '';
for(var i = 0; i < feed.items.length; i++) {
var item = feed.items[i];
html += '<li><p><a class="title" href="#">' + item.title + '</a>' + item.description + '</p></li>';
$('#eventscount').text(i);
}
$('#eventsfeed').append(html);
}
});
});
</script>
24
Money in Sight!submitted by imasif [link] [11 comments]
From my sketchbook: Evolutionary stages of Redditsubmitted by
Schaafwond [link] [55 comments]
Basically, every sports column I read on Monday...submitted by milk4dh
[link] [21 comments]
(snip)

Categories

Resources