Jquery script doen't load in a logical order - javascript

I got this code here in a JS file, where I've put two console.log(), one at the beginning and one at the end, to see why I'm having problems targeting the with a specific ID / class. Now I see that the console.log() at the end loads before the one in the beginning. Even when I place a console.log() outside of the file underneath the <script> tag which loads this JS file, it loads before the JS file, which doesn't make any sense to me. How can I fix this problem?
/*!
* jquery.instagramFeed
*
* #version 1.2.7
*
* #author Javier Sanahuja Liebana <bannss1#gmail.com>
* #contributor csanahuja <csanahuja10#gmail.com>
*
* https://github.com/jsanahuja/jquery.instagramFeed
*
*/
(function($){
var defaults = {
'host': "https://www.instagram.com/",
'username': 'username',
'tag': '',
'container': '#instagram',
'display_profile': true,
'display_biography': true,
'display_gallery': true,
'display_igtv': false,
'get_data': false,
'callback': null,
'styling': true,
'items': 8,
'items_per_row': 4,
'margin': 0.5,
'image_size': 640
};
var image_sizes = {
"150": 0,
"240": 1,
"320": 2,
"480": 3,
"640": 4
};
var escape_map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escape_string(str){
return str.replace(/[&<>"'`=\/]/g, function (char) {
return escape_map[char];
});
}
$.instagramFeed = function(opts){
//console log at the beginning of the function
console.log("Beginning instagramFeed");
var options = $.fn.extend({}, defaults, opts);
if(options.username == "" && options.tag == ""){
console.error("Instagram Feed: Error, no username or tag found.");
return false;
}
if(typeof options.get_raw_json !== "undefined"){
console.warn("Instagram Feed: get_raw_json is deprecated. See use get_data instead");
options.get_data = options.get_raw_json;
}
if(!options.get_data && options.container == ""){
console.error("Instagram Feed: Error, no container found.");
return false;
}
if(options.get_data && options.callback == null){
console.error("Instagram Feed: Error, no callback defined to get the raw json");
return false;
}
var is_tag = options.username == "",
url = is_tag ? options.host + "explore/tags/"+ options.tag + "/" : options.host + options.username + "/";
$.get(url, function(data){
try{
data = data.split("window._sharedData = ")[1].split("<\/script>")[0];
}catch(e){
console.error("Instagram Feed: It looks like the profile you are trying to fetch is age restricted. See https://github.com/jsanahuja/InstagramFeed/issues/26");
return;
}
data = JSON.parse(data.substr(0, data.length - 1));
data = data.entry_data.ProfilePage || data.entry_data.TagPage;
if(typeof data === "undefined"){
console.error("Instagram Feed: It looks like YOUR network has been temporary banned because of too many requests. See https://github.com/jsanahuja/jquery.instagramFeed/issues/25");
return;
}
data = data[0].graphql.user || data[0].graphql.hashtag;
if(options.get_data){
options.callback(data);
return;
}
//Setting styles
var styles = {
'profile_container': "",
'profile_image': "",
'profile_name': "",
'profile_biography': "",
'gallery_image': ""
};
if(options.styling){
styles.profile_container = " style='text-align:center;'";
styles.profile_image = " style='border-radius:10em;width:15%;max-width:125px;min-width:50px;'";
styles.profile_name = " style='font-size:1.2em;'";
styles.profile_biography = " style='font-size:1em;'";
var width = (100 - options.margin * 2 * options.items_per_row)/options.items_per_row;
styles.gallery_image = " style='margin:"+options.margin+"% "+options.margin+"%;width:"+width+"%;float:left;'";
}
var html = "";
//Displaying profile
if(options.display_profile){
html += "<div class='instagram_profile'" +styles.profile_container +">";
html += "<img class='instagram_profile_image' src='"+ data.profile_pic_url +"' alt='"+ (is_tag ? data.name + " tag pic" : data.username + " profile pic") +"'"+ styles.profile_image +" />";
if(is_tag)
html += "<p class='instagram_tag'"+ styles.profile_name +"><a href='https://www.instagram.com/explore/tags/"+ options.tag +"' rel='noopener' target='_blank'>#"+ options.tag +"</a></p>";
else
html += "<p class='instagram_username'"+ styles.profile_name +">#"+ data.full_name +" (<a href='https://www.instagram.com/"+ options.username +"' rel='noopener' target='_blank'>#"+options.username+"</a>)</p>";
if(!is_tag && options.display_biography)
html += "<p class='instagram_biography'"+ styles.profile_biography +">"+ data.biography +"</p>";
html += "</div>";
}
//image size
var image_index = typeof image_sizes[options.image_size] !== "undefined" ? image_sizes[options.image_size] : image_sizes[640];
if(options.display_gallery){
if(typeof data.is_private !== "undefined" && data.is_private === true){
html += "<p class='instagram_private'><strong>This profile is private</strong></p>";
}else{
var imgs = (data.edge_owner_to_timeline_media || data.edge_hashtag_to_media).edges;
max = (imgs.length > options.items) ? options.items : imgs.length;
html += "<div class='instagram_gallery'>";
for(var i = 0; i < max; i++){
var url = "https://www.instagram.com/p/" + imgs[i].node.shortcode,
image, type_resource, caption, date, likes, comments;
switch(imgs[i].node.__typename){
case "GraphSidecar":
type_resource = "sidecar"
image = imgs[i].node.thumbnail_resources[image_index].src;
date = new Date(imgs[i].node.taken_at_timestamp * 1000);
likes = imgs[i].node.edge_media_preview_like.count;
comments = imgs[i].node.edge_media_to_comment.count;
break;
case "GraphVideo":
type_resource = "video";
image = imgs[i].node.thumbnail_src
break;
default:
type_resource = "image";
image = imgs[i].node.thumbnail_resources[image_index].src;
date = new Date(imgs[i].node.taken_at_timestamp * 1000);
likes = imgs[i].node.edge_media_preview_like.count;
comments = imgs[i].node.edge_media_to_comment.count;
}
console.log(date);
console.log(likes);
console.log(comments);
if(
typeof imgs[i].node.edge_media_to_caption.edges[0] !== "undefined" &&
typeof imgs[i].node.edge_media_to_caption.edges[0].node !== "undefined" &&
typeof imgs[i].node.edge_media_to_caption.edges[0].node.text !== "undefined" &&
imgs[i].node.edge_media_to_caption.edges[0].node.text !== null
){
caption = imgs[i].node.edge_media_to_caption.edges[0].node.text;
}else if(
typeof imgs[i].node.accessibility_caption !== "undefined" &&
imgs[i].node.accessibility_caption !== null
){
caption = imgs[i].node.accessibility_caption;
}else{
caption = (is_tag ? data.name : data.username) + " image " + i;
}
html += "<a id='instagramID" + i + "' class='instagramimg instagram-" + type_resource + "' rel='noopener' target='_blank'>";
html += "<img class='instagramicon' src='https://cdn.shopify.com/s/files/1/0278/9644/7113/files/instagram-icon.svg?v=1592246117' alt='instagramicon'>";
html += "<div class='instagramhover'></div>";
html += "<img src='" + image + "' alt='" + escape_string(caption) + "'"/* + styles.gallery_image*/ +" />";
html += "</a>";
}
}
}
if(options.display_igtv && typeof data.edge_felix_video_timeline !== "undefined"){
var igtv = data.edge_felix_video_timeline.edges,
max = (igtv.length > options.items) ? options.items : igtv.length
if(igtv.length > 0){
html += "<div class='instagram_igtv'>";
for(var i = 0; i < max; i++){
html += "<a href='https://www.instagram.com/p/"+ igtv[i].node.shortcode +"' rel='noopener' target='_blank'>";
html += "<img src='"+ igtv[i].node.thumbnail_src +"' alt='"+ options.username +" instagram image "+ i+"'"+styles.gallery_image+" />";
html += "</a>";
}
html += "</div>";
}
}
$(options.container).html(html);
}).fail(function(e){
console.error("Instagram Feed: Unable to fetch the given user/tag. Instagram responded with the status code: ", e.status);
});
return true;
};
// Ending of the code
console.log("Ending instagramFeed");
})(jQuery);
This function gets called like this in the html part. Also here, the console.log("before instagramFeed.JS"); loads together with console.log("after instagramFeed.JS");, and after that I receive the
console.log(date);
console.log(likes);
console.log(comments);
which are inside the for loop of the function.
<script src="{{ 'jquery.instagramFeed.js' | asset_url }}"></script>
<div id="instagram"></div>
<script>
console.log("before instagramFeed.JS");
(function($){
$(window).on('load', function(){
$.instagramFeed({
'username': 'username',
'container': "#instagram",
'display_profile': false,
'display_biography': false,
'display_gallery': true,
'callback': null,
'styling': true,
'items': 10,
'items_per_row': 5,
'margin': 0.2
});
});
})(jQuery);
console.log("after instagramFeed.JS");
</script>

