Passing function response (callback) as variable to another function - javascript

See below. I'm trying to pass function(response) as a variable to be used in a progress bar function. That's the idea anyways. How do I call back the data = response to the var i = data in this case?
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var data = 0;
setInterval(function () {
$('#divToRefresh').load('usercounter.php', function (response) {
data = response;
});
}, 100);
window.onload = function () {
var Animator = new function () {
var parent = document.getElementById('container');
var element = document.getElementById('test');
var target = document.getElementById('message');
this.move = function () {
var i = data;
var width = 0;
var timer = window.setTimeout(function () {
i += 1;
element.style.width = width + i + 'px';
}, 10);
};
};
Animator.move();
};
});

Not sure how your animator works or how those elements interact, but I'm guessing your goal is to call move periodically to refresh it's current status? So put that in the interval, and then make the retrieval of the count part of the animation. Not sure if that'll work for your scenario.
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
window.onload = function () {
var Animator = new function () {
var parent = document.getElementById('container');
var element = document.getElementById('test');
var target = document.getElementById('message');
this.move = function () {
$('#divToRefresh').load('usercounter.php', function (response) {
var i = response;
var width = 0;
var timer = window.setTimeout(function () {
i += 1;
element.style.width = width + i + 'px';
}, 10);
});
};
};
Animator.move();
setInterval(function () {
Animator.move();
}, 100);
};
});

Related

javascript DOM object (window) extended property is null on page reload after being idle

