Stop function on dialog open - javascript

have a question for you. I am loading a function that I want to stop once they click the sprite, which in turn opens a dialog.
How can I do this?
My jQuery to make a image pop up in specific coordinates:
(function fadeInDiv(){
var divs = $('#showSprite');
var fadeInTime = Math.floor(Math.random()*(3000-1000+1)+1000);
var fadeOutTime = Math.floor(Math.random()*(5000-1000+1)+1000);
var timeThere = Math.floor(Math.random()*(50-25+1)+25);
var elem = divs.eq(Math.floor(Math.random()*divs.length));
var whichCord = Math.floor(Math.random()*(6-1+1)+1);
var arrayDictionary = {
ary1: ["39","141"],
ary2: ["85","27"],
ary3: ["215","166"],
ary4: ["351","13"],
ary5: ["389","168"],
ary6: ["486","32"],
ary7: ["576","150"]
};
if (!elem.is(':visible')) {){
elem.fadeIn(Math.floor(Math.random()*fadeInTime),fadeInDiv);
elem.css({
'position':'absolute',
'left':arrayDictionary["ary"+whichCord][0]+'px',
'top':arrayDictionary["ary"+whichCord][1]+'px'
});
}
else {
elem.fadeOut(Math.floor(Math.random()*fadeOutTime),fadeInDiv)
.delay(timeThere);
}
})();
and my dialog:
$('#clickedSprite').dialog({
autoOpen: false,
title: 'What Do We Have Here?'
});
$('#sprite').click(function() {
var palID = $(this).attr('palID');
var petID = $(this).attr('petID');
var securePass = $(this).attr('securePass');
var timePassed = new Date().getTime() / 1000;
$.cookie("hashing", securePass);
$.cookie("timePassed", Math.round(timePassed));
$('#clickedSprite').dialog('open');
return false;
});

Use !$(".ui-dialog").length to check that there are no dialogs:
(function fadeInDiv() {
if(!$(".ui-dialog").length){
var divs = $('#showSprite');
var fadeInTime = Math.floor(Math.random() * (3000 - 1000 + 1) + 1000);
var fadeOutTime = Math.floor(Math.random() * (5000 - 1000 + 1) + 1000);
var timeThere = Math.floor(Math.random() * (50 - 25 + 1) + 25);
var elem = divs.eq(Math.floor(Math.random() * divs.length));
var whichCord = Math.floor(Math.random() * (6 - 1 + 1) + 1);
var arrayDictionary = {
ary1: ["39", "141"],
ary2: ["85", "27"],
ary3: ["215", "166"],
ary4: ["351", "13"],
ary5: ["389", "168"],
ary6: ["486", "32"],
ary7: ["576", "150"]
};
if (!elem.is(':visible')) {) {
elem.fadeIn(Math.floor(Math.random() * fadeInTime), fadeInDiv);
elem.css({
'position': 'absolute',
'left': arrayDictionary["ary" + whichCord][0] + 'px',
'top': arrayDictionary["ary" + whichCord][1] + 'px'
});
} else {
elem.fadeOut(Math.floor(Math.random() * fadeOutTime), fadeInDiv)
.delay(timeThere);
}
}
})();

Related

Calling functions from within functions JS