Your code is executed in the following order:
first snippet (definition of instagramFeed plugin) is executed during page load. console.log statements outside of that plugin are executed as well.
window is loaded (all script tag contents are read and executed), your window load handler kicks in. It calls your instagramFeed function the way you set it in the second snippet. before/after instagramFeed.JS logs are executed here. instagramFeed function starts a network call the result of which is processed after the load handler finishes running.
network call response is processed. comments, likes and date are logged at this stage.
As a result, everything is working as expected if I understand the purpose correctly.
UPD: to use the elements generated by network call response handler (provided you have an opportunity to edit the plugin code directly) you can add a function into options object, say onImageElementsCreated and call it after the loop in the plugin. Then you can provide your function as another option in the second snippet.

I can't say this with 100% certainty, as I haven't run the code.
However, I think the line console.log("Ending instagramFeed"); is being run before the line console.log("Beginning instagramFeed");, because it's outside the function $.instagramFeed = function(opts).
The function is created, then the ending log line is called, then something is calling the function, then the beginning log line is called.
Where in your code do you call $.instagramFeed()?

Related

How to load only part of a document in javascript?

I am new to JavaScript and I have an html page that loads the source code from this page into a given div and I am using the code provided by the user rob-w which works fine but my main goal is to learn how to show only part of the returned text starting at a given value and ending at a given value after that
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector("#message");
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// #author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
I have played around with many DOM functions and getBy functions but I have not been able to apply them correctly and I don't think they are exactly what I am after. If someone can point me in the right direction it would be appreciated
My solution uses String.prototype.match() to get an array containing all values between strings x and y but not including strings x and y.
function getStringsBetweenXandY(html) {
var matches = html.match(/x[\s\S]*?y/g), i = matches.length;
while(i--) {
matches[i] = matches[i].match(/x([\s\S]*?)y/)[1];
}
return matches;
}
var array = getStringsBetweenXandY(html);
You need to make sure that strings x and y contain backslashes where necessary.
matches will contain an array or an array-like object containing all of the html fragments you are looking for