I have a custom extended property attached to the window object in JavaScript as follows:
Community.js
(function (window, document, $) {
'use strict';
var containerScrollPositionOnHideList = [];
var scrollToTopOnShowContainerList = [];
var userProfileInfo = {};
window.Community = $.extend({
//init
init: function () {
var Site = window.Site;
Site.run();
this.enableHideShowEventTrigger();
},
setUserInfo: function (userObj) {
if (UtilModule.allowDebug) { debugger; }
window.localStorage.setItem('userInfo', JSON.stringify(userObj));
var d = new $.Deferred();
$.when(this.initUserProfile(userObj.UserId)).done(function () {
d.resolve("ok");
});
},
getUserInfo: function () {
var userJson = window.localStorage.getItem('userInfo');
var userObj = JSON.parse(userJson);
return userObj;
},
})(window, document, jQuery);
The problem is that this extension property window.Community is null in certian scenarios when i refresh the page which i am going to describe below along with flow of code.
and here is a module in JavaScript to force reload scripts even if they are cached every time the page is refreshed as my code heavily depends on javascript calls so I just enabled it to make sure while I am still writing the code page reloads every time, the code is below as follows:
Util.js
var UtilModule = (function () {
var allowDebug = false;
var currentVersion = 0;
var properlyLoadScript = function (scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function () {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript(scriptPath)).done(function () {
callBackAfterLoadScript();
d.resolve("ok");
});
}
else {
console.log('Community loaded already and running now : ' + scriptPath);
callBackAfterLoadScript();
}
return d.promise();
};
var forceReloadScript = function (scriptPath) {
if (UtilModule.allowDebug) { debugger; }
var d = $.Deferred();
initCurrentVersion();
var JSLink = scriptPath + "?version=" + currentVersion;
var JSElement = document.createElement('script');
JSElement.src = JSLink;
JSElement.onload = customCallBack;
document.getElementsByTagName('head')[0].appendChild(JSElement);
function customCallBack() {
d.resolve("ok");
}
return d.promise();
};
var enableDebugger = function () {
allowDebug = true;
};
var disableDebugger = function () {
allowDebug = false;
};
var debugBreakPoint = function () {
if (allowDebug) {
}
};
var initCurrentVersion = function () {
if (currentVersion == 0) {
var dt = new Date();
var ttime = dt.getTime();
currentVersion = ttime;
}
};
var getCurrentVersion = function () {
return currentVersion;
};
return {
forceReloadScript,
properlyLoadScript,
enableDebugger,
disableDebugger,
debugBreakPoint,
allowDebug,
getCurrentVersion
};
})();
Note: I have made deferred objects to resolve only when the JSElement.onload has been called successfully. This step was taken just for testing purpose to make sure that I am not missing something before reaching a point to call the method where I am getting an error.
After that the code where I load scripts using UtilModule in my layout file look like as below:
_Layout.cshtml
<script src = "~/Scripts/Application/Modules/Util.js" ></script>
<script>
$.when(
UtilModule.properlyLoadScript('/Scripts/Application/Community.js', () => {
// Community.init() was supposed to be called here but i was still getting the error so i implemented this using promise that is returned from properlyLoadScript and call Community.init() further in .done callback to make sure that script is properly loading till this point.
//window.Community.init();
})
).done(function() {
window.Community.init();
});
</script>
#RenderSection("scripts", required: false)
Now coming to my main file where My index file is executing having (_layout.chsmtl) as parent layout
is
Index.cshtml
#{
ViewBag.Title = "My Blog";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<article id="BlogPage" style="margin: 5px;">
</article>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$.when(UtilModule.properlyLoadScript('/Scripts/Application/Modules/Blog.js', () => {
})).done(function () {
BlogModule.init();
});
});
//});
</script>
}
from what I know is that #section scripts is executed only once all the scripts in the layout page are loaded first so seems like a safe place to initialize the code which is dependent on some script in _Layout.HTML file and further enclosed with $(document).ready() for testing just to make sure that this script loads after everything else is loaded already.
Note: I am running all this code in in-cognito mode in chrome so nothing is cached while this code is running
now my Blog.js file looks like as below
var BlogModule = (function () {
var moduleReference = this;
var PageId = "#BlogPage ";
var currentUser;
var BlogPostList = [];
var blogPostInfo = {};
//init
var init = function () {
if (UtilModule.allowDebug) { debugger; }
//This is where the problem happens
console.log(window.Community);
console.log(window.Community.getUserInfo());
currentUser = window.Community.getUserInfo();
initBlogInformation();
//window.Community.registerModule(BlogModule);
if (Object.keys(window.Community.getUserProfileObject()) <= 0) {
$.when(window.Community.initUserProfile(currentUser.UserId)).then(function () {
$.when(initBlogInformation()).done(function () {
//debugger;
console.log(BlogPostList);
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
});
}
else {
$.when(initBlogInformation()).done(function () {
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
}
};
var loadBlogIndexMenuWidget = function () {
if (UtilModule.allowDebug) { debugger; }
};
var loadBlogPostWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogPostWidget";
widgetOptions.container = PageId + "#BlogPostWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
}
var loadBlogViewWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogViewWidget";
widgetOptions.container = PageId + "#BlogViewWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var loadBlogCommentsWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogCommentsWidget";
widgetOptions.container = PageId + "#BlogCommentsWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var initBlogList = function () {
$.when(getBlogPosts()).then(function (results) {
if (UtilModule.allowDebug) { debugger; }
BlogPostList = results.Record;
console.log(BlogPostList);
});
};
var getBlogPosts = function () {
if (UtilModule.allowDebug) { debugger; }
var d = new $.Deferred();
var uri = '/Blog/GetBlogPosts?userId=' + currentUser.UserId;
$.post(uri).done(function (returnData) {
if (UtilModule.allowDebug) { debugger; }
if (returnData.Status == "OK") {
BlogPostList = returnData.Record;
BlogPostList.map(x => {
if (UtilModule.allowDebug) { debugger; }
x.UserName = window.Community.getUserProfileObject().UserName;
if (x.Comments != null) {
x.CommentsObject = JSON.parse(x.Comments);
x.CommentsCount = x.CommentsObject.length;
}
});
console.log(returnData.Record);
d.resolve("ok");
} else {
window.Community.showNotification("Error", returnData.Record, "error");
d.resolve("error");
}
});
return d.promise();
};
var initBlogInformation = function () {
//debugger;
var d = $.Deferred();
getBlogPosts().then(getBlogModelTemplate()).then(function () {
d.resolve("ok");
});
return d.promise();
};
//Get Blog Model
var getBlogModelTemplate = function () {
var d = new $.Deferred();
var uri = '/Blog/GetBlogModel';
$.post(uri).done(function (returnData) {
blogPostInfo = returnData.Record;
d.resolve("ok");
});
return d.promise();
};
return {
init: init,
};
})();
The error I have highlighted below
so the problem is in init function of BlogModule which is BlogModule.init() the page is idle for too long and I reload it I get the following error:
cannot call
window.Community.getUserInfo() of undefined implying that community is undefied
after couple of refreshes its fine and the issue doesn't happen unless I change reasonable portion of code for js files to be recompiled again by browser or the browser is idle for too long and I am not able to understand what is triggering this issue.
below is log from console
p.s. error occurs more repeatedly if i refresh page with f5 but happens rarely if i refresh page with ctrl + f5
Please any help would be of great value
Answering my own question, took a while to figure it out but it was a small mistake on my end just fixing the following function in Util.js fixed it for me
var properlyLoadScript = function(scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function() {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript('/Scripts/Application/Community.js')).done(function() {
//debugger;
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
d.resolve("ok");
});
} else {
console.log('Community loaded already and running now : ' + scriptPath);
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
}
return d.promise();
};

Attach varriable to a api object

So I get multiple objects from a REST API.
I get the data via AJAX like this:
var APICaller = (function () {
let endpoint = "https://jsonplaceholder.typicode.com/";
function api_call(method, url, data, callback) {
$.ajax({
url: url,
method: method,
data: data,
success: callback
});
}
function get_users(callback) {
let method = "GET";
let url = endpoint + "users";
let data = {};
api_call(method, url, data, callback);
}
return {
get_users: get_users,
};
})();
I am rolling 3 dices, and the total values of these 3 dices should be attached to each user so i can order the "scoreboard" after the total value.
I wonder if there is any way to attach the variable totalamount to every user?
Thanks in advace!
EDIT:
Currently i am getting all the users from the api.
This is the rest of my code withing this topic:
var Game = (function () {
var dice_total;
//Function for when the dice rolls.
function roll_dice() {
var value1 = $(".val1");
var value2 = $(".val2");
var value3 = $(".val3");
var v1 = Math.floor(Math.random() * 6) + 1;
var v2 = Math.floor(Math.random() * 6) + 1;
var v3 = Math.floor(Math.random() * 6) + 1;
value1.html(v1);
value2.html(v2);
value3.html(v3);
dice_total = v1 + v2 + v3;
}
return {
roll_dice: roll_dice
};
})();
var EventHandlers = (function () {
function init() {
var currentPlayer;
APICaller.get_users(on_get_users_success);
function on_get_users_success(response) {
//For each user in the API
$.each(response, function (i, user) {
$("#my-list").append('<li class="list-li"><a class="list-a">' + user.name + '</a></li>');
//Create the divs and p tags
$("#dice_value").append('<div class="val_div"> <p class="val1"></p> <p class="val2"></p> <p class="val3"></p></div>');
});
//change information
$("#info-txt").text("Välj en spelare!");
}
// On klick on a user make klicked user your own player.
$("#my-list").on('click', '.list-a', function () {
currentPlayer = this.text;
$("#info-txt").text("Tryck på spela knappen för att börja spelet!");
$("#currentPlayer-div").animate({
height: '300px',
opacity: '1'
});
$("#currentPlayer-h3").text(currentPlayer);
});
// On klick of the play button
$("#startGame-button").click(function () {
$().animate();
$("#currentPlayer-div").animate({
height: '150px'
});
$("#startGame-button").animate({
opacity: '0'
});
$("#dice_value").animate({
opacity: '1'
});
Game.roll_dice();
});
// $(".button-to-hide").click(function (){
// $(this).hide();
// });
// $("#show-all-buttons").click(function (){
// $(".button-to-hide").show();
// });
// $("#btn-edit-text").click(function (){
// var value = $("#my-input").val();
// $("p").html(value);
// });
}
return {
init: init,
}
})();
var DocumentEdit = (function () {
return {
}
})();
$(document).ready(function () {
EventHandlers.init();
});
Hope that describes it.

Ajax call doesn't work after success

I have a problem with ajax call after success.
I am trying to call my following javascript codes:
function imgResize($, sr) {
var debounce = function(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this,
args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn) {
return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
};
};
//CALL ON PAGE LOAD OR ANY TIME YOU WANT TO USE IT
imgResize(jQuery, 'smartresize');
/* Wait for DOM to be ready */
// Detect resize event
$(window).smartresize(function() {
// Set photo image size
$('.photo-row').each(function() {
var $pi = $(this).find('.photo-item'),
cWidth = $(this).parent('.photo').width();
// Generate array containing all image aspect ratios
var ratios = $pi.map(function() {
return $(this).find('img').data('org-width') / $(this).find('img').data('org-height');
}).get();
// Get sum of widths
var sumRatios = 0,
sumMargins = 0,
minRatio = Math.min.apply(Math, ratios);
for (var i = 0; i < $pi.length; i++) {
sumRatios += ratios[i] / minRatio;
};
$pi.each(function() {
sumMargins += parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
});
// Calculate dimensions
$pi.each(function(i) {
var minWidth = (cWidth - sumMargins) / sumRatios;
$(this).find('img')
.height(Math.floor(minWidth / minRatio))
.width(Math.floor(minWidth / minRatio) * ratios[i]);
});
});
});
/* Wait for images to be loaded */
$(window).load(function() {
$(".photo").each(function() {
var imgGrab = $(this).find('.photo-item');
var imgLength = imgGrab.length;
for (i = 0; i < imgLength; i = i + 3) {
imgGrab.eq(i + 1)
.add(imgGrab.eq(i + 1))
.add(imgGrab.eq(i + 2))
.wrapAll('<div class="photo-row"></div>');
}
$(this).find(".photo-item").each(function() {
if ($(this).parent().is(":not(.photo-row)")) {
$(this).wrap('<div class="photo-row"></div>');
}
});
// Store original image dimensions
$(this).find('.photo-item img').each(function() {
$(this)
.data('org-width', $(this)[0].naturalWidth)
.data('org-height', $(this)[0].naturalHeight);
});
});
$(window).resize();
});
And here is my ajax code for LOAD MORE POST
$('body').on("click",'.morep', function(event) {
event.preventDefault();
var ID = $(this).attr("id");
var P_ID = $(this).attr("rel");
var URL = $.base_url + 'more_post.php';
var dataString = "lastpid=" + ID + "&post_id=" + P_ID;
if (ID) {
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
beforeSend: function() {
$("#more" + ID).html('<img src="loaders/ajaxloader.gif" />');
},
success: function(html) {
$("div.post-content").append(html);
$("#more" + ID).remove();
imgResize(jQuery, 'smartresize');
}
});
} else {
$("#more").html('FINISHED');
}
return false;
});
The ajax should call imgResize(jQuery, 'smartresize'); but it is not working. What I am missing here anyone can help me here ?

