Update data in matrix of cells - javascript

This code implements a 60 cell spreadsheet, 6x10 rows,columns. At the end of each row are two labels, one for row total and for running total. The main issue here is how to update the row and running total labels when the calc button is pressed.
I would also like to move the button from the bottom of the scrollview to the bottom of the window where it's always visible. Another view for buttons at the bottom?
Ti.include("toast.js"); // 3rd-party code; displays notifications
var i=0;
var r=0;
var rows = 10;
var columns = 6;
left = ["0%","12%","24%","36%","48%","60%"];
Titanium.UI.setBackgroundColor('#000');
var win1 = Titanium.UI.createWindow({
title:'Target 1',
exitOnClose: true,
backgroundColor:'#fff'
});
win1.addEventListener('androidback' , function(e){
win1.close();
var activity = Titanium.Android.currentActivity;
activity.finish();
});
var scrollView1 = Ti.UI.createScrollView({
bottom:120,
contentHeight: 'auto',
layout: 'vertical'
});
if (Ti.UI.Android){
win1.windowSoftInputMode = Ti.UI.Android.SOFT_INPUT_ADJUST_PAN;
}
var buttonCalc = Titanium.UI.createButton({
title: 'Calc',
top: 10,
width: 100,
height: 50,
left: "10%"
});
var lbAttrs1 = {
text: "000",
left: "74%",
color:'#000',width:'auto',height:'auto',textAlign:'left',
font:{fontSize:24,fontWeight:'regular'}
};
var lbAttrs2 = {
text: "000",
left: "88%",
color:'#000',width:'auto',height:'auto',textAlign:'left',
font:{fontSize:24,fontWeight:'regular'}
};
var baseAttrs = {
borderStyle : Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
keyboardType: Titanium.UI.KEYBOARD_NUMBERS_PUNCTUATION,
maxLength: 2,
top: 10,
height: 60,
value: "",
width: '12%',
color : '#000000'
};
var tfields = [];
var labels1 = [];
var labels2 = [];
buttonCalc.addEventListener('click',function(e)
{
var a = 0;
var b = 0;
for (j=0;j<rows;j++)
{
a = 0;
for (i=0;i<columns;i++)
a = parseInt(tfields[j][i].value) + a;
b = b + a;
labels1[j] = a.toString();
labels2[j] = b.toString();
}
for (j=0;j<rows;j++)
alert( labels1[j]+' '+labels2[j]+ ' ' + j.toString());
});
function createRow1(i) // start create row
{
row1 = Ti.UI.createView({
backgroundColor: 'white',
borderColor: '#bbb',
borderWidth: 1,
width:'100%', height: 70,
top: 0, left: 0 });
var tfield1 = [];
var label1 = [];
var label2 = [];
for (i=0;i<columns;i++)
{
tfield1[i] = Ti.UI.createTextField(baseAttrs);
label1[i] = Ti.UI.createLabel(lbAttrs1);
label2[i] = Ti.UI.createLabel(lbAttrs2);
}
tfield1[0].addEventListener('change', function()
{
if (tfield1[0].value > 10)
{
tfield1[0].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[1].addEventListener('change', function()
{
if (tfield1[1].value > 10)
{
tfield1[1].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[2].addEventListener('change', function()
{
if (tfield1[2].value > 10)
{
tfield1[2].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[3].addEventListener('change', function()
{
if (tfield1[3].value > 10)
{
tfield1[3].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[4].addEventListener('change', function()
{
if (tfield1[4].value > 10)
{
tfield1[4].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[5].addEventListener('change', function()
{
if (tfield1[5].value > 10)
{
tfield1[5].value = "";
showMessageTimeout("More than 10.",15);
}
});
tfield1[0].left = left[0];
tfield1[1].left = left[1];
tfield1[2].left = left[2];
tfield1[3].left = left[3];
tfield1[4].left = left[4];
tfield1[5].left = left[5];
for (i=0;i<columns;i++)
{
row1.add(tfield1[i]);
row1.add(label1[i]);
row1.add(label2[i]);
}
;
tfields.push(tfield1);
labels1.push(label1);
labels2.push(label2);
return row1;
} /// end of createrow1
for(i = 0; i < rows; i++){
row1 = createRow1(i);
scrollView1.add(row1);
}
win1.add(scrollView1);
scrollView1.add(buttonCalc);
// win1.add(buttonCalc);
win1.open();

Point 1.
That is a typo, you should substitute each occurrence of labels1[j] and labels2[j] to labels1[j].text and labels2[j].text respectively:
buttonCalc.addEventListener('click',function(e)
{
var a = 0;
var b = 0;
for (j=0;j<rows;j++)
{
a = 0;
for (i=0;i<columns;i++){
var newValue = parseInt(tfields[j][i].value);
if(!isNaN(newValue) && typeof(newValue) === 'number')
a = newValue + a;
}
b = b + a;
labels1[j].text = a.toString();
labels2[j].text = b.toString();
}
for (j=0;j<rows;j++)
Ti.API.info( labels1[j].text +' '+labels2[j].text + ' ' + j.toString());
});
And also it must be changed these parts:
function createRow1(i) // start create row
{
...
for (i=0;i<columns;i++)
{
tfield1[i] = Ti.UI.createTextField(baseAttrs);
}
label1 = Ti.UI.createLabel(lbAttrs1); //there is only one per row
label2 = Ti.UI.createLabel(lbAttrs2); //there is only one per row
...
for (i=0;i<columns;i++)
{
row1.add(tfield1[i]);
}
row1.add(label1); //there is only one per row
row1.add(label2); //there is only one per row
tfields.push(tfield1);
labels1.push(label1);
labels2.push(label2);
return row1;
} /// end of createrow1
Point 2.
you can do it this way:
var scrollView1 = Ti.UI.createScrollView({
top:0,
height:'60%', //Put your desired value here
contentHeight: 'auto',
layout: 'vertical'
});
...
var buttonCalc = Titanium.UI.createButton({
title: 'Calc',
top: '70%', // Put your desired value here greater than scrollView1.height
width: 100,
height: 50,
left: "10%"
});
...
win1.add(scrollView1);
//scrollView1.add(buttonCalc);
win1.add(buttonCalc);
Extra point.
you need to set softKeyboardOnFocus property in your baseAttrs:
var baseAttrs = {
borderStyle : Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
keyboardType: Titanium.UI.KEYBOARD_NUMBERS_PUNCTUATION,
softKeyboardOnFocus: Titanium.UI.Android.SOFT_KEYBOARD_SHOW_ON_FOCUS,
maxLength: 2,
top: 10,
height: 60,
value: "",
width: '12%',
color : '#000000'
};
this way, softKeyboard will be shown on focus the first time.
Finally, good luck with your app :-)

Related

Dygraphs: Highlight specific point on mouse over

Is there a way to highlight a specific point when mouse is over or near that specific point ? The thing is that I don't want to highlight all the lines but only the point(s) under or near my cursor. My goal is to show a tooltip at that position with the informations for that point.
This ChartJs example demonstrate pretty well what I would like to do:
http://www.chartjs.org/samples/latest/scales/time/line.html
And these are my current options:
{
drawPoints: true,
showRoller: false,
highlightCircleSize: 5,
labels: ['Time', 'Vac', 'Temp'],
ylabel: 'Vaccum (In/Hg)',
y2label: 'Temperature ('+ TemperatureUnitFactory.getTemperatureUnit() + ')',
series : {
'Vac': {
axis: 'y'
},
'Temp': {
axis: 'y2'
}
},
axes: {
y: {
drawGrid: true,
independentTicks: true,
valueRange: [0, -32],
label: 'Vaccum'
},
y2: {
drawGrid: false,
independentTicks: true,
valueRange: [
TemperatureUnitFactory.getTemperatureForUnit(-30),
TemperatureUnitFactory.getTemperatureForUnit(35)
],
ylabel: 'Temperature'
}
}
}
If you feel like I am missing informations that would help you enlighting me, just let me know in a comment.
Thank you all!
So here's a snippet for the solution to my problem. I believe it could be optimized by throtling the mousemouve callback, but in my case it did just fine. I converted the snippet from angular to jQuery for "simplicity".
var data = [
[new Date(20070101),62,39],
[new Date(20070102),62,44],
[new Date(20070103),62,42],
[new Date(20070104),57,45],
[new Date(20070105),54,44],
[new Date(20070106),55,36],
[new Date(20070107),62,45],
[new Date(20070108),66,48],
[new Date(20070109),63,39],
[new Date(20070110),57,37],
[new Date(20070111),50,37],
[new Date(20070112),48,35],
];
var graph = new Dygraph(
document.getElementById("chart"), data, {
rollPeriod: 1,
labels: ['Time', 'Vac', 'Temp'],
showRoller: false,
drawPoints: true,
}
);
var tooltip = {
element: $('#tooltip'),
x: function(_x){
this.element.css('left', _x);
},
y: function(_y) {
this.element.css('top', _y);
},
shown: false,
throttle: null,
currentPointData: null,
show: function() {
if(!this.shown) {
this.element.show();
this.shown = true;
}
},
hide: function() {
this.cancelThrottle();
if(this.shown) {
this.element.hide();
this.shown = false;
}
},
cancelThrottle: function () {
if(this.throttle !== null) {
clearTimeout(this.throttle);
this.throttle = null;
}
},
bindPoint: function (_point) {
this.element.html([_point.point.name,_point.point.xval, _point.point.yval].join(' | '))
console.log('Handle point data', _point);
}
};
var chartElement = $('#chart');
var isMouseDown = false;
chartElement.on('mousedown', function(){ isMouseDown = true; });
chartElement.on('mouseup', function(){ isMouseDown = false; });
chartElement.on('mousemove', function(){
if(graph === null) { return; }
if(isMouseDown) {
tooltip.hide();
return;
}
const ACCEPTABLE_OFFSET_RANGE = 8;
const TOOLTIP_BOTTOM_OFFSET = 25;
const TOOLTIP_THROTTLE_DELAY = 600;
var graphPos = Dygraph.findPos(graph.graphDiv),
canvasX = Dygraph.pageX(event) - graphPos.x,
canvasY = Dygraph.pageY(event) - graphPos.y,
rows = graph.numRows(),
cols = graph.numColumns(),
axes = graph.numAxes(),
diffX, diffY, xPos, yPos, inputTime, row, col, axe;
for (row = 0; row < rows; row++)
{
inputTime = graph.getValue(row, 0);
xPos = graph.toDomCoords(inputTime, null)[0];
diffX = Math.abs(canvasX - xPos);
if (diffX < ACCEPTABLE_OFFSET_RANGE)
{
for (col = 1; col < cols; col++)
{
var inputValue = graph.getValue(row, col);
if (inputValue === null) { continue; }
for(axe = 0; axe < axes; axe++)
{
yPos = graph.toDomCoords(null, inputValue, axe)[1];
diffY = Math.abs(canvasY - yPos);
if (diffY < ACCEPTABLE_OFFSET_RANGE)
{
tooltip.cancelThrottle();
if(!tooltip.shown)
{
var self = this;
tooltip.throttle = setTimeout(function () {
var ttHeight = tooltip.element.height(),
ttWidth = tooltip.element.width();
tooltip.x((xPos - (ttWidth / 2)));
tooltip.y((yPos - (ttHeight + TOOLTIP_BOTTOM_OFFSET)));
tooltip.show();
var closestPoint = graph.findClosestPoint(xPos, yPos);
if(closestPoint) {
tooltip.bindPoint(closestPoint);
}
}, TOOLTIP_THROTTLE_DELAY);
}
return;
}
}
}
}
}
tooltip.hide();
});
.chart-container {
position:relative;
}
.chart-container > .tooltip {
position:absolute;
padding: 10px 10px;
background-color:#ababab;
color:#fff;
display:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chart-container">
<div id="chart"></div>
<div id="tooltip" class="tooltip">
Some data to be shown
</div>
</div>

setInterval wont work if timing is too short

I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>

QueryLoader PreLoading Issue

I'm using http://www.gayadesign.com/scripts/queryLoader/to preload my pages. Now, it works fine with my home page, but when I put the code on any other page, the loader just stops at 90% and it won't load... I'm using the code provided in the zip file on the site. What's the problem? I added the script which initiates the plugin
QueryLoader.selectorPreload = "body";
QueryLoader.init();
In the php file and included it in my pages... Like I said, works good on my home page, but fails on any other. Why?
Code 1:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function()
{
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0")
{
return false;
}
if (QueryLoader.selectorPreload == "body")
{
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
}
else
{
$(document).ready(function()
{
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function()
{
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE"))
{
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100)
{
QueryLoader.imgCallback();
}
}
},
imgCallback: function()
{
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector)
{
var everything = $(selector).find("*:not(script)").each(function()
{
var url = "";
if ($(this).css("background-image") != "none")
{
var url = $(this).css("background-image");
}
else if (typeof($(this).prop("src")) != "undefined" && $(this).prop("tagName").toLowerCase() == "img")
{
var url = $(this).prop("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0)
{
QueryLoader.items.push(url);
}
});
},
createPreloading: function()
{
QueryLoader.preloader = $("<DIV></DIV>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow:"hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++)
{
var imgLoad = $("<IMG></IMG>");
$(imgLoad).prop("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function()
{
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function()
{
if (QueryLoader.selectorPreload == "body")
{
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
}
else
{
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<DIV></DIV>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("LoadCont");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<DIV></DIV>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("Loading");
$(QueryLoader.loadBar).css({
position: "relative",
top: "90%",
width: "0%"
});
},
animateLoader: function()
{
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99)
{
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function()
{
QueryLoader.doneLoad();
});
}
else
{
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function()
{
clearTimeout(QueryLoader.ieTimeout);
if (QueryLoader.selectorPreload == "body")
{
var height = $(window).height();
}
else
{
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function()
{
$(QueryLoader.overlay).fadeOut(888);
$(QueryLoader.preloader).remove();
});
}
}
Code 2:
<SCRIPT>
QueryLoader.selectorPreload = "body";
QueryLoader.init();
</SCRIPT>
CSS:
.LoadCont
{
Z-INDEX: 9999 !important;
BACKGROUND: #000000;
}
.Loading
{
HEIGHT: 1px;
BACKGROUND-COLOR: #626262;
}
The page is: http://www.okultopedija.com/Ulaz?otvori=Razno

Make words pulsate and change of place randomly

I'm doing this plugin that takes the words and makes them pulsate on the screen:
First they appear and grow, then they vanish, change place and again appear
Working plugin:
+ function($) {
var Pulsate = function(element) {
var self = this;
self.element = element;
self.max = 70;
self.min = 0;
self.speed = 500;
self.first = true;
self.currentPlace;
self.possiblePlaces = [
{
id: 0,
top: 150,
left: 150,
},
{
id: 1,
top: 250,
left: 250,
},
{
id: 2,
top: 350,
left: 350,
},
{
id: 3,
top: 250,
left: 750,
},
{
id: 4,
top: 450,
left: 950,
}
];
};
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = self.possiblePlaces[Math.floor(Math.random() * self.possiblePlaces.length)];
if(!self.possiblePlaces) self.defineRandomPlace;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.defineRandomPlace();
});
};
Pulsate.prototype.animateToRandomNumber = function() {
var self = this;
self.element.animate({
'fontSize': Math.floor(Math.random() * (70 - 50 + 1) + 50),
'queue': true
}, self.speed, function() {
self.first = false;
self.start();
});
};
Pulsate.prototype.start = function() {
var self = this;
if (self.first) self.defineRandomPlace();
if (!self.first) self.animateToZero();
self.animateToRandomNumber();
};
$(window).on('load', function() {
$('[data-pulsate]').each(function() {
var element = $(this).data('pulsate') || false;
if (element) {
element = new Pulsate($(this));
element.start();
}
});
});
}(jQuery);
body {
background: black;
color: white;
}
.word {
position: absolute;
text-shadow: 0 0 5px rgba(255, 255, 255, 0.9);
font-size: 0px;
}
.two {
position: absolute;
color: white;
left: 50px;
top: 50px;
}
div {
margin-left: 0px;
}
<span class="word" data-pulsate="true">Love</span>
<span class="word" data-pulsate="true">Enjoy</span>
<span class="word" data-pulsate="true">Huggs</span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
If you notice i define the places that the word can grow in the self.possiblePlaces, and if you notice the animation, sometimes more then one word can grow in one place, my goal coming here is ask for help. How I can make two words never grow in the same place??
I was trying to do like this:
In the defineRandomPlace i pick a random object inside my possiblePlaces array:
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = self.possiblePlaces[Math.floor(Math.random() * self.possiblePlaces.length)];
if(!self.possiblePlaces) self.defineRandomPlace;
delete self.possiblePlaces[self.currentPlace.id];
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
Notice the delete, first i clone the chosen object, after I delete it but keep his place in the array.
After the animation was over, I put the object in the array again, before starting all over again:
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.possiblePlaces[self.currentPlace.id] = self.currentPlace;
self.defineRandomPlace();
});
But it made no difference.
Thanks!!
Pen: http://codepen.io/anon/pen/waooQB
In your example, you are randomly picking from a list that has five members, and you have three separate words that could be displayed, putting chance of overlap fairly high.
A simple approach to resolve is to pick the first item in the list, remove it from the list, and the append to the end of the list each time. Because you have more positions in the lists than items selecting from it, you're guaranteed to never collide.
Share the same list possiblePlaces between all instances.
Shift the first item off the queue, and push it onto the end when its done each time, instead of selecting randomly in defineRandomPlace.
Snippet highlighting #2:
// shift a position off the front
self.currentPlace = possiblePlaces.shift();
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
// push it back on the end
possiblePlaces.push(self.currentPlace);
If you want it truly random, you'll need to randomly select and remove an item from the array, and not put it back into the array until after it's been used. You'll also need to always ensure that you have more possiblePlaces than you have dom elements to place on the page.
Like so:
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
var newPlace = possiblePlaces.splice(Math.floor(Math.random()*possiblePlaces.length), 1)[0];
if (self.currentPlace) {
possiblePlaces.push(self.currentPlace);
}
self.currentPlace = newPlace;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
See http://codepen.io/anon/pen/bdBBPE
My decision is to divide the page to imaginary rows and to prohibit more than one word in the same row. Please check this out.
Note: as the code currently does not support recalculating of rows count on document resize, the full page view will not display correctly. Click "reload frame" or try JSFiddle or smth.
var pulsar = {
// Delay between words appearance
delay: 400,
// Word animation do not really depend on pulsar.delay,
// but if you set pulsar.delay small and wordAnimationDuration long
// some words will skip their turns. Try 1, 2, 3...
wordAnimationDuration: 400 * 3,
// Depending on maximum font size of words we calculate the number of rows
// to which the window can be divided
maxFontSize: 40,
start: function () {
this.computeRows();
this.fillWords();
this.animate();
},
// Calculate the height or row and store each row's properties in pulsar.rows
computeRows: function () {
var height = document.body.parentNode.clientHeight;
var rowsCount = Math.floor(height/this.maxFontSize);
this.rows = [];
for (var i = 0; i < rowsCount; i++) {
this.rows.push({
index: i,
isBusy: false
});
}
},
// Store Word instances in pulsar.words
fillWords: function () {
this.words = [];
var words = document.querySelectorAll('[data-pulsate="true"]');
for (var i = 0; i < words.length; i++) {
this.words.push(new Word(words[i], this.wordAnimationDuration, this.maxFontSize));
}
},
// When it comes time to animate another word we need to know which row to move it in
// this random row should be empty at the moment
getAnyEmptyRowIndex: function () {
var emptyRows = this.rows.filter(function(row) {
return !row.isBusy;
});
if (emptyRows.length == 0) {
return -1;
}
var index = emptyRows[Math.floor(Math.random() * emptyRows.length)].index;
this.rows[index].isBusy = true;
return index;
},
// Here we manipulate words in order of pulsar.words array
animate: function () {
var self = this;
this.interval = setInterval(function() {
var ri = self.getAnyEmptyRowIndex();
if (ri >= 0) {
self.words.push(self.words.shift());
self.words[0].animate(ri, function () {
self.rows[ri].isBusy = false;
});
}
}, this.delay);
}
}
function Word (span, duration, maxFontSize) {
this.span = span;
this.inAction = false;
this.duration = duration;
this.maxFontSize = maxFontSize;
}
/**
* #row {Numer} is a number of imaginary row to place the word into
* #callback {Function} to call on animation end
*/
Word.prototype.animate = function (row, callback) {
var self = this;
// Skip turn if the word is still busy in previous animation
if (self.inAction) {
return;
}
var start = null,
dur = self.duration,
mfs = self.maxFontSize,
top = row * mfs,
// Random left offset (in %)
left = Math.floor(Math.random() * 90),
// Vary then font size within half-max size and max size
fs = mfs - Math.floor(Math.random() * mfs / 2);
self.inAction = true;
self.span.style.top = top + 'px';
self.span.style.left = left + '%';
function step (timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
// Calculate the factor that will change from 0 to 1, then from 1 to 0 during the animation process
var factor = 1 - Math.sqrt(Math.pow(2 * Math.min(progress, dur) / dur - 1, 2));
self.span.style.fontSize = fs * factor + 'px';
if (progress < dur) {
window.requestAnimationFrame(step);
}
else {
self.inAction = false;
callback();
}
}
window.requestAnimationFrame(step);
}
pulsar.start();
body {
background: black;
color: white;
}
.word {
position: absolute;
text-shadow: 0 0 5px rgba(255, 255, 255, 0.9);
font-size: 0px;
/* To make height of the .word to equal it's font size */
line-height: 1;
}
<span class="word" data-pulsate="true">Love</span>
<span class="word" data-pulsate="true">Enjoy</span>
<span class="word" data-pulsate="true">Huggs</span>
<span class="word" data-pulsate="true">Peace</span>
I updated your plugin constructor. Notice the variable Pulsate.possiblePlaces, I have changed the variable declaration this way to be able to share variable data for all Object instance of your plugin.
var Pulsate = function(element) {
var self = this;
self.element = element;
self.max = 70;
self.min = 0;
self.speed = 500;
self.first = true;
self.currentPlace;
Pulsate.possiblePlaces = [
{
id: 0,
top: 150,
left: 150,
},
{
id: 1,
top: 250,
left: 250,
},
{
id: 2,
top: 350,
left: 350,
},
{
id: 3,
top: 250,
left: 750,
},
{
id: 4,
top: 450,
left: 950,
}
];
};
I added occupied attribute to the possible places to identify those that are already occupied. If the randomed currentPlace is already occupied, search for random place again.
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = Pulsate.possiblePlaces[Math.floor(Math.random() * Pulsate.possiblePlaces.length)];
if(!Pulsate.possiblePlaces) self.defineRandomPlace;
if (!self.currentPlace.occupied) {
self.currentPlace.occupied = true;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
} else {
self.defineRandomPlace();
}
};
Every time the element is hidden, set the occupied attribute to false.
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.currentPlace.occupied = false;
self.defineRandomPlace();
});
};
A small hint f = 0.5px x = 100px t = 0.5s
x / f = 200
200/2 * t * 0.5 = f(shrink->expand until 100px square) per 0.5 seconds

TypeError using QueryLoader plugin

For page loader i have used the plugin. Following is js:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function() {
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0") {
//break if IE6
return false;
}
if (QueryLoader.selectorPreload == "body") {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
} else {
$(document).ready(function() {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
//help IE drown if it is trying to die :)
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function() {
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE")) {
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100) {
QueryLoader.imgCallback();
}
}
},
imgCallback: function() {
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector) {
var everything = $(selector).find("*:not(script)").each(function() {
var url = "";
if ($(this).css("background-image") != "none") {
var url = $(this).css("background-image");
} else if (typeof($(this).attr("src")) != "undefined" && $(this).attr("tagName").toLowerCase() == "img") {
var url = $(this).attr("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0) {
QueryLoader.items.push(url);
}
});
},
createPreloading: function() {
QueryLoader.preloader = $("<div></div>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow: "hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++) {
var imgLoad = $("<img></img>");
$(imgLoad).attr("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function() {
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function() {
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<div></div>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("QOverlay");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<div></div>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("QLoader");
$(QueryLoader.loadBar).css({
position: "relative",
top: "50%",
width: "0%"
});
},
animateLoader: function() {
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99) {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() {
QueryLoader.doneLoad();
});
} else {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function() {
//prevent IE from calling the fix
clearTimeout(QueryLoader.ieTimeout);
//determine the height of the preloader for the effect
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function() {
$(QueryLoader.overlay).fadeOut(800);
$(QueryLoader.preloader).remove();
});
}
}
In my html file, I used following Javascript:
<script type='text/javascript'>
QueryLoader.init();
</script>
And css is as following:
.QOverlay {
background-color: #000000;
z-index: 9999;
}
.QLoader {
background-color: #CCCCCC;
height: 1px;
}
I used this for simple example it works well.
But when I used this for my site it is giving error in js file as following:
TypeError: $(...).offset(...) is undefined
var left = $(QueryLoader.selectorPreload).offset()['left'];
So please can you help out from this issue:
Thanks in advance..
Your plugin is not really one. Go see the documentation to see more details.
Anyway, even if it's not a plugin, it could work as an object using some jQuery functions.
First, you shouldn't call the object inside the object function.
IE :
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
Here, you got your first error which you could have seen in the console. It should be :
this.ieTimeout = setTimeout(this.ieLoadFix, this.ieLoadFixTime);
You can start debugging like this, up to your initial error here.

Categories

Resources