How can I change the number of columns in Gridster? - javascript

I have a a gridster based layout that will start with a set number of columns and a fixed number of tiles. Is there a way to change the number of columns once it has been set up? -- for example starting with 3 columns :
(tile1 | tile2 | tile3
tile4 | tile5 | tile6)
and changing it to a two column layout:
(tile1 | tile2
tile3 | tile4
tile5 | tile6)
The change will be driven by user interaction.
I have tried to use something like:
gridster = $("#gridster-container").gridster({
widget_margins: [30, 30],
widget_base_dimensions : [ 200, 170 ],
max_cols:numberOfColumns,
avoid_overlapped_widgets: true
}).data('gridster');
// user interaction
gridster.options.max_rows = 2;
gridster.init();
but that does not seem to work...
I have tried manually changing the data-row and data-col values to the new positions, and called init() (and not called init).
I have even tried changing the gridster code adding
// HACK
if (max_cols && max_cols < this.cols) {
this.cols = max_cols;
}
to the method fn.generate_grid_and_stylesheet (just after the line:
if (max_cols && max_cols >= min_cols && max_cols < this.cols) {
this.cols = max_cols;
}
).
I can get the tiles to move the the correct position using any of these options, but subsequent dragging behaviour is... odd.
I have set up a jsfiddle (http://jsfiddle.net/qT6qr/) to explain what I mean (please excuse the gridster.min.js in line at the top of the fidddle, I couldn't find a cdn that I could use for it...).
Thanks in advance

I just spent a couple of hours and ran across this piece of code. I just put it in a .js file and did:
var gr = $(elem).gridster(options).data('gridster');
// update options and then call this at a later point:
gr.resize_widget_dimensions(options);
And then it just worked.
Here's the code:
(function($) {
$.Gridster.generate_stylesheet = function(opts) {
var styles = '';
var max_size_x = this.options.max_size_x;
var max_rows = 0;
var max_cols = 0;
var i;
var rules;
opts || (opts = {});
opts.cols || (opts.cols = this.cols);
opts.rows || (opts.rows = this.rows);
opts.namespace || (opts.namespace = this.options.namespace);
opts.widget_base_dimensions || (opts.widget_base_dimensions = this.options.widget_base_dimensions);
opts.widget_margins || (opts.widget_margins = this.options.widget_margins);
opts.min_widget_width = (opts.widget_margins[0] * 2) +
opts.widget_base_dimensions[0];
opts.min_widget_height = (opts.widget_margins[1] * 2) +
opts.widget_base_dimensions[1];
/* generate CSS styles for cols */
for (i = opts.cols; i >= 0; i--) {
styles += (opts.namespace + ' [data-col="'+ (i + 1) + '"] { left:' +
((i * opts.widget_base_dimensions[0]) +
(i * opts.widget_margins[0]) +
((i + 1) * opts.widget_margins[0])) + 'px;} ');
}
/* generate CSS styles for rows */
for (i = opts.rows; i >= 0; i--) {
styles += (opts.namespace + ' [data-row="' + (i + 1) + '"] { top:' +
((i * opts.widget_base_dimensions[1]) +
(i * opts.widget_margins[1]) +
((i + 1) * opts.widget_margins[1]) ) + 'px;} ');
}
for (var y = 1; y <= opts.rows; y++) {
styles += (opts.namespace + ' [data-sizey="' + y + '"] { height:' +
(y * opts.widget_base_dimensions[1] +
(y - 1) * (opts.widget_margins[1] * 2)) + 'px;}');
}
for (var x = 1; x <= max_size_x; x++) {
styles += (opts.namespace + ' [data-sizex="' + x + '"] { width:' +
(x * opts.widget_base_dimensions[0] +
(x - 1) * (opts.widget_margins[0] * 2)) + 'px;}');
}
return this.add_style_tag(styles);
};
$.Gridster.add_style_tag = function(css) {
var d = document;
var tag = d.createElement('style');
tag.setAttribute('generated-from', 'gridster');
d.getElementsByTagName('head')[0].appendChild(tag);
tag.setAttribute('type', 'text/css');
if (tag.styleSheet) {
tag.styleSheet.cssText = css;
} else {
tag.appendChild(document.createTextNode(css));
}
return this;
};
$.Gridster.resize_widget_dimensions = function(options) {
if (options.widget_margins) {
this.options.widget_margins = options.widget_margins;
}
if (options.widget_base_dimensions) {
this.options.widget_base_dimensions = options.widget_base_dimensions;
}
this.min_widget_width = (this.options.widget_margins[0] * 2) + this.options.widget_base_dimensions[0];
this.min_widget_height = (this.options.widget_margins[1] * 2) + this.options.widget_base_dimensions[1];
var serializedGrid = this.serialize();
this.$widgets.each($.proxy(function(i, widget) {
var $widget = $(widget);
this.resize_widget($widget);
}, this));
this.generate_grid_and_stylesheet();
this.get_widgets_from_DOM();
this.set_dom_grid_height();
return false;
};
})(jQuery);

I had a similar problem and was able to get it working through this approach:
var gridster = $(".gridster ul").gridster().data('gridster');
gridster.options.min_cols = 5; // Not necessarily required because of the following size changes, but I did it for clarity
gridster.options.widget_base_dimensions = [240, 400];
gridster.options.min_widget_width = 240;
// This section was for existing widgets. Apparently the code for drawing the droppable zones is based on the data stored in the widgets at creation time
for (var i = 0; i < gridster.$widgets.length; i++) {
gridster.resize_widget($(gridster.$widgets[i]), 1, 1);
}
gridster.generate_grid_and_stylesheet();

Related

How can I optimize the below code with less number of line?

I have coded the below piece of code which handle the number bigger than 999 and add a comma to it. For example 1,000 and 1,000,000. Wheare as once the number increase the comma will be placed in the correct position. I used DRY principle and I feel still there is another easy way to handle it.
Now, I want to know if there is much better way than that I did.
Waiting for your opinion.
Thanks.
function seperate_num_by_comma() {
var num = '199228754645.25',
withOutComma = num.split('.'),
addNewCommaAfter = 3,
x = withOutComma[0].length % addNewCommaAfter,
lenOfWithOutComma_0 = withOutComma[0].length,
length_1 = withOutComma[0].length - x,
starter = 0,
wholeNumber = ' ';
for (var i = 0; i < lenOfWithOutComma_0; i++) {
function run_first_func() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter);
};
function run_second_fun() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter) + ",";
starter += addNewCommaAfter;
length_1 -= addNewCommaAfter;
};
if (x > 0) {
if (length_1 == 0) {
run_first_func();
break;
} else if (wholeNumber == ' ') {
wholeNumber += withOutComma[0].substr(starter, x) + ",";
length_1 -= addNewCommaAfter;
starter = x;
} else {
run_second_fun();
}
} else if (x == 0) {
if (length_1 == 3) {
run_first_func();
break;
}
run_second_fun();
}
}
console.log(wholeNumber + '.' + withOutComma[1]);
}
seperate_num_by_comma();
One Line:
165B minified version (no IE): seperate_by_comma=t=>(x=(""+t).split("."),z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|"),x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length),x.join("."))
OR 180B, IE-friendly: seperate_by_comma=function(t){x=(""+t).split(".");z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|");x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length);return x.join(".")}
Explanation:
seperate_num_by_comma = function(number){//12345678.9
var str = String(t);
var withoutDot = str.split("."); //["12345678", "9"]
var chunksOfThree = withoutDot[0].replace(/((\d{3})*?)(\.|$)/,"|$1");//"12|345678"
chunksOfThree = chunksOfThree.split("|");//["12", "345678"]
chunksOfThree[1] = chunksOfThree[1].replace(/(.{3})/g,",$1") //",345,678"
if(chunksOfThree[0].length==0){
chunksOfThree[1] = chunksOfThree[1].slice(1); //Fix for specific cases
}
withoutDot[0] = chunksOfThree[0] /*"12"*/ + chunksOfThree[1] /*",345,678"*/
return withoutDot.join(".") //"12,345,678.9"
}

Getting back correct index value from Array

I have to show Array values in circle kind of shape and it has to be run in a loop forever. Things are working fine when you rotate circle counter clockwise. But it has a problem in when we move circle in opposite direction.
I have an active element on the wheel. So when you user clicks on any other slide then active it calculates the difference between clicked slide and active slide then add and remove items in wheel accordingly.
So basically it picks the value from Array. if you move circle clockwise it picks values from the back of the Array and if you move it counterclockwise it starts picking up values from next available. If 11 items are rendered in first-page load then it will start taking values from 12 no index.
The problem occurs when you click the item which has above position from the active element and then you again rotates it counterclockwise.
Let say you click item no. 8 then you click item no.7. In this case item, no.2 should have been added into the wheel.
Here is fiddle.
var numberOfElement = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
var initialRender = numberOfElement.slice(0, 11);
var startPoint = initialRender.length;
var endPoint = numberOfElement.length;
function generateHtml() {
var html = '';
initialRender.forEach(function(item, index) {
var angle = 18 * (index);
var className = angle === 90 ? 'active' : '';
html += '<div class="shapes ' + className + '" data-deg="' + angle + '" style="--deg:' + angle + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angle + ' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML = html;
}
generateHtml();
$('#dynamic-html').on('click', '.shapes', function() {
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({
'transform': 'rotate(' + degrees + 'deg)'
}).attr('data-deg', degrees);
if (movementCloseWise) {
var itemLength = $('.shapes').length;
$('.shapes:gt(' + ((itemLength - 1) - diff) + ')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
} else {
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt(' + (diff) + ')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat(getItemFromStart(length - valueCount));
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem(items, isClockWise) {
var html = "",
lastItemAngle;
if (isClockWise) {
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
} else {
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item, index) {
if (isClockWise) {
var angles = lastItemAngle - (18 * (index + 1))
} else {
var angles = lastItemAngle + (18 * (index + 1))
}
html += '<div class="shapes" data-deg="' + (angles) + '" style="--deg:' + angles + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angles + ' deg </span></div>';
});
return html;
}
I think your problem is just your endPoint initialization value. In your code, you initialize it as var endPoint = numberOfElement.length; which is wrong( I think) and it should be initialized by 0; I changed it and it worked:
var numberOfElement = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
var initialRender = numberOfElement.slice(0,11);
var startPoint = initialRender.length;
var endPoint = 0; /* here is the change */
function generateHtml(){
var html ='';
initialRender.forEach(function(item,index){
var angle = 18 * (index);
var className = angle === 90? 'active':'';
html+='<div class="shapes '+className+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angle+' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
if(movementCloseWise){
var itemLength = $('.shapes').length;
$('.shapes:gt('+((itemLength-1)-diff)+')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
}else{
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt('+(diff)+')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat( getItemFromStart(length - valueCount) );
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem (items, isClockWise){
var html = "", lastItemAngle;
if(isClockWise){
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
}
else{
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item,index){
if(isClockWise){
var angles = lastItemAngle - (18 * (index +1))
}
else{
var angles = lastItemAngle + (18 * (index +1))
}
html+='<div class="shapes" data-deg="'+(angles)+'" style="--deg:'+angles+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angles+' deg </span></div>';
});
return html;
}
.main{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}
.pos{
height:150px;
width:150px;
position: relative;
}
.circle{
background: red;
height:150px;
width:150px;
border-radius: 50%;
transition: transform 0.3s ease-in-out;
}
.shapes{
position: absolute;
top:calc(50% - 75px);
left:calc(50% - 10px);
width: 20px;
height: 150px;
transform: rotate(var(--deg)) translate(0, 160px);
background: green;
text-align: center;
}
.fake-overlay{
position: absolute;
width: 203%;
height: 320%;
background: #fff;
top: -160px;
right: -148%;
display: none
}
.active{
background: red
}
.set-pos{
position: absolute;
bottom: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="pos">
<div class="circle">
<div id="dynamic-html"></div>
</div>
<div class="fake-overlay"></div>
</div>
</div>
And here is Jsfiddle
I have fixed this by the following code.
function getItemsFromBack(length) {
var values = [];
if (endPoint > numberOfElement.length) {
var diff = endPoint - numberOfElement.length;
values = numberOfElement.slice(diff - length, diff)
endPoint = endPoint - length;
return values.reverse();
}
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
I am checking if endPoint is greater then total Array length. Then endPoint- Array.length and using diff to get the element
Your CSS is awesome, but your JavaScript still has a bug. Try this:
click 7, then click 2
To fix it, I propose we simplify your logic a bit:
give meaningful ids to items so we can easily select them, compare them and deduce the item angle
do not use hard coded arrays (if you did it because of a code quality tool like jslint, consider telling it to tolerate for loops)
The complexity of your code was coming from the management of start and end points within a range of 1-30. This is now made easy by 1st point above.
I have not changed your code too much so you can recognize your working parts easily:
// Global variables
var numberOfItems = 30,
numberOfRenderedItems = 11,
firstItem = 0
;
function generateHtml(){
var html ='';
for (var item = 0; item < numberOfRenderedItems; item++) {
var angle = 18 * item,
className = angle === 90? 'active':'';
html +=
'<div class="shapes '+className+'" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+(item+1)+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
// Set clicked item active
$('.shapes').removeClass('active');
$(this).addClass('active');
var selectedItem = Number($(this).data('item')),
previousActiveItem = firstItem + Math.floor(numberOfRenderedItems/2),
diff = selectedItem - previousActiveItem,
selectedAngle = selectedItem * 18,
degrees = 90 - selectedAngle,
isClockWise = diff < 0;
// Rotate all items
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
var items;
if (isClockWise)
items = getItemsFromBack(diff);
else
items = getItemsFromFront(diff);
// Remove items
items.toRemove.forEach( function (item) {
$(".shapes[data-item="+item+"]").remove();
});
// Add items
var newItems = items.toAdd.reduce( function (html, item) {
// Get item number between 1 and max
var itemNumber = getNumberInRange(item),
angle = 18 * item;
return html +
'<div class="shapes" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+itemNumber+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}, '');
if (isClockWise)
$('#dynamic-html').append(newItems);
else
$('#dynamic-html').prepend(newItems)
})
function getItemsFromBack (diff) {
var items = {
toAdd: [],
toRemove: []
};
firstItem += diff;
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i);
items.toRemove.push(firstItem + i + numberOfRenderedItems);
}
return items;
}
function getItemsFromFront (diff) {
var items = {
toAdd: [],
toRemove: []
};
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i + numberOfRenderedItems);
items.toRemove.push(firstItem + i);
}
firstItem += diff;
return items;
}
function getNumberInRange (item) {
do {
item = (item + numberOfItems) % numberOfItems;
}
while (item < 0);
return item + 1;
}
Updated JSFiddle link is below
https://jsfiddle.net/dpvjtvjd/2/

Javascript how to set interval time to stop scrolling

This is the demo in jsfiddle, demo
What I want is let the scrolled items('one ', 'two', 'three', '4', '5', '6', '7') automatically scroll up like the demo showed, and stop 2 sec when it's in the middle position. But in my demo, it will shack for a while after stopping in the middle position.
Here is the place in my demo code for setting position.
if ((x == 0) || (x % 35== 0)) {
setTimeout(function () {
i.top = x + 'px';
}, 1000);
} else {
i.top = x + 'px';
}
Any one can help me? Thanks!
UPDATE:
The reason why I set 35 is because I found that the scrolled items are approximately in the middle position when it equals to 0, -35,-70,-105,.... But when I console all x, I found that the value of x is between (31, -251). Do you know how to find the exact position when each items are in the middle of position? Thanks!
i modified your code a bit,
i set a variable "k" that the interval is assigned to and i clear the interval on stop and start it again after the timeout
looks good for me -> http://jsfiddle.net/ato0mf7u/3/
no funny shakin anymore ;-D
window.onload = addScrollers;
var i = 1;
var arr = ['one ', 'two', 'three', '4', '5', '6', '7'];
var mid;
var k;
function addScrollers() {
var txt = arr[0];
while (i < arr.length) {
txt += '<p>' + arr[i] + '</p>';
i++;
}
startScroll('myscroller', txt);
}
var speed = 10; // scroll speed (bigger = faster)
var dR = false; // reverse direction
var step = 1;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
function objHeight(obj) {
if (obj.offsetHeight) return obj.offsetHeight;
if (obj.clip) return obj.clip.height;
return 0;
}
function scrF(i, sH, eH) {
var x = parseInt(i.top) + (dR ? step : -step);
if (dR && x > sH) {
x = -eH;
} else if (x < 1 - eH) {
x = sH;
}
//when x is the times of 35, the positio is in middle
if ((x == 0) || (x % 35== 0)) {
clearInterval(k);
setTimeout(function () {
i.top = x + 'px';
k = setInterval(function () {
scrF(i, sH, eH);
}, 1000 / speed);
}, 1000);
}
else {
i.top = x + 'px';
}
return x;
}
function startScroll(sN, txt) {
var scr = document.getElementById(sN);
var sW = objWidth(scr);
var sH = objHeight(scr);
scr.innerHTML = '<div id="' + sN + 'in" style="position:absolute; left:3px; width:' + sW + ';">' + txt + '<\/div>';
var sTxt = document.getElementById(sN + 'in');
var eH = objHeight(sTxt);
mid = (eH - sH) / 2;
sTxt.style.top = (dR ? -eH : sH) + 'px';
sTxt.style.clip = 'rect(0,' + sW + 'px,' + eH + 'px,0)';
k = setInterval(function () {
scrF(sTxt.style, sH, eH);
}, 1000 / speed);
}

How to "echo" or show pictures from Javascript

I'm trying to use the below code to reflect different pictures of the moon into an HTML doc. Of course i've added the Jquery and Javascript tags.
I've been looking at this for hours and trying different things but I can't find out what to put into HTML code that will actually show or echo the pictures.
What should I put into the "moonImage.src = "pix/moon" + truncPhase + ".png";" part of the code? I don't understand how to essentially echo the photos. Help please?:
// Image max size
var IMAGE_MAX_SIZE = 196;
// Records whether or not the gadget is expanded
var poppedOut = false;
function onOpen() {
// Check once every 30 minutes
view.setInterval(onTimer, 30 * 60 * 1000);
// Initialize the gadget
onTimer();
}
// Called when the timer goes off
function onTimer() {
// Compute the moon phase each time timer is called
var cal = new Date();
// Base the computation off of UTC time, to the nearest hour
var phase = computeMoonPhase(cal.getUTCFullYear(),
cal.getUTCMonth() + 1,
cal.getUTCDate(),
cal.getUTCHours());
var truncPhase = Math.floor(phase) % 30;
// Find the text description of the current phase
var desc;
if (truncPhase === 0) {
desc = STRING_MOON_DESC_NEW;
} else if (truncPhase == 7) {
desc = STRING_MOON_DESC_FIRST_QUARTER;
} else if (truncPhase == 15) {
desc = STRING_MOON_DESC_FULL;
} else if (truncPhase == 23) {
desc = STRING_MOON_DESC_THIRD_QUARTER;
} else if (truncPhase > 0 && phase < 7) {
desc = STRING_MOON_DESC_WAXING_CRESCENT;
} else if (truncPhase > 7 && phase < 15) {
desc = STRING_MOON_DESC_WAXING_GIBBOUS;
} else if (truncPhase > 15 && phase < 23) {
desc = STRING_MOON_DESC_WANING_GIBBOUS;
} else {
desc = STRING_MOON_DESC_WANING_CRESCENT;
}
// Set the image and text component appropriately
moonImage.src = "pix/moon" + truncPhase + ".png";
moonImage.tooltip = (Math.floor(phase * 100) / 100) + " " + STRING_DAYS_OLD;
phaseAge.innerText = STRING_MOON_AGE_PREFIX + " " + moonImage.tooltip +
"\n" +
desc;
}
// Called when view is resized (recompute constituent basicElement sizes and
// locations)
function resizeView() {
setDimensions(event.width, event.height);
}
// Open the browser whenever a user double clicks (expanded or collapsed)
function onDblClick() {
var obj = new ActiveXObject("Shell.Application");
obj.Open("http://stardate.org/nightsky/moon/");
}
// Show date age in title, when gadget is minimized
function onMinimize() {
view.caption = STRING_MOON_SHORT + " - " + moonImage.tooltip;
}
// Only show the textual part (details) when popped out
function onPopout() {
poppedOut = true;
phaseAge.visible = true;
}
// Hide the textual part in restored mode, show regular title, and reset
// dimensions
function onRestore() {
view.caption = GADGET_NAME;
phaseAge.visible = false;
//moonImage.enabled = true;
poppedOut = false;
setDimensions(view.width, view.height);
}
// Called whenever the sizes and/or locations of basicElements need to change
function setDimensions(width, height) {
// Image is square, constrained by smallest dimension
var sz = Math.min(width, height);
// Make the image almost as large as the sz
moonImage.width = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
moonImage.height = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
if (poppedOut) {
// Align image on left, and set text location
moonImage.x = 0;
phaseAge.x = moonImage.width + 5;
phaseAge.y = (height - phaseAge.height) / 2;
} else {
// Center image horizontally
moonImage.x = (width - moonImage.width) * 0.5;
}
// Always center image vertically
moonImage.y = (height - moonImage.height) * 0.5;
}
// Compute the moon phase.
// Code is based upon Bradley E. Schaefer''s well-known moon phase algorithm.
function computeMoonPhase(year, month, day, hours) {
var MOON_PHASE_LENGTH = 29.530588853;
// Convert the year into the format expected by the algorithm
var transformedYear = year - Math.floor((12 - month) / 10);
// Convert the month into the format expected by the algorithm
var transformedMonth = month + 9;
if (transformedMonth >= 12) {
transformedMonth = transformedMonth - 12;
}
// Logic to compute moon phase as a fraction between 0 and 1
var term1 = Math.floor(365.25 * (transformedYear + 4712));
var term2 = Math.floor(30.6 * transformedMonth + 0.5);
var term3 = Math.floor(Math.floor((transformedYear / 100) + 49) * 0.75) - 38;
var intermediate = term1 + term2 + (day + (hours - 1) / 24) + 59;
if (intermediate > 2299160) {
intermediate = intermediate - term3;
}
var normalizedPhase = (intermediate - 2451550.1) / MOON_PHASE_LENGTH;
normalizedPhase = normalizedPhase - Math.floor(normalizedPhase);
if (normalizedPhase < 0) {
normalizedPhase = normalizedPhase + 1;
}
// Return the result as a value between 0 and MOON_PHASE_LENGTH
return normalizedPhase * MOON_PHASE_LENGTH;
}
HTML:
<html>
<head><title>Kendrick Moon</title>
<script src="ajax.googleapis.com/ajax/libs/jquery/1.8.3/ (etc.)
<script src="code.jquery.com/ui/1.9.2/jquery-ui.js"></script>;
<script src="main.js" type="text/javascript"></script>
<head>
<body>
<div><img src=""/> </div>
</body>
</html>
ok, well thats then easy.
first of all, you might want to check out jquery. with jquery it would be something like this.
<img src="" id="my_image" />
in javascript then (with jquery)
// the `myLinkToImage` is hopefully the variable of your path
$("#my_image").attr("src", myLinkToImage);
as you can see I´m using #. That is a typical jQuery Selector. You might check out more of them here
in javascript without jquery
document.getElementById("my_image").src = myLinkToImage;

Having issues with live calculations, calculating each key stroke

I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.

Categories