How to pause a .scrollTop() animation on mouseover? (jsfiddle included)

I am using the following jquery code to create a slow scrolling animation.
http://jsfiddle.net/fhj45f21/
Unfortunately I am having difficulties pausing the animation on mouse over. Could someone please have a look and give me a hint?
function Scroller(y){
this.times = 0;
this.moveInter = 0;
this.backInter = 0;
this.moveBack = function () {
var self = this;
clearInterval(this.moveInter);
this.backInter = setInterval(function () {
self.times -= 5;
y.scrollTop(self.times);
if (self.times == 0) {
return self.startMove();
}
}, 1);
}
this.move = function() {
var self = this;
this.moveInter = setInterval(function () {
self.times++;
y.scrollTop(self.times);
if (self.times == 1200) {
return self.moveBack();
}
}, 50);
}
this.startMove = function() {
this.times = 0;
var self = this;
if (this.backInter != null) {
clearInterval(this.backInter);
}
window.setTimeout(function () {
self.move();
}, 1000);
}
}
jQuery('.textBox').each(function () {
y = jQuery(this);
var scroller = new Scroller(y);
scroller.startMove();
});
Thanks a bunch!
Here you go: http://jsfiddle.net/nxk4vseq/
add an y.hover handler with functions for mousein and mouseout
var scrl=this;
y.hover(function(){
clearInterval(scrl.moveInter);
},function(){
scrl.move();
});

