jQuery function preventing nested <body> elements from being read - html

My assignment is to create a Twitter clone with HTML, CSS, and jQuery. I have been provided a jQuery function that generates 10 tweets, but when I call it in <scripts>, I am only able to get it to run in the <body> tag, and all of my changes to HTML and CSS are canceled out. Basically it just spits out 10 tweets on top of my singular background.
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('Twitter-Clone');
var $tweets = $("tweets-container");
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
And if I write something like
$tweet.appendTo($tweets) <!--or-->
$tweet.appentTo("#tweets-container");
Tweets do not show up at all, AND my page ignores all the HTML and CSS I've written aside from what's at the top of <body>
I really want to know, how can I apply this function to my <div>"tweets-container", and why does the code seem to skip over all of my elements nested in <body> after execution?
I think once I figure this out, it'll be a huge step in the right direction. Any help is very much appreciated! Can supply additional code if needed.

Related

Wixcode "static" html iframe

Apologies if this is not the correct place to post this. I'm completely new to HTML and such, but I wanted to put a button on my website which would remember how many times it been pressed and each time someone presses it it give you a number, say for example the next prime number. With enough googleing I managed to put together some (what I expect is really bad code) which I thought could do this. This is what I have (sorry if its not formatted correctly, I had trouble with copy pasting).
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
function isPrime(_n)
{
var _isPrime=true;
var _sqrt=Math.sqrt(_n);
for(var _i=2;_i<=_sqrt;_i++)
if((_n%_i)==0) _isPrime=false;
return _isPrime;
}
function nextPrime(_s,_n)
{
while(_n>0)if(isPrime(_s++))_n--;
return --_s;
}
var clicks = 0;
function hello() {
clicks += 1;
v = nextPrime(2,clicks);
document.getElementById("clicks1").innerHTML = clicks ;
document.getElementById("v").innerHTML = v ;
};
</script>
<button type="button" onclick="hello()">Get your prime</button>
<p>How many primes have been claimed: <a id="clicks1">0</a></p>
<p>Your prime: <a id="v">0</a></p>
</body>
The problem is that when I put this code in a iframe on my wixsite it seems to reload the code each time you look at the site, so it starts the counter again. What I would like it say the button has been pressed 5 times, it will stay at 5 until the next visitor comes along and presses it. Is such a thing possible?
You don't actually need an iframe for that, You can use wixCode to do that. WixCode let's you have a DB collection. and all you need to do is update the collection values on every click.
Let's say you add an Events collection can have the fields:
id, eventName, clicksCount
add to it a single row with eventName = 'someButtonClickEvent' and clicksCount = 0
Then add the following code to your page:
import wixData from 'wix-data';
$w.onReady(function () {});
export function button1_click(event) {
wixData.get("Events", "the_event_id")
.then( (results) => {
let item = results;
let toSave = {
"_id": "the_event_id",
"clicksCount": item.clicksCount++
};
wixData.update("Events", toSave)
})
}
now you need to add button1_click as the onClick handler of your button (in the wixCode properties panel).

Need a random ID for a div to solve a caching issue in Wordpress

I'm hoping someone can help a javascript noob with a caching problem. I'm making a site in Wordpress and I've got a caching plugin installed. I need one div (that's on the sidebar of every page) NOT to be cached as it contains an image and text that is randomly generated on each page load. I've done a lot of reading and testing out of various online solutions, but I can't get one to work. I read that the best way to get around this is to give the div a random ID via Date.now(), but I can't get that to work either. So I found something close, yet it, too, doesn't work (posted below). The div doesn't show on screen, yet its contents show up fine in my source code.
Can anyone fix it for me or suggest something? I am a complete noob when it comes to javascript. Thank you for reading! :)
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">[autonav display="images,title, page, excerpt" pics_only="0" postid="11" attachment="1" orderby="rand" count=1]</div>');
</script>

HTML5 Progress Element Scripting