Javascript Filevalidation always return false

I have a function that is part of a fileupload, however when i try to validate the files through an array, wether i use an "accepted" file or a "wrong" file, i get the same end result which is the alert message on the return false statement of the code.
can someone spot an error here ? there are no syntax errors in the function.
handleFiles = function (files,e){
var rand = Math.floor((Math.random()*100000)+3);
for(var i=0, file; file = files[i]; i++) {
var fileType = new Array("psd","ai","eps","svg","png","doc","docx","jpg","jpeg","pptx","ppt","gif");
var file_extension = file.name.split('.').pop().toLowerCase();
if (parseInt(file.size / 1024) > 204800) {
alert("Filen er \""+file.name+"\" for stor");
return false;
}
if (fileType[i]==file_extension)
{
var src = '/printuploads/upload.png'
var template = '<div class="eachImage" id="'+rand+'">';
template += '<span class="preview" id="'+rand+'"><img src="'+src+'"><span class="overlay"><span class="updone"></span></span>';
template += '</span>'
template += '<div class="progress" id="'+rand+'"><span></span></div>';
if($("#dropbox .eachImage").html() == null)
$("#dropbox").html(template);
else
$("#dropbox").append(template);
upload(file,rand);
return true;
}
alert("Forkert filformat");
return false;
}
};
Your validation to check if the file extension is supported is incorrect:
fileType[i]==file_extension
Here, i is the index of file, not the extension. So every file extension is being compared with "psd".
Instead it should be checking if the extension is available in the array file_extension. You can do that using Array#some method:
fileType.some(t => t == file_extension)
Or, you can simply check that the extension belongs to the array using indexOf:
fileType.indexOf(file_extension) >= 0
Here's a working snippet, you can check the logged value in the console:
var handleFiles = function(files, e) {
var rand = Math.floor((Math.random() * 100000) + 3);
for (var i = 0, file; file = files[i]; i++) {
var fileType = new Array("psd", "ai", "eps", "svg", "png", "doc", "docx", "jpg", "jpeg", "pptx", "ppt", "gif");
var file_extension = file.name.split('.').pop().toLowerCase();
if (parseInt(file.size / 1024) > 204800) {
alert("Filen er \"" + file.name + "\" for stor");
return false;
}
if (fileType.some(t => t == file_extension)) {
console.log("Extension matches");
var src = '/printuploads/upload.png'
var template = '<div class="eachImage" id="' + rand + '">';
template += '<span class="preview" id="' + rand + '"><img src="' + src + '"><span class="overlay"><span class="updone"></span></span>';
template += '</span>'
template += '<div class="progress" id="' + rand + '"><span></span></div>';
if ($("#dropbox .eachImage").html() == null)
$("#dropbox").html(template);
else
$("#dropbox").append(template);
upload(file, rand);
return true;
}
alert("Forkert filformat");
return false;
}
};
function upload() {};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type ="file" onchange="handleFiles(this.files, event);">