I'm writing a small battleships game, and I'm refactoring my code using Javascript Objects, a tool that I am not very familiar with. I would like to be able to call a function from within a function using objects, and I cannot seem to work out how to do this. The code is here:
<script>
var xPos;
var yPos;
var boatGrid = {
selectPos : function() {
console.log("it works"); //want to try calling function addNumber() here
for (boatNum = 1; boatNum < 4; boatNum++) {
xPos = Math.floor(Math.random() * 8);
yPos = Math.floor(Math.random() * 10 + 1);
}
},
buildBoat : function() {
console.log("this works too");
for (boatLen = 1; boatLen < 4; boatLen++) {
xPos = xPos++;
boatPos = "cell_" + xPos + "_" + yPos;
}
},
addNumber : function() {
document.getElementById("test2").innerHTML = "hello"; //debug line
}
}
The addNum() function is there as a debug.
You are almost there.
In your case boatGrid is an object and addNumber is one of it's method. so use this.addNumber()
var xPos;
var yPos;
var boatGrid = {
selectPos : function() {
console.log("it works"); //want to try calling function addNumber() here
this.addNumber(); // Changed here
for (boatNum = 1; boatNum < 4; boatNum++) {
xPos = Math.floor(Math.random() * 8);
yPos = Math.floor(Math.random() * 10 + 1);
}
},
buildBoat : function() {
console.log("this works too");
for (boatLen = 1; boatLen < 4; boatLen++) {
xPos = xPos++;
boatPos = "cell_" + xPos + "_" + yPos;
}
},
addNumber : function() {
//document.getElementById("test2").innerHTML = "hello"; //debug line
document.write('<pre>Add Number called</pre>')
}
}
boatGrid.selectPos();
jsfiddle
Use
this.addNumber();
Your code should look like this
selectPos : function() {
console.log("it works");
this.addNumber(); //want to try calling function addNumber() here
for (boatNum = 1; boatNum < 4; boatNum++) {
xPos = Math.floor(Math.random() * 8);
yPos = Math.floor(Math.random() * 10 + 1);
}
},
If you want to call boatGrid.selectPos() and call the addNumber function within the selectPos function, just add this.addNumber(); within the selectPos function.
selectPos : function() {
console.log("it works");
this.addNumber(); // <---- boatGrid calls addNumber()
for (boatNum = 1; boatNum < 4; boatNum++) {
xPos = Math.floor(Math.random() * 8);
yPos = Math.floor(Math.random() * 10 + 1);
}
}
When used within an object function, this refers to the object calling the function.
So to go with my original example, boatGrid calls selectPos, so this within the selectPos function refers to boatGrid.
So then this.addNumber() will have that boatGrid object call its addNumber function.

Bind event listener from outside function