I'm trying to display a HTML5 progress element to show the download progress of a large image file.
I've checked a few answers to similar questions already posted on this forum but they don't seem to directly answer the question (or more likely it's just my ignorance) or they get very technical and therefore way beyond me.
I've downloaded a HTML5 / JavaScript example file that shows the basic method (see code below) but I can't figure out how to link this script to my image download.
Any advice would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Developer Drive | Displaying the Progress of Tasks with HTML5 | Demo</title>
<script type="text/javascript">
var currProgress = 0;
var done = false;
var total = 100;
function startProgress() {
var prBar = document.getElementById("prog");
var startButt = document.getElementById("startBtn");
var val = document.getElementById("numValue");
startButt.disabled=true;
prBar.value = currProgress;
val.innerHTML = Math.round((currProgress/total)*100)+"%";
currProgress++;
if(currProgress>100) done=true;
if(!done)
setTimeout("startProgress()", 100);
else
{
document.getElementById("startBtn").disabled = false;
done = false;
currProgress = 0;
}
}
</script>
</head>
<body>
<p>Task progress:</p>
<progress id="prog" value="0" max="100"></progress>
<input id="startBtn" type="button" value="start" onclick="startProgress()"/>
<div id="numValue">0%</div>
</body>
</html>
If you are looking to track the progress of an XMLHttpRequest (which could be loading an image, or anything else), Adobe has a great example there. Ctrl+U is your friend :)
Basically, you'll want to do that:
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
// This tests whether the server gave you the total number of bytes that were
// about to be sent; some servers don't (this is config-dependend), and
// without that information you can't know how far along you are
if (e.lengthComputable)
{
// e.loaded contains how much was loaded, while e.total contains
// the total size of the file, so you'll want to get the quotient:
progressBar.value = e.loaded / e.total * 100;
}
else
{
// You can't know the progress in term of percents, but you could still
// do something with `e.loaded`
}
};
Mozilla's Developer site has some more details, if you want to see what can be done.
Hope that's enough for you :)
PS: Now that I think about it, I see no reason not to use the e.total as progressBar.max, and simply push e.loaded into progressBar.value

Using Phonegap, Json and jQuery mobile, how to make a list of titles linking to the individuel articles

I used Json to get data off a site build in Wordpress (using the Json API plugin). I'm using jQuery mobile for the layout of the application in Phonegap. Getting the data to display in Phonegap wasn't the hardest thing to find (code below). But, is it possible to make a list of the titles of different posts and linking them to the specific article and loading the content in a page? In PHP you could just use an argument but is there a way to make something like this work in jQuery mobile?
Here's code I used. Also handy if someones happens to come across this post using google.
<script>
$(document).ready(function(){
var url="http://127.0.0.1:8888/wp/api/get_recent_posts";
$.getJSON(url,function(json){
$.each(json.posts,function(i,post){
$("#content").append(
'<div class="post">'+
'<h1>'+post.title+'</h1>'+
'<p>'+post.content+'</p>'+
'</div>'
);
});
});
});
</script>
EDIT:
I'd like to thank shanabus again for helping me with this. This was the code I got it to work
with:
$(document).ready(function() {
var url="http://127.0.0.1:8888/wpjson/api/get_recent_posts";
var buttonHtmlString = "", pageHtmlString = "";
var jsonResults;
$.getJSON(url,function(data){
jsonResults = data.posts;
displayResults();
});
function displayResults() {
for (i = 0; i < jsonResults.length; i++) {
buttonHtmlString += '' + jsonResults[i].title + '';
pageHtmlString += '<div data-role="page" id="' + $.trim(jsonResults[i].title).toLowerCase().replace(/ /g,'') + '">';
pageHtmlString += '<div data-role="header"><h1>' + jsonResults[i].title + '</h1></div>';
pageHtmlString += '<div data-role="content"><p>' + jsonResults[i].content + '</p></div>';
pageHtmlString += '</div>';
}
$("#buttonGroup").append(buttonHtmlString);
$("#buttonGroup a").button();
$("#buttonGroup").controlgroup();
$("#main").after(pageHtmlString);
}
});
Yes, this is possible. Check out this example: http://jsfiddle.net/shanabus/nuWay/1/
There you will see that we take an object array, cycle through it and append new buttons (and jqm styling). Does this do what you are looking to do?
I would also recommend improving your javascript by removing the $.each and substituting it for the basic for loop:
for(i = 0; i < json.posts.length; i++)
This loop structure is known to perform better. Same with the append method. I've heard time and time again that its more efficient to build up a string variable and append it once rather than call append multiple times.
UPDATE
In response to your comment, I have posted a new solution that simulates loading a Json collection of content objects to dynamically add page elements to your application. It also dynamically generates the buttons to link to them.
This works if you do it in $(document).ready() and probably a few other jQM events, but you may have to check the documentation on that or call one of the refresh content methods to make the pages valid.
http://jsfiddle.net/nuWay/4/
Hope this helps!

Chrome extension used to refresh pages

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?
Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html
Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.