How do I get the function checkViewers(); to work properly? I believe I am calling it wrong within the JS document file and therefore the JS is not reading the function properly.
The current code:
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
The function is called towards the bottom of the remaining JS, after the JSON Data has been called.
Ideally, the JSON Data should be inputted into the HTML and the function should catch the number of viewers. This should then effect how the viewers are being shown in the HTML, upon how many viewers are being listed.
View the Plunker.
Making my comment an answer:
Ajax is Asynchronous. You ordered a pizza off the internet and you try to eat the pizza before it gets to your house. You have to wait for the pizza to show up before you eat it. AKA, you can not call your function until the data is there. So when you set the html, you call your function
xhr.onload = function() { //<--Function is called when the Pizza shows up at your door and the doorbell rings
... //removed a bunch of code....
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers); //You open up the pizza box
checkViewers(); //<--- MOVE IT HERE, The pizza is here!!!!
}
};
xhr.open('GET', 'data.json', true); //<-- You set up your pizza order
xhr.send(null); //<--You make the pizza purchase
//checkViewers(); <-- PIZZA IS NOT HERE!!!!
Related
I'm trying to write a function that increments a variable, which will later be stored as post meta for the WordPress post, by clicking the posts title. In other words, I want to a create function that keep track of how many times a post title of a certain post is being clicked.
I'm new to using jQuery so I'm trying to figure out how to get the 2 function in PHP and jQuery to interact. I need to process the data in PHP later, which is why I need to do this.
This is what I have so far (PHP):
function clickScoreMethod($postid){
//$clickScore = 0;
$clickScore = get_post_meta($postid, 'redditclickscore', true);
$clickScore = $clickScore + 0.25;
update_post_meta($postid, 'redditclickscore',$clickScore);
}
$clickScore is the variable I want to increase by 0.25 every time the post title is clicked. I'm using meta to store it easily per post. If it is simpler, I can also increase the score by just incrementing the variable and then dividing it by 4 when I process it in the PHP later.
The jQuery:
$("li.post-item article").each(function(){
$( ".the-post-container .entry-title" ).click(function() {
var clickScore = 0.25;
});
});
.entry-title is the post title and .post-item-article is basically the blog roll.
I have no idea how to get these two to work together so that I increase the number.
Use ajax to do this.
Your jQuery would look something like this:
$("li.post-item article").each(function () {
$(".the-post-container .entry-title").click(function () {
var clickScore = 0.25;
$.ajax({
url: "/path/to/php/file",
type: "POST",
data: { clickScore: clickScore },
success: function () {
console.log("Success!");
}
});
});
});
and you would access the variable and do stuff with it with this (in PHP):
$clickScore = $_POST["clickScore"]
Hope this helps you.
I'm getting the images with the media/search endopoint passing a lat and lon like this
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
and then I'm gettin only the pics with a certain tag #instabeachpro,if the pic is not found I go trough the next set of pics adding the last pic created_time to the url with the max_timestamp parameter, here is the code I'm using
(function(){
var url,tags,menos,photos = new Array(),i=90;
function search(){
generateResource(tag;
$.getJSON(url, toScreen);
}
function init(){
bindEventHandlers();
}
function generateResource(){
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
return url;
}
function toScreen(){
var next_url=url+"&max_timestamp="+data.data[data.data.length - 1].created_time;
$.each(data.data, function(index, photo){
i--;
tags=photo.tags;
menos=jQuery.inArray( "instabeachpro", tags );
if(menos!=-1)
{
$('div#photos-wrap').append("<div id='"+i+"' ><a href='"+photo.link+"'><img src='"+photo.images.low_resolution.url+"'/></a></div><div><img class='second' src='"+photo.user.profile_picture+"'/></div>");
}
else{
i++;
}
});
if(next_url!=undefined+"&callback=?" && i>=0){
console.log(i);
pagination(next_url);
}
}
function pagination(url)
{
$.getJSON(url, toScreen);
}
Instagram.App = {
search: search,
init: init
};
function bindEventHandlers(){
$('body').on('click', '#loadObject', function(){
url=$(this).attr('data-next-url');
i=90;
if(url=='undefined')
{
alert("undefined");
}
else{
pagination(url);
return false;
}
});
}
}());
$(function(){
Instagram.App.init();
Instagram.App.search();
});
This works but it's extremely slow and I have no idea what to do to speed it up, because the api doesn't support searching like I want to do, and i need to get al the pcitures with a certain tag IN a certain location, I have been told a number of times this is the only way to do it, but there has to be a faster way.Thank you.
Your method is extremely inefficient, since the tag you are searching is not popular and very small percentage of people use it, so getting API around location and then filtering by tag is expensive on number of API calls.
Search the other way round, make API call for the tag and then check for location for that photo. Check this implementation: http://www.gramfeed.com/instagram/tags#instabeachpro
You can get the tag photos and maps it on Google Maps, scroll to load more photos and see that very few of the #instabeachpro photos are tagged with location
I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.
I am working on the adobe air with javascript and html. I want to run multiple functions in a function with show the percentange run on the each function but the percentage also show the last calculation please help me.
Edit: added code snippet from comment, but I may have butchered the layout.
function show_percentage() {
down_admin()
down_staff()
down_client() }
function down_admin() {
down all information of admin from the server; flag=1; }
function down_staff() {
down all information of the staff falg=2; }
we want to calculation show the every after loaded functions. as percentage=25% to 100%
If you downloading several types of info and want to show summary progress, first you need to know bytes total of each download. When you get ProgressEvent from each operation, you may call function show():
function show() {
var progress = (adminBytesLoaded + staffBytesLoaded + clientBytesLoaded) * 100 /
(adminBytesTotal + staffBytesTotal + clientBytesTotal);
//show progress somehow
}
Update: some clarifications
Load resource you need with Loader. Add event listener to ProgressEvent on Loader.contentLoaderInfo. There will be three listeners for three load operations - load admin data, client data and staff data. When you get progress event from each operation (track it with three vars), you will know download size total:
var adminTotal:int;
var clientTotal:int;
var staffTotal:int;
var adminLoaded:int;
var clientLoaded:int;
var staffLoaded:int;
function onAdminLoadProgress(event:ProgressEvent):void
{
adminLoaded = event.bytesLoaded;
adminTotal = event.bytesTotal;
//if other operations already going, show progress
if (clientTotal && staffTotal)
{
showProgress();
}
}
function onClientLoadProgress(event:ProgressEvent):void
{
clientLoaded = event.bytesLoaded;
clientTotal = event.bytesTotal;
if (adminTotal && staffTotal)
{
showProgress();
}
}
//write onStaffLoaded yourself as an exercise :)))
I'm assuming you will make single request for each of those three downloads.
I'm trying to bypass going through a bunch of menus, to get to the data I want directly.
Here are the links I want to go to:
http://factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53053072904&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53025981400&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53067011620&tree_id=4001&context=dt&_lang=en&_ts=288363511701
Notice, if you pull that up right now, you simply see a GIF outline of the map, however there is no map data "behind" it.
However, if you go to: factfinder.census.gov/servlet/DTGeoSearchByListServlet?ds_name=DEC_2000_SF1_U&_lang=en&_ts=288392632118
Select Geographic Type: ..... ..... Census Tract
Select a State: Washington
Select a County: Pierce
Select one or more geographic areas: Census Tract 729.04
Hit "Map It"
The map will load perfectly. Also, until you close your browser, any of the other links will work perfectly. What I want to do, is be able to bypass these 5 steps, but obviously something is preventing this. Is there a feasible workaround? I have my own domain that I would be able to upload new Javascript or HTML files or whatever is needed.
Looking at the relevant code, there's only a few functions that are needed. The "Map it" button calls the mapit function with a string literal of '/servlet/MapItDrawServlet'.
function launchMapItServlet(mapItServlet) {
context = document.form1.context.value;
lang = "en";
url = mapItServlet + "?geo_id=" + geo + "&" + "tree_id=" + tree_id + "&context=" + context + "&_lang=" + lang;
url = getAFFWindowLocation(url, true);
windowCtr++;
window.open(url, "identify" + windowCtr, "menubar=yes,scrollbars=yes,resizable=yes,top=10,left=10,width=750,height=550");
}
function mapItMulti(servlet) {
if (numberOfSelections(document.forms["form1"].search_results) == 0 || numberOfSelections(document.forms["form1"].search_results) > 1) {
alert(ALERT_MSG1);
}
else if (canMapItMulti(document.forms["form1"].search_results)) {
index = document.forms["form1"].search_results.selectedIndex;
geo = document.forms["form1"].search_results.options[index].value;
tree_id = document.form1["tree_id"].value;
launchMapItServlet(servlet);
}
else {
alert(ALERT_MSG1);
}
}
function mapit(mapItServlet) {
geo = "";
mapItMulti(mapItServlet);
}
Notice the window.open function which will be the relevant information that you will want to use, especially the 'url' variable.