How can I from the outside of my init function, fire off the reset function within init.
I want my reset function to reset all variables set from the collection of the images (3 in this case) which is bound 3 times. My example here isn't working I'm aware.
Here's my code:
document.getElementsByClassName('zoomer-start')[0].addEventListener('click', init);
document.getElementsByClassName('zoomer-reset')[0].addEventListener('click', reset);
function init() {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
(function() {
var image = images[i];
var zoomer = new Hammer(image);
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
var clicked = false;
var adjustScale = 1;
var adjustDeltaX = 0;
var adjustDeltaY = 0;
var currentScale = null;
var currentDeltaX = null;
var currentDeltaY = null;
zoomer.on('tap', function (e) {
if (!clicked) {
zoomer.get('pinch').set({enable: true});
zoomer.get('pan').set({enable: true, direction: Hammer.DIRECTION_ALL});
clicked = true;
} else {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
}
if (currentScale > 1) {
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
} else {
adjustScale = 2;
}
currentScale = adjustScale * e.scale;
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('pan pinch', function (e) {
currentScale = Math.max(1, Math.min(adjustScale * e.scale, 4));
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
var scaledX = ((((image.width * currentScale) / 2) - (image.width / 2)) / currentScale);
if (currentDeltaX > scaledX)
currentDeltaX = scaledX;
if (currentDeltaX < -scaledX)
currentDeltaX = -scaledX;
var scaledY = ((((image.height * currentScale) / 2) - (image.height / 2)) / currentScale);
if (currentDeltaY > scaledY)
currentDeltaY = scaledY;
if (currentDeltaY < -scaledY)
currentDeltaY = -scaledY;
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('panend pinchend', function () {
adjustScale = currentScale;
adjustDeltaX = currentDeltaX;
adjustDeltaY = currentDeltaY;
});
function reset() {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
currentScale = null;
currentDeltaX = null;
currentDeltaY = null;
image.style.transform = 'scale(' + 1 + ') translate3d(' + 0 + 'px, ' + 0 + 'px, 0)';
}
})();
}
}
To call function(s) from withinn scope you have to pass it somehow to the surronding scope. One possible example for Your code:
var resets = [];
function init() {
[...]
for (var i = 0; i < images.length; i++) {
(function() {
[...]
resets[i]=function reset() {
[...]
})
And then call them naively:
resets[0](); resets[1](); resets[2];
Or via:
resets.forEach(function(f) { f(); } );
Having your functions inside the init function gives them Private SCOPE only (can only be accessed from within the init function) To give them global scope you will have to move them outside of the init function which will require some code restructuring.
With the code as written, you can't. The reset function is entirely private to the code in the anonymous function inside init. Even other code in init can't access it, much less code outside init.
I say "it" above, but really, you have multiple reset functions, one for each image.
You could, of course, move your code trying to use it as a click handler into that anonymous function inside init. That's basically your only real option, other than creating an array or similar of reset functions that you expose outside init.
Thanks guys, I learned something today! Here's my working example. Really really neat:
var resets = [];
document.getElementsByClassName('zoomer-start')[0].addEventListener('click', init);
document.getElementsByClassName('zoomer-reset')[0].addEventListener('click', function () {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
resets[i]();
}
});
function init() {
var images = document.querySelectorAll('.zoomer-img');
for (var i = 0; i < images.length; i++) {
(function(i) {
var image = images[i];
var zoomer = new Hammer(image);
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
var clicked = false;
var adjustScale = 1;
var adjustDeltaX = 0;
var adjustDeltaY = 0;
var currentScale = null;
var currentDeltaX = null;
var currentDeltaY = null;
zoomer.on('tap', function (e) {
if (!clicked) {
zoomer.get('pinch').set({enable: true});
zoomer.get('pan').set({enable: true, direction: Hammer.DIRECTION_ALL});
clicked = true;
} else {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
}
if (currentScale > 1) {
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
} else {
adjustScale = 2;
}
currentScale = adjustScale * e.scale;
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('pan pinch', function (e) {
currentScale = Math.max(1, Math.min(adjustScale * e.scale, 4));
currentDeltaX = adjustDeltaX + (e.deltaX / currentScale);
currentDeltaY = adjustDeltaY + (e.deltaY / currentScale);
var scaledX = ((((image.width * currentScale) / 2) - (image.width / 2)) / currentScale);
if (currentDeltaX > scaledX)
currentDeltaX = scaledX;
if (currentDeltaX < -scaledX)
currentDeltaX = -scaledX;
var scaledY = ((((image.height * currentScale) / 2) - (image.height / 2)) / currentScale);
if (currentDeltaY > scaledY)
currentDeltaY = scaledY;
if (currentDeltaY < -scaledY)
currentDeltaY = -scaledY;
image.style.transform = 'scale(' + currentScale + ') translate3d(' + currentDeltaX + 'px, ' + currentDeltaY + 'px, 0)';
});
zoomer.on('panend pinchend', function () {
adjustScale = currentScale;
adjustDeltaX = currentDeltaX;
adjustDeltaY = currentDeltaY;
});
resets[i] = function reset() {
zoomer.get('pinch').set({enable: false});
zoomer.get('pan').set({enable: false});
clicked = false;
adjustScale = 1;
adjustDeltaX = 0;
adjustDeltaY = 0;
currentScale = null;
currentDeltaX = null;
currentDeltaY = null;
image.style.transform = 'scale(' + 1 + ') translate3d(' + 0 + 'px, ' + 0 + 'px, 0)';
}
})(i);
}
}

Pomodoro Clock's time doesn't work

I am currently working on Pomodoro Clock project, everything seems working on plus/minus buttons in both Session and Break but time itself is not working (in blue circle area), something is little missing, please see below.
var time = document.querySelector(".time");
var timerBody = document.querySelector(".timerBody");
var currentWork = document.querySelector(".currentWork");
var sessionLength = document.querySelector(".sessionLength");
var minusSessionLength = document.querySelector(".minus-sessionLength");
var plusSessionLength = document.querySelector(".plus-sessionLength");
var breakLength = document.querySelector(".breakLength");
var minusBreakLength = document.querySelector(".minus-breakLength");
var plusBreakLength = document.querySelector(".plus-breakLength");
var isLoop = false;
var isSession = true;
var Sound = new Audio('http://www.oringz.com/oringz-uploads/sounds-917-communication-channel.mp3');
function GetTime(timeString){
timeString = timeString.split(':');
var seconds = parseInt(timeString[0]) * 60 + parseInt(timeString[1]);
return seconds;
}
// Errors here
function setTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
var currentTime = GetTime(time.innerHTML);
minusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
if(STime - 1 >= 1)
STime--;
sessionLength.innerHTML = STime;
if(isSession) {
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
sessionLength.innerHTML = ++STime;
if(isSession){
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
minusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
if(BTime - 1 >= 1) {
BTime--;
breakLength.innerHTML = BTime;
}
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
breakLength.innerHTML = ++BTime;
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
var loop;
timerBody.addEventListener('click', function(event){
if(isLoop) {
clearInterval(loop);
currentWork.innerHTML = 'Paused';
isLoop = !isLoop;
}
else {
currentWork.innerHTML = isSession ? 'Session' : 'Break';
loop = setInterval(function() {
time.innerHTML = SetTime(--currentTime);
if(currentTime < 1) {
if(isSession) {
currentWork.innerHTML = 'Break';
time.innerHTML = breakLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#80FF80";
Sound.play();
var isBreakTitle = true;
var changeTitle = setInterval(function(){
document.title = isBreakTitle ? '***Break!***' : '************';
isBreakTitle = !isBreakTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
else {
currentWork.innerHTML = 'Session';
time.innerHTML = sessionLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#F64141";
Sound.play();
var isSessionTitle = false;
var changeTitle = setInterval(function() {
document.title = isSessionTitle ? '***Session!****' : '************';
isSessionTitle = !isSessionTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
}
}, 1000);
isLoop = !isLoop;
}
});
Here's mispelling mistake which should be "SetTime"
function SetTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
Hope that helps to your future issues.

how to make synchronous call to json data from angularjs

I am calling some data from a JSON file in AngularJS but due to the asynchronous call the code is moving to other step before receiving the data so that is causing an error.
I used $http.get
$http.get('job.json').success(function (response) {
$scope.big = response;
});
Can you suggest some synchronous method to call json data which is
{
"days": [{
"dayname": "Sun,23 Aug 2015",
"date": "2015-08-23",
"hours": "hoursArray(array24)"
}, {
"dayname": "Mon,24 Aug 2015",
"date": "2015-08-24",
"hours": "hoursArray(array24)"
}, {
"dayname": "Tue,25 Aug 2015",
"date": "2015-08-25",
"hours":"hoursArray(array24)"
}, {
"dayname": "Wed,26 Aug 2015",
"date": "2015-08-26",
"hours": "hoursArray(array24)"
}]
}
this is the jquery file i am using
(function($) {
$.fn.schedule = function(options) {
var methods = {
init : function(ele, opt) {
//methods.currentdate = methods.now.getFullYear() + "Engine Change" + methods.now.getMonth() + "Engine Change" + methods.now.getDate();
methods.currentdate = methods.now.getFullYear() + "-" + methods.now.getMonth() + "-" + methods.now.getDate();
// $("#scheduleAllDays > *").each(function(){
// var item = $(this);
// $("#scheduleAllDays").width($("#scheduleAllDays").width()+item.width());
// });
// $("#scheduleAllDays").width($("#scheduleAllDays").width());
ele.find("[data-row]").each(function() {
var drow = $(this), drowset = $("[data-row='" + drow.data("row") + "']");
var maxheight = methods.elesMaxHeight(drowset);
drowset.height(maxheight);
});
methods.allocateDurations(ele);
$("#scheduleContentInner", ele).css("min-height", $(".schedule-drag-wrap", ele).innerHeight());
},
elesMaxHeight : function(ele) {
var heights = $(ele).map(function() {
return $(this).height();
}).get();
return Math.max.apply(null, heights);
},
allocateDurations : function(ele) {
methods.flightdata = {
routes : {}
};
ele.find("[data-flight-row]").each(function(i, ival) {
var flight = $(this);
methods.flightdata.routes["row" + i] = [];
flight.find("[data-flight-record]").each(function() {
var currentFlight = $(this), flightrecord = methods.makeStringToObject(currentFlight.data("flight-record"));
flightrecord.element = currentFlight;
methods.flightdata.routes["row" + i].push(flightrecord);
});
});
methods.positionSet(ele);
},
positionSet : function(ele) {
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var divider = $(".schedule-h-divider");
dayelement.each(function(i, ival) {
var dayele = $(this), dividerele = divider.eq(i);
dividerele.css({
top : $("#scheduleAllDays").height(),
left : dayele.offset().left - 104
});
});
for (var i in methods.flightdata.routes) {
var iobj = methods.flightdata.routes[i];
for (var j in iobj) {
var jobj = iobj[j];
var duration = jobj.duration, width = Number(methods.hmtosec(duration, ".") * perSecondsWidth);
var parent = jobj.element.parent();
jobj.element.css({
// position : "relative",
width : width + "px",
overflow : "hidden",
"white-space" : "nowrap"
}).parent().css({
// width : width+"px",
// overflow : "hidden"
// position:"absolute",
left : (j==0)?0:parent.prev().position().left+parent.prev().width()
});
}
}
methods.dragInit(ele);
},
setCurrentTimeMarker : function(ele) {
var marker = $(".schedule-current-time-marker");
var markerpills = $(".schedule-time-marker-pills");
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var currentdate = new Date();
var format = currentdate.getFullYear() + "Engine Change" + currentdate.getMonth() + "Engine Change" + currentdate.getDate();
var currentdateele = $("#scheduleAllDays").find("[data-date='" + format + "']");
var days = (currentdateele.index()), seconds = ((days * 24) * 60) * 60;
seconds = seconds + methods.hmtosec(currentdate.getHours() + "." + currentdate.getMinutes(), ".");
marker.stop().animate({
top : $("#scheduleAllDays",ele).height()-53,
left : (seconds * perSecondsWidth) - (marker.width() / 2)
}, 1000, "swing");
markerpills.html(currentdate.getHours() + ":" + currentdate.getMinutes());
methods.markermove = setInterval(function() {
currentdate = new Date();
marker.css({
left : marker.position().left + perSecondsWidth
}, "fast", "swing");
markerpills.html(methods.makezerodigit(currentdate.getHours()) + " : " + methods.makezerodigit(currentdate.getMinutes()));
// methods.schedulemove(ele,perSecondsWidth);
}, 1000);
},
schedulemove : function(ele,seconds) {
var dragwrap = ele.find(".schedule-drag-wrap");
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragwrap.width() - ($(window).width() - routewidth));
if (Math.abs(dragwrap.position().left) < Math.abs(maxleft)) {
dragwrap.css({
left : (dragwrap.position().left - (dragwrap.width)) + "px"
});
}
},
makezerodigit : function(digit) {
return (String(digit).match(/^[0-9]$/)) ? "0" + digit : digit;
},
dragInit : function(ele) {
var currentdaycol = $("[data-date='" + methods.currentdate + "']");
ele.find(".schedule-drag-wrap").css({
left : -(currentdaycol.position().left - 50) + "px"
}).animate({
left : -currentdaycol.position().left - 0 + "px"
}, 1000, "swing", function() {
methods.drag(ele);
methods.setCurrentTimeMarker(ele);
});
},
drag : function(ele) {
methods.move = null;
$(".schedule-drag-wrap", ele).on("mousedown", function(e) {
var dragele = $(this), position = dragele.position();
methods.move = {
x : e.pageX,
y : e.pageY,
left : position.left
};
}).on("mouseup mouseleave", function(e) {
var dragele = $(this);
if (methods.move) {
methods.move = null;
dragele.removeClass("userselect-none cursor-move");
}
}).on("mousemove", function(e) {
var dragele = $(this), position = dragele.position(), movedx, drag = true;
if (methods.move) {
methods.curmove = {
x : e.pageX,
y : e.pageY
};
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragele.width() - ($(window).width() - routewidth));
var xcondition = (methods.move.x > methods.curmove.x);
dragele.addClass("userselect-none cursor-move");
if (position.left <= maxleft && xcondition) {
drag = false;
dragele.css({
left : maxleft
});
}
if (position.left > -10 && !xcondition) {
drag = false;
dragele.css({
left : 0
});
}
if (drag) {
//if direction right to left
movedx = methods.move.left + (methods.curmove.x - methods.move.x);
dragele.css({
left : movedx
});
}
}
});
},
now : new Date(),
currentdate : "",
hmtosec : function(hours, identy) {
var s = (hours.match(/\./)) ? hours.split(identy) : [hours, 0], h = s[0], m = s[1];
h = (Number(h)) ? (h * 60) * 60 : 0;
m = (m == 0) ? 0 : m * 60;
return Number(h + m);
},
makeStringToObject : function(string) {
var loc_string = String(string).split("|");
var output = {};
for (var i in loc_string) {
var keyvalue = loc_string[i].split("~");
output[keyvalue[0]] = keyvalue[1];
}
return output;
}
};
return this.each(function() {
methods.init($(this), $.extend({}, $.fn.schedule.setting, options));
});
};
$.fn.schedule.setting = {};
})(jQuery);
and this is the error i am getting
Uncaught TypeError: Cannot read property 'left' of undefined
In service: var deferred = $q.defer();
$http.get('job.json')
.success(function(response) {
defer.resolve(response);
}).error(function(error){
console.log(error);
})
return deferred.promise;
In controller:
var p=<serviceCall>
p.then(function(s){
$scope.ans=s;
})
The $q is used for getting synchronous response.for more details:https://docs.angularjs.org/api/ng/service/$q
You can't do a synchronous HTTP request, since the reponse (in your case it is the JSON file) can not be loaded instantly. However, $http.get returns a promise which is resolved when the request completes. You should do everything you want to do as soon as the JSON file has loaded inside the then-block of the promise.
$http.get('job.json').then(function (response) {
$scope.big = response;
// Do anything else you need to after JSON has been loaded.
});
Using promise.then you can update your value.
var promise=$http.get('job.json');
promise.then(function(result){
$scope.big=response;
});
alternative way
function getObj(callback){
$http.get('job.json').success(callback);;
}
getObj(function(result){
console.log(result)
// add your jquery code
})

JavaScript SetInterval () is not working after clicking

Hi I have wrote this code and it suppose to move the object every 3000 ms after clicking on the object, but some how the time its not working, can anyone tell me what I am doing wrong, I am just learning javascript; thank you very much
function move1() {
var im1 = document.images[0];
im1.onclick = function() {
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
}
function move2() {
var im2 = document.images[1];
im2.onclick = function() {
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
}
window.onload = function() {
setInterval(move1, 100);
setInterval(move2, 3000);
}
You're doing it the other way round. Every 3000ms you make it possible to move the image by 1px when clicking on it.
function move(el, ms, px) {
/* moves the el every ms by px
returns the interval id to clear the movement */
return setInterval(function() {
el.style.left = parseInt(el.style.left) + px + "px";
}, ms);
}
window.onload = function() {
var im0 = document.images[0];
var im1 = document.images[1];
im0.onclick = function() {
move(im0, 100, 1);
};
im1.onclick = function() {
move(im1, 3000, 10);
};
}
Your move function registers the image on click, but doesn't actually do any moving until the user clicks. What you want is more like this:
function move1() {
var im1 = document.images[0];
im1.style.left = parseInt(im1.style.left) + 1 + "px";
}
function move2() {
var im2 = document.images[1];
im2.style.left = parseInt(im2.style.left) + 10 + "px";
}
window.onload = function() {
var im2 = document.images[1];
im2.onclick = function() {
setInterval(move2, 3000);
}
im1.onclick = function() {
setInterval(move1, 100);
}
}

Categories