ClearInterval undefined when button clicked

Suppose I have a few buttons and when they are clicked they trigger certain setInterval, but when I clicked on different button the previous setInterval doesn't clear or it say it is undefined.
example:
$("#button1").click(function () {
var url = "xxx";
var min = "yyy";
getGraphCredentials3(min,url);
var onehour = setInterval(function () {
getGraphCredentials3(min,url);
}, 5000);
clearInterval(twohour);
});
$("#button2").click(function () {
var url = "zzz";
var min = "uuu";
getGraphCredentials3(min,url);
var twohour = setInterval(function () {
getGraphCredentials3(min,url);
}, 5000);
clearInterval(onehour);
});
can anyone help please?
much appreciated
The scope of the onehour and twohour functions is the function in which they're declared, so they're not visible from the other callback.
You must declare your variables in a common scope. Do this :
var onehour, twohour;
$("#button1").click(function () {
var url = "xxx";
var min = "yyy";
getGraphCredentials3(min,url);
onehour = setInterval(function () {
getGraphCredentials3(min,url);
}, 5000);
clearInterval(twohour);
});
$("#button2").click(function () {
var url = "zzz";
var min = "uuu";
getGraphCredentials3(min,url);
twohour = setInterval(function () {
getGraphCredentials3(min,url);
}, 5000);
clearInterval(onehour);
});
Variable onehour and twohour are local to the function. If you declare them globally, it should work fine.

Categories