jQuery slickQuiz plugin: support multiple quizes on the same page?

Please see comment under question first.
I apologize to those that have read this question so far (10 views). I'm still not sure of the syntax to pass in the quiz configuration but she apparently allows it.
I'm trying to make a small change so the slickQuiz plugin supports multiple quizes on the same page, which the author 3 years suggested it probably can do. However it's loading in the same quiz questions and it seems due to the defining of quizJSON in slickQuiz-config.js file:
// Setup your quiz text and questions here
var quizJSON = {
"info": {
"name": "Test Your Knowledge!!",
"main": "<p>Think you're smart enough to be on Jeopardy?
... continues on ...
}
};
and the following line in slickQuiz.js, apparently allowing no variability on the quizJSON configuration loaded in:
// Set via json option or quizJSON variable (see slickQuiz-config.js)
var quizValues = (plugin.config.json ? plugin.config.json : typeof quizJSON != 'undefined' ? quizJSON : null);
I'm quite new to Javascript and am not sure how I could pass something in to set which quiz configuration (questions/answers) file is used for quizValues . Note the plugin includes a tiny master.js file, where it appears I can set a different id for each quiz:
// master.js file -- originally just defined #slickQuiz
$(function () {
$('#slickQuiz').slickQuiz();
});
$(function () {
$('#slickQuiz2').slickQuiz();
});
But how do I pass a parameter into slickQuiz() that I can use inside slickQuiz.js? This is probably trivial, but the way the function is invoked and its options are confusing to me new to JS.
Note here is how the slickQuiz id gets used in the plugin's example html file:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<title>SlickQuiz Demo</title>
<link href="css/reset.css" media="screen" rel="stylesheet" type="text/css">
<link href="css/slickQuiz.css" media="screen" rel="stylesheet" type="text/css">
<link href="css/master.css" media="screen" rel="stylesheet" type="text/css">
</head>
<body id="slickQuiz">
<h1 class="quizName"><!-- where the quiz name goes --></h1>
<div class="quizArea">
<div class="quizHeader">
<!-- where the quiz main copy goes -->
<a class="button startQuiz" href="#">Get Started!</a>
</div>
<!-- where the quiz gets built -->
</div>
<div class="quizResults">
<h3 class="quizScore">You Scored: <span><!-- where the quiz score goes --></span></h3>
<h3 class="quizLevel"><strong>Ranking:</strong> <span><!-- where the quiz ranking level goes --></span></h3>
<div class="quizResultsCopy">
<!-- where the quiz result copy goes -->
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/slickQuiz-config.js"></script>
<script src="js/slickQuiz.js"></script>
<script src="js/master.js"></script>
</body>
</html>
Here is most of the slickQuiz.js file (only allowed to copy in so much, rest at link above):
/*!
* SlickQuiz jQuery Plugin
(function($){
$.slickQuiz = function(element, options) {
var plugin = this,
$element = $(element),
_element = '#' + $element.attr('id'),
defaults = {
checkAnswerText: 'Check My Answer!',
nextQuestionText: 'Next ยป',
backButtonText: '',
completeQuizText: '',
tryAgainText: '',
questionCountText: 'Question %current of %total',
preventUnansweredText: 'You must select at least one answer.',
questionTemplateText: '%count. %text',
scoreTemplateText: '%score / %total',
nameTemplateText: '<span>Quiz: </span>%name',
skipStartButton: false,
numberOfQuestions: null,
randomSortQuestions: false,
randomSortAnswers: false,
preventUnanswered: false,
disableScore: false,
disableRanking: false,
scoreAsPercentage: false,
perQuestionResponseMessaging: true,
perQuestionResponseAnswers: false,
completionResponseMessaging: false,
displayQuestionCount: true, // Deprecate?
displayQuestionNumber: true, // Deprecate?
animationCallbacks: { // only for the methods that have jQuery animations offering callback
setupQuiz: function () {},
startQuiz: function () {},
resetQuiz: function () {},
checkAnswer: function () {},
nextQuestion: function () {},
backToQuestion: function () {},
completeQuiz: function () {}
},
events: {
onStartQuiz: function (options) {},
onCompleteQuiz: function (options) {} // reserved: options.questionCount, options.score
}
},
// Class Name Strings (Used for building quiz and for selectors)
questionCountClass = 'questionCount',
questionGroupClass = 'questions',
questionClass = 'question',
answersClass = 'answers',
responsesClass = 'responses',
completeClass = 'complete',
correctClass = 'correctResponse',
incorrectClass = 'incorrectResponse',
correctResponseClass = 'correct',
incorrectResponseClass = 'incorrect',
checkAnswerClass = 'checkAnswer',
nextQuestionClass = 'nextQuestion',
lastQuestionClass = 'lastQuestion',
backToQuestionClass = 'backToQuestion',
tryAgainClass = 'tryAgain',
// Sub-Quiz / Sub-Question Class Selectors
_questionCount = '.' + questionCountClass,
_questions = '.' + questionGroupClass,
_question = '.' + questionClass,
_answers = '.' + answersClass,
_answer = '.' + answersClass + ' li',
_responses = '.' + responsesClass,
_response = '.' + responsesClass + ' li',
_correct = '.' + correctClass,
_correctResponse = '.' + correctResponseClass,
_incorrectResponse = '.' + incorrectResponseClass,
_checkAnswerBtn = '.' + checkAnswerClass,
_nextQuestionBtn = '.' + nextQuestionClass,
_prevQuestionBtn = '.' + backToQuestionClass,
_tryAgainBtn = '.' + tryAgainClass,
// Top Level Quiz Element Class Selectors
_quizStarter = _element + ' .startQuiz',
_quizName = _element + ' .quizName',
_quizArea = _element + ' .quizArea',
_quizResults = _element + ' .quizResults',
_quizResultsCopy = _element + ' .quizResultsCopy',
_quizHeader = _element + ' .quizHeader',
_quizScore = _element + ' .quizScore',
_quizLevel = _element + ' .quizLevel',
// Top Level Quiz Element Objects
$quizStarter = $(_quizStarter),
$quizName = $(_quizName),
$quizArea = $(_quizArea),
$quizResults = $(_quizResults),
$quizResultsCopy = $(_quizResultsCopy),
$quizHeader = $(_quizHeader),
$quizScore = $(_quizScore),
$quizLevel = $(_quizLevel)
;
// Reassign user-submitted deprecated options
var depMsg = '';
if (options && typeof options.disableNext != 'undefined') {
if (typeof options.preventUnanswered == 'undefined') {
options.preventUnanswered = options.disableNext;
}
depMsg += 'The \'disableNext\' option has been deprecated, please use \'preventUnanswered\' in it\'s place.\n\n';
}
if (options && typeof options.disableResponseMessaging != 'undefined') {
if (typeof options.preventUnanswered == 'undefined') {
options.perQuestionResponseMessaging = options.disableResponseMessaging;
}
depMsg += 'The \'disableResponseMessaging\' option has been deprecated, please use' +
' \'perQuestionResponseMessaging\' and \'completionResponseMessaging\' in it\'s place.\n\n';
}
if (options && typeof options.randomSort != 'undefined') {
if (typeof options.randomSortQuestions == 'undefined') {
options.randomSortQuestions = options.randomSort;
}
if (typeof options.randomSortAnswers == 'undefined') {
options.randomSortAnswers = options.randomSort;
}
depMsg += 'The \'randomSort\' option has been deprecated, please use' +
' \'randomSortQuestions\' and \'randomSortAnswers\' in it\'s place.\n\n';
}
if (depMsg !== '') {
if (typeof console != 'undefined') {
console.warn(depMsg);
} else {
alert(depMsg);
}
}
// End of deprecation reassignment
plugin.config = $.extend(defaults, options);
// Set via json option or quizJSON variable (see slickQuiz-config.js)
var quizValues = (plugin.config.json ? plugin.config.json : typeof quizJSON != 'undefined' ? quizJSON : null);
// Get questions, possibly sorted randomly
var questions = plugin.config.randomSortQuestions ?
quizValues.questions.sort(function() { return (Math.round(Math.random())-0.5); }) :
quizValues.questions;
// Count the number of questions
var questionCount = questions.length;
// Select X number of questions to load if options is set
if (plugin.config.numberOfQuestions && questionCount >= plugin.config.numberOfQuestions) {
questions = questions.slice(0, plugin.config.numberOfQuestions);
questionCount = questions.length;
}
// some special private/internal methods
var internal = {method: {
// get a key whose notches are "resolved jQ deferred" objects; one per notch on the key
// think of the key as a house key with notches on it
getKey: function (notches) { // returns [], notches >= 1
var key = [];
for (i=0; i<notches; i++) key[i] = $.Deferred ();
return key;
},
// put the key in the door, if all the notches pass then you can turn the key and "go"
turnKeyAndGo: function (key, go) { // key = [], go = function ()
// when all the notches of the key are accepted (resolved) then the key turns and the engine (callback/go) starts
$.when.apply (null, key). then (function () {
go ();
});
},
// get one jQ
getKeyNotch: function (key, notch) { // notch >= 1, key = []
// key has several notches, numbered as 1, 2, 3, ... (no zero notch)
// we resolve and return the "jQ deferred" object at specified notch
return function () {
key[notch-1].resolve (); // it is ASSUMED that you initiated the key with enough notches
};
}
}};
plugin.method = {
// Sets up the questions and answers based on above array
setupQuiz: function(options) { // use 'options' object to pass args
var key, keyNotch, kN;
key = internal.method.getKey (3); // how many notches == how many jQ animations you will run
keyNotch = internal.method.getKeyNotch; // a function that returns a jQ animation callback function
kN = keyNotch; // you specify the notch, you get a callback function for your animation
$quizName.hide().html(plugin.config.nameTemplateText
.replace('%name', quizValues.info.name) ).fadeIn(1000, kN(key,1));
$quizHeader.hide().prepend($('<div class="quizDescription">' + quizValues.info.main + '</div>')).fadeIn(1000, kN(key,2));
$quizResultsCopy.append(quizValues.info.results);
// add retry button to results view, if enabled
if (plugin.config.tryAgainText && plugin.config.tryAgainText !== '') {
$quizResultsCopy.append('<p><a class="button ' + tryAgainClass + '" href="#">' + plugin.config.tryAgainText + '</a></p>');
}
// Setup questions
var quiz = $('<ol class="' + questionGroupClass + '"></ol>'),
count = 1;
// Loop through questions object
for (i in questions) {
if (questions.hasOwnProperty(i)) {
var question = questions[i];
var questionHTML = $('<li class="' + questionClass +'" id="question' + (count - 1) + '"></li>');
if (plugin.config.displayQuestionCount) {
questionHTML.append('<div class="' + questionCountClass + '">' +
plugin.config.questionCountText
.replace('%current', '<span class="current">' + count + '</span>')
.replace('%total', '<span class="total">' +
questionCount + '</span>') + '</div>');
}
var formatQuestion = '';
if (plugin.config.displayQuestionNumber) {
formatQuestion = plugin.config.questionTemplateText
.replace('%count', count).replace('%text', question.q);
} else {
formatQuestion = question.q;
}
questionHTML.append('<h3>' + formatQuestion + '</h3>');
// Count the number of true values
var truths = 0;
for (i in question.a) {
if (question.a.hasOwnProperty(i)) {
answer = question.a[i];
if (answer.correct) {
truths++;
}
}
}
// Now let's append the answers with checkboxes or radios depending on truth count
var answerHTML = $('<ul class="' + answersClass + '"></ul>');
// Get the answers
var answers = plugin.config.randomSortAnswers ?
question.a.sort(function() { return (Math.round(Math.random())-0.5); }) :
question.a;
// prepare a name for the answer inputs based on the question
var selectAny = question.select_any ? question.select_any : false,
forceCheckbox = question.force_checkbox ? question.force_checkbox : false,
checkbox = (truths > 1 && !selectAny) || forceCheckbox,
inputName = $element.attr('id') + '_question' + (count - 1),
inputType = checkbox ? 'checkbox' : 'radio';
if( count == quizValues.questions.length ) {
nextQuestionClass = nextQuestionClass + ' ' + lastQuestionClass;
}
for (i in answers) {
if (answers.hasOwnProperty(i)) {
answer = answers[i],
optionId = inputName + '_' + i.toString();
// If question has >1 true answers and is not a select any, use checkboxes; otherwise, radios
var input = '<input id="' + optionId + '" name="' + inputName +
'" type="' + inputType + '" /> ';
var optionLabel = '<label for="' + optionId + '">' + answer.option + '</label>';
var answerContent = $('<li></li>')
.append(input)
.append(optionLabel);
answerHTML.append(answerContent);
}
}
// Append answers to question
questionHTML.append(answerHTML);
// If response messaging is NOT disabled, add it
if (plugin.config.perQuestionResponseMessaging || plugin.config.completionResponseMessaging) {
// Now let's append the correct / incorrect response messages
var responseHTML = $('<ul class="' + responsesClass + '"></ul>');
responseHTML.append('<li class="' + correctResponseClass + '">' + question.correct + '</li>');
responseHTML.append('<li class="' + incorrectResponseClass + '">' + question.incorrect + '</li>');
// Append responses to question
questionHTML.append(responseHTML);
}
// Appends check answer / back / next question buttons
if (plugin.config.backButtonText && plugin.config.backButtonText !== '') {
questionHTML.append('' + plugin.config.backButtonText + '');
}
var nextText = plugin.config.nextQuestionText;
if (plugin.config.completeQuizText && count == questionCount) {
nextText = plugin.config.completeQuizText;
}
// If we're not showing responses per question, show next question button and make it check the answer too
if (!plugin.config.perQuestionResponseMessaging) {
questionHTML.append('' + nextText + '');
} else {
questionHTML.append('' + nextText + '');
questionHTML.append('' + plugin.config.checkAnswerText + '');
}
// Append question & answers to quiz
quiz.append(questionHTML);
count++;
}
}
// Add the quiz content to the page
$quizArea.append(quiz);
// Toggle the start button OR start the quiz if start button is disabled
if (plugin.config.skipStartButton || $quizStarter.length == 0) {
$quizStarter.hide();
plugin.method.startQuiz.apply (this, [{callback: plugin.config.animationCallbacks.startQuiz}]); // TODO: determine why 'this' is being passed as arg to startQuiz method
kN(key,3).apply (null, []);
} else {
$quizStarter.fadeIn(500, kN(key,3)); // 3d notch on key must be on both sides of if/else, otherwise key won't turn
}
internal.method.turnKeyAndGo (key, options && options.callback ? options.callback : function () {});
},
// Starts the quiz (hides start button and displays first question)
startQuiz: function(options) {
var key, keyNotch, kN;
key = internal.method.getKey (1); // how many notches == how many jQ animations you will run
keyNotch = internal.method.getKeyNotch; // a function that returns a jQ animation callback function
kN = keyNotch; // you specify the notch, you get a callback function for your animation
function start(options) {
var firstQuestion = $(_element + ' ' + _questions + ' li').first();
if (firstQuestion.length) {
firstQuestion.fadeIn(500, function () {
if (options && options.callback) options.callback ();
});
}
}
if (plugin.config.skipStartButton || $quizStarter.length == 0) {
start({callback: kN(key,1)});
} else {
$quizStarter.fadeOut(300, function(){
start({callback: kN(key,1)}); // 1st notch on key must be on both sides of if/else, otherwise key won't turn
});
}
internal.method.turnKeyAndGo (key, options && options.callback ? options.callback : function () {});
if (plugin.config.events &&
plugin.config.events.onStartQuiz) {
plugin.config.events.onStartQuiz.apply (null, []);
}
},
*** had to delete code because stackoverflow limits what I can put into a question,
here is the end of the slickQuiz file found at the link above:
plugin.init();
};
$.fn.slickQuiz = function(options) {
return this.each(function() {
if (undefined === $(this).data('slickQuiz')) {
var plugin = new $.slickQuiz(this, options);
$(this).data('slickQuiz', plugin);
}
});
};
})(jQuery);

Facebook Graph Call not working in Internet Explorer 9

I have a JavaScript function that I use to call the Facebook API and get a list of posts from a wall. In Firefox, Chrome and Safari this works with no issue, but in Internet Explorer 9 (I haven't tested below yet), it just doesn't do anything, the UI stays blocked, but I do not seem to get any messages that point to an error. I have a feeling it may have something to do with the JSON being returned and the Internet Explorer parser, but I can't be sure at this point.
After being pointed back to the Facebook SDK, I re-implemented using that (I am not sure why I left it before now), and it all seems to play nicely with Internet Explorer now.
Old Code
var getFeed = function (name, type, limit, accessToken, apiKey, containerId) {
var list_url = "https://graph.facebook.com/" + name + "/" + type + "?limit=" + limit + "&access_token=" + accessToken + "&api_key=" + apiKey;
var html = "";
displayHelper.blockUI(containerId, "Loading Feed");
$.getJSON(list_url, function (json) {
//Loop through and within the data array to retrieve the variables.
$.each(json.data, function (i, fb) {
var msg = (typeof (fb.message) != "undefined") ? fb.message : "";
var link = (typeof (fb.link) != "undefined") ? fb.link : "";
var pic = "";
// msg = (typeof(fb.story) != "undefined") ? fb.story : msg;
var type = (typeof (fb.type) != "undefined") ? fb.type : "";
var includeInOutput = true;
pic = getPicture(fb.from.id);
switch (type) {
case "story":
msg = fb.story;
break;
case "link":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.caption) != "undefined")
msg = fb.caption;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
else if (typeof (fb.name) != "undefined")
msg = fb.name;
break;
case "video":
case "photo":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
break;
case "status":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
break;
default:
includeInOutput = false;
break;
}
if (includeInOutput) {
//build html for this list item
html += '<dl class="fb-item">';
html += "<dt>" + fb.from.name + "</dt>";
html += (pic != '') ? '<dd class="img"><img src="' + pic + '" />' : '';
html += '<dd class="msg">' + msg + '</dd>';
/*html += '<a href="' + link + '" class="fb_link" target="_blank">'
+ msg + "(" + type + ")"
+ "</a>";*/
html += '<dd class="links">';
html += '<span>' + fuzzyTime(fb.created_time.replace(/-/g, '/')) + '</span>';
if (typeof (fb.actions) != "undefined") {
if (fb.actions[1].name == "Like")
html += "<a href='" + fb.actions[1].link + "' class='fb_link' target='_blank'>Like</a> - ";
if (fb.actions[0].name == "Comment")
html += "<a href='" + fb.actions[0].link + "' class='fb_link' target='_blank'>Comment</a>";
}
html += '</dd>';
html += "</dl>";
}
}); /* end .each */
//html += "</ul>";
$(containerId).html(html);
$(containerId).unblock();
}); /* end getJSON */
} /* end hetFeed
New Code - UPDATED again. The picture was not returning so I extracted the message and build parts into its own method and built the message on the call back of the get picture. Before I was doing it in a blocking way, just wrong! Hopefully this will help someone one day.
var postMessage = function (fb, containerId) {
FB.api("/" + fb.from.id + "/?fields=picture", {}, function (p) {
var pic = p.picture;
var msg = (typeof (fb.message) != "undefined") ? fb.message : "";
var link = (typeof (fb.link) != "undefined") ? fb.link : "";
var type = (typeof (fb.type) != "undefined") ? fb.type : "";
var includeInOutput = true;
var html = "";
switch (type) {
case "story":
msg = fb.story;
break;
case "link":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.caption) != "undefined")
msg = fb.caption;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
else if (typeof (fb.name) != "undefined")
msg = fb.name;
break;
case "video":
case "photo":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
break;
case "status":
if (typeof (fb.message) != "undefined")
msg = fb.message;
else if (typeof (fb.story) != "undefined")
msg = fb.story;
break;
default:
includeInOutput = false;
break;
}
if (includeInOutput) {
//build html for this list item
html += '<dl class="fb-item">';
html += "<dt>" + fb.from.name + "</dt>";
html += (pic != '') ? '<dd class="img"><img src="' + pic + '" />' : '';
html += '<dd class="msg">' + msg + '</dd>';
/*html += '<a href="' + link + '" class="fb_link" target="_blank">'
+ msg + "(" + type + ")"
+ "</a>";*/
html += '<dd class="links">';
html += '<span>' + fuzzyTime(fb.created_time.replace(/-/g, '/')) + '</span>';
if (typeof (fb.actions) != "undefined") {
if (fb.actions[1].name == "Like")
html += "<a href='" + fb.actions[1].link + "' class='fb_link' target='_blank'>Like</a> - ";
if (fb.actions[0].name == "Comment")
html += "<a href='" + fb.actions[0].link + "' class='fb_link' target='_blank'>Comment</a>";
}
html += '</dd>';
html += "</dl>";
}
$(containerId).append(html);
});
}
var getFeed = function (name, type, limit, accessToken, apiKey, containerId) {
var list_url = "https://graph.facebook.com/" + name + "/" + type + "?limit=" + limit + "&access_token=" + accessToken + "&api_key=" + apiKey;
var fullHtml = "";
helper.blockUI(containerId, "Loading Feed");
var path = "/" + name + "/" + type;
FB.api(path, { access_token: accessToken, api_key: apiKey, limit: limit }, function (json) {
console.log(json);
var data = json.data;
for (var i = 0, l = data.length; i < l; i++) {
var fb = data[i];
postMessage(fb, containerId);
} //End For
$(containerId).unblock();
});
} /* End getFeed */
You might want to try to use the sdk anyway, that way you can know better where exactly is the problem with your code in IE.
If you do this:
var path = name + "/" + type;
var params = limit == null ? {} : { limit: limit };
FB.api(path, "post", params, function(json) {
......
});
It should pretty much do the same as the code you posted (minus the actual handling of the results). If you try it and this works in IE then the problem was with how you communicated with facebook, otherwise it's in the part that handles the results from facebook.
One thing for sure, this approach (of using the sdk) is simpler and more elegant, not to mention that in this way, changes facebook are making on their on end won't affect you (in most cases).

How can I open with blank page on this rss javascript nor html?

I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'

Categories

Resources