noUIslider adjustment with plus and minus buttons on slider - javascript

Has anyone included anchor tags as a plus and minus function to increase and decrease your value on the slider of the noUIslider? I haven't found anything related to this using the noUIslider yet, but I'm in hopes someone has done it before. I have an example of one of my sliders when they're created below.
qdata['calc-rate'] = {value:4,type:"percent",decimals:3,post:"%",interface:"slider",min:0,max:10,inc:.125,label:'Interest Rate',display:''};
var f = qdata['calc-rate'];
var val = f['value'];
var sliderInterest = document.getElementById("paymentSliderInterest");
noUiSlider.create(sliderInterest, {
start:val,
behaviour:'tap',
range:{'min':0,'max':10},
connect:"lower",
step:f.inc,
format: wNumb({decimals: f.decimals})
});
sliderInterest.noUiSlider.on('slide', setInterestSliderDisplay);

There is "noUiSlider.get()" and "noUiSlider.set()" methods available to let you achieve this. I have done this for date and amount. Please have a look at code below and let me know if you have any question.
Please don't forget to have a look at stepSize variable in my script below. You can customise step size. In date you can select Year or Month. Hope this helpful to someone.
Simple number or amount
var connectSlider = document.getElementById('slider-connect');
noUiSlider.create(connectSlider, {
start: 100,
connect: [true, false],
range: {
'min': 0,
'max': 500
},
step : 1,
tooltips: wNumb({decimals: 0, suffix: 'K'}),
format: wNumb({decimals: 0})
});
connectSlider.noUiSlider.on('update', function (values, handle) {
document.getElementById('event-start').innerHTML = values[0] + "K";
//var myVal = connectSlider.noUiSlider.get();
});
function manualStep (direction){
var currentPosition = parseInt(connectSlider.noUiSlider.get());
var stepSize = 100;
if(direction == 'f'){
currentPosition += stepSize;
}
if(direction == 'b'){
currentPosition -= stepSize;
}
currentPosition = (Math.round(currentPosition / stepSize) * stepSize);
connectSlider.noUiSlider.set(currentPosition);
}
document.getElementById('stepforward').onclick = function() {manualStep("f")};
document.getElementById('stepback').onclick = function() {manualStep("b")};
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wnumb/1.1.0/wNumb.js"></script>
<p>
Some Amount
</p>
<div id="slider-connect"></div>
<div class="example-val" id="event-start">34</div>
<div class="example-val" id="event-end"></div>
<button id="stepback">Decrease</button>
<button id="stepforward">Increase</button>
Date Slider
// Create a new date from a string, return as a timestamp.
function timestamp(str) {
return new Date(str).getTime();
}
var dateSlider = document.getElementById('slider-date');
var dateNow = timestamp(Date.now());
noUiSlider.create(dateSlider, {
// Create two timestamps to define a range.
range: {
min: timestamp('2012'),
max: timestamp(dateNow)
},
// Steps of one week
step: 24 * 60 * 60 * 1000,
// Two more timestamps indicate the handle starting positions.
start: timestamp('2015'),
connect: [true, false],
tooltips: true,
// No decimals
format: { to: toFormat, from: Number }
});
function toFormat ( v ) {
return formatDate(new Date(v));
}
var dateValues = [
document.getElementById('event-start'),
document.getElementById('event-end')
];
dateSlider.noUiSlider.on('update', function (values, handle) {
dateValues[handle].innerHTML = values[handle];
});
// Create a string representation of the date.
function formatDate(date) {
// Create a list of day and month names.
var months = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
return months[date.getMonth()] + ", " +
date.getFullYear();
}
function manualStep (direction){
var currentPosition = dateSlider.noUiSlider.get();
var stepSize = 'month';
currentPosition = new Date(currentPosition);
if(stepSize === 'month'){
if(direction === 'f'){
currentPosition = new Date(currentPosition.setMonth(currentPosition.getMonth()+1));
}
if(direction === 'b'){
currentPosition = new Date(currentPosition.setMonth(currentPosition.getMonth()-1));
}
}
if(stepSize === 'year'){
if(direction === 'f'){
currentPosition = new Date(currentPosition.setFullYear(currentPosition.getFullYear()+1));
}
if(direction === 'b'){
currentPosition = new Date(currentPosition.setFullYear(currentPosition.getFullYear()-1));
}
}
dateSlider.noUiSlider.set(currentPosition);
}
document.getElementById('stepforward').onclick = function() {manualStep("f")};
document.getElementById('stepback').onclick = function() {manualStep("b")};
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/12.0.0/nouislider.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wnumb/1.1.0/wNumb.js"></script>
<p>
Some date:
</p>
<div id="slider-date"></div>
<div class="example-val" id="event-start"></div>
<div class="example-val" id="event-end"></div>
<button id="stepback">Decrease</button>
<button id="stepforward">Increase</button>
JS Fiddle Link for Amount or Number
JS Fiddle Link for Date

You can use the keypress example from the documentation, but change the event from a keypress to a button click.
It uses the step option to get the next and previous step:
button.addEventListener('click', function( e ) {
var values = keypressSlider.noUiSlider.get();
var value = Number(values[handle]);
// [[handle0_down, handle0_up], [handle1_down, handle1_up]]
var steps = keypressSlider.noUiSlider.steps();
// [down, up]
var step = steps[handle];
// set slider
// ...
});

function incRateSlider(e){
// changes slider rate value using plus and minus buttons
if(e){ e.preventDefault(); }
var f = qdata['calc-rate'];
var id = $(this).attr("id");
var dir = 1;
if(id == "leftCircleRate"){ dir = -1; }
//console.log(f.value);
var newval = +f.value + +(dir * f.inc);// add or subtract values
if(newval > f.max){ newval = f.max;}
else if(newval < f.min){ newval = f.min; }
var slider = document.getElementById('paymentSliderInterest');
slider.noUiSlider.set(newval); //this sets the value for the slider "super necessary"
setInterestSliderDisplay(newval);
}
Since I had my own array of data set for the required pieces of 'calc-rate' it was able to use the 'f.inc' to increase or decrease based on the selected id to move the slider one step at a time. If there isn't enough clarity on how this works just let me know so I can edit more of it to make sense.

Related

jQuery UI Slider Missing BG

I'm using a range slider with jQuery UI but when I move the slider, the background line does not show up so it's hard to tell where it is at. How do I highlight the background line only for the selected portion?
jsfiddle is below.
https://jsfiddle.net/zbmt5qrn/
/* INTEREST RATE SLIDER */
$("#interestRange").slider({
min: 0,
max: 100,
step: 1,
values: [10],
slide: function(event, ui) {
for (var i = 0; i < ui.values.length; ++i) {
$("input.interestValue[data-index=" + i + "]").val(ui.values[i]);
}
}
});
$("input.interestValue").change(function() {
var $this = $(this);
$("#interestValue").slider("values", $this.data("index"), $this.val());
});
function handleInterestChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 24) input.value = 24;
}
var items =[ '8%','24%'];
var oneBig = 100 / (items.length - 1);
$.each(items, function(key,value){
var w = oneBig;
if(key === 0 || key === items.length-1)
w = oneBig/2;
$("#interestLabel").append("<label style='width: "+w+"%'>"+value+"</laben>");
});
I am removing the code about '8%/24%' because it does not seem to be relevant to this question.
There are a couple ways to set the background. You could insert a new element inside #interestRange and change its width based on the slider value. But if you do not need to worry about supporting outdated browsers, it would be much easier to use apply a linear-gradient to the background of #interestRange.
const sliderMin = 0
const sliderMax = 100
const sliderDefaultValue = 10
function setSliderBackground(value){
const sliderRange = sliderMax - sliderMin
const sliderPercent = Math.floor(100 * (value / sliderRange))
$("#interestRange").css({
background: `linear-gradient(90deg, #0000ff ${sliderPercent}%, #ffffff ${sliderPercent}%)`
})
}
function setSliderValue(value){
$("#interestRange").slider("value", value);
}
function setInputValue(value){
$("#interestValue").val(value)
}
$(document).ready(()=>{
$("#interestRange").slider({
min: sliderMin,
max: sliderMax,
step: 1,
// Handle when the user moves the slider
slide: (event, ui)=>{
const sliderValue = ui.value
setInputValue(sliderValue)
setSliderBackground(sliderValue)
}
})
// Handle when the user types in a value
$("#interestValue").change(()=>{
const typedValue = $("#interestValue").val()
setSliderValue(typedValue)
setSliderBackground(typedValue)
})
// Stuff to do when the page loads
setSliderValue(sliderDefaultValue)
setInputValue(sliderDefaultValue)
setSliderBackground(sliderDefaultValue)
})
<link href="https://code.jquery.com/ui/1.12.0-rc.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p>Interest Rate:</p>
<div>
<div id="interestRange"></div>
<div id="interestLabel"></div>
</div>
<div>
<input type="number" id="interestValue" />
</div>

Javascripts code stops working

the problem it's about a roulette that spins every 1 min,
Problem : When I switch from one tab to another on google chrome or any other navigators, the script stops running and the roulette stops (and I need to go back to the tab again in order to make the script work)
image roulette = animation of game
//<![CDATA[
var myRoll = {
nbr : [14, 1, 13, 2, 12, 3, 11, 0, 4, 10, 5, 9, 6, 8 ,7],
initRoll : function(){
var Ccolor;
var nbrCtn = $(".nbr-ctn");
for(j = 0; j < 6 ; j++){
for(i = 0; i < this.nbr.length; i++){
Ccolor = "";
if(this.nbr[i] === 0 ){
Ccolor = "nbr-green";
}else if(this.nbr[i] > 7){
Ccolor = "nbr-black";
}else{
Ccolor = "nbr-red";
}
var elem = '<div class="nbr '+ Ccolor +'" >'+ this.nbr[i] +'</div>';
nbrCtn.append(elem);
}
}
},
lastResult : function(n){
Ccolor = "";
if(n === 0 ){
Ccolor = "nbr nbr-green";
}else if(n > 7){
Ccolor = "nbr nbr-black";
}else{
Ccolor = "nbr nbr-red";
}
var nbrResult = $(".lastResult > div").length;
if(nbrResult === 5 ){
$(".lastResult div:first-child").remove();
}
var elem = '<div class="circle '+ Ccolor +'" >'+ n +'</div>';
$(".lastResult").append(elem);
},
rollAnimation : function(offset, n){
var prog = $(".progress-line");
if(offset){
prog.width("100%");
var nbrCtn = $(".nbr-ctn");
nbrCtn.css("left" , "0px");
nbrCtn.animate({left: "-"+ offset +".5px"}, 6000, 'easeInOutQuint', function(){
myRoll.lastResult(n);
myRoll.countDown();
});
}
},
getRandomInt : function(min, max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
},
startRoll : function(n){
var nbrCtn = $(".nbr-ctn");
var gAnim = $("#game-animation");
var idx = this.nbr.indexOf(n) + this.nbr.length * 4;
var elmWidth = nbrCtn.find(".nbr").width();
var offset = idx * elmWidth - (gAnim.width() / 2);
offset = this.getRandomInt(offset + 5, offset + elmWidth - 5);
this.rollAnimation(offset, n);
},
countDown : function(){
var prog = $(".progress-line");
var gameStatus = $(".rolling > span");
prog.animate({width : "0px"}, {
duration: 30000,
step: function(now){
var rt = (now*3) / 100;
gameStatus.html("Closing in " + rt.toFixed(2));
},
complete: function(){
// when the progress bar be end
gameStatus.html("Rolling ...");
myRoll.startRoll(myRoll.getRandomInt(0, 14));
},
easing: "linear"
});
}
};
window.onload = function(){
myRoll.initRoll();
myRoll.countDown();
};
//]]>
For this you need to implement things in following way (this is just way out).
Basic concept behind bellow code is calculate lag between tab switch and set current state accordingly.
var prevTime,curTime;
var rate = 500; //(miliseconds) you can set it.
function update()
{
var diffTime = curTime - prevTime;
if (diffTime >= rate)
{
//check if difference is more than step value then calculate
//current state accordingly. so you will always be updated as you calculating lags.
// e.g. diffTime = 1500;
// you will need to jump Math.floor(diffTime/rate) which is 3.
// calculate current state.
//your code....
prevTime = curTime;
}
requestAnimationFrame(update);
}

Phaser Game Development - Movement with arrows too fast in Menu

I am testing Phaser doing a simple spaceships game. I have configured some states (boot, load, menu and levelOne) for the game and his functionality.
On the menú I have 3 options in gray color (start, continue and credits), I keep a var called selected to mark which menu is selected (1, 2 or 3). When I press the Up arrow I set selected - 1, and down arrow selected + 1, in the way to navigate between options. It works perfect, but its impossible to select an option because of the change speed, see it yourself: Spaceships
JS code of the menu:
var title = ""
var starfield = null
var selected = 1;
var cursores = null;
var menuOptions = {
start: {title: "Empezar partida", variable: null},
continue: {title: "Continuar partida", variable: null},
credits: {title: "Creditos", variable: null}
}
var menuState = {
downMenu: function(){
selected += 1
console.log(selected)
if(selected>=4){
selected = 1
}
},
upMenu: function(){
selected -= 1
console.log(selected)
if(selected<=0){
selected = 4
}
},
preload: function(){
var me = this;
//console.log('preload')
space.load.bitmapFont('titleFont', 'assets/Fonts/title.png', 'assets/Fonts/title.fnt');
space.load.bitmapFont('menuFont', 'assets/Fonts/menuFont.png', 'assets/Fonts/menuFont.fnt');
space.load.image('background', 'assets/Backgrounds/menuStarfield.png')
},
create: function(){
//console.log('create')
starfield = space.add.image(0, 0, 'background')
space.stage.backgroundColor = '#000000'
title = space.add.bitmapText(50, 50, 'titleFont', 'Deviant Spaceships!', 64);
menuOptions.start.variable = createText(150, menuOptions.start.title)
menuOptions.continue.variable = createText(225, menuOptions.continue.title)
menuOptions.credits.variable = createText(300, menuOptions.credits.title)
cursores = space.input.keyboard.createCursorKeys()
//cursores.onDown.addOnce(this.changeMenu, this)
},
update: function(){
title.text = 'Oh No! Spaceships! \n';
if(cursores.down.isDown){
this.downMenu()
}
if(cursores.up.isDown){
this.upMenu()
}
if(selected == 1){
//menuOptions.start.variable.text = "-> "+menuOptions.start.variable.text
menuOptions.start.variable.fill = '#FFFFFF'
}else{
menuOptions.start.variable.fill = '#999999'
}
if(selected == 2){
//menuOptions.start.variable.text = "-> "+menuOptions.start.variable.text
menuOptions.continue.variable.fill = '#FFFFFF'
}else{
menuOptions.continue.variable.fill = '#999999'
}
if(selected == 3){
//menuOptions.start.variable.text = "-> "+menuOptions.start.variable.text
menuOptions.credits.variable.fill = '#FFFFFF'
}else{
menuOptions.credits.variable.fill = '#999999'
}
menuOptions.continue.variable.text = menuOptions.continue.title
menuOptions.credits.variable.text = menuOptions.credits.title
starfield.x -= 2
if(starfield.x <= -1026){
starfield.x = 0
}
}
}
function createText(y, texto) {
var text = space.add.text(space.world.centerX, y, texto);
text.anchor.set(0.5);
text.align = 'center';
// Font style
text.font = 'Arial Black';
text.fontSize = 50;
text.fontWeight = 'bold';
text.fill = '#999999';
return text;
}
¿How can I take the menu items selected one by one? Is there a way to stop the key being pressed in code every time I add or deduct the selected var?
I had the same problem a couple a weeks ago and I didn't find a nice solution, so I finally made a not very elegant hack... I allow to change the menu just once every a little time (200ms). I'm sure there will be a nicer solution but something like this is what I'm using(check the console):
var game = new Phaser.Game(500, 500, Phaser.CANVAS, 'game');
var selected = 1;
var menuState = {
create:function(){
cursores = game.input.keyboard.createCursorKeys();
this.cambia_menu = this.time.now + 200;
},
downMenu: function(){
selected += 1
console.log(selected)
if(selected>=4){
selected = 1
}
},
upMenu: function(){
selected -= 1
console.log(selected)
if(selected<=0){
selected = 4
}
},
update:function(){
if(cursores.down.isDown && this.cambia_menu<this.time.now){
this.cambia_menu = this.time.now + 200;
this.downMenu();
}
if(cursores.up.isDown && this.cambia_menu<this.time.now){
this.cambia_menu = this.time.now + 200;
this.upMenu();
}
},
};
game.state.add('menu', menuState);
game.state.start('menu');
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.min.js"></script>
<div id="game"></div>

cant get the right values for previous minutes

<script>
var train_arrivals = [
'00:10',
'00:15',
'00:23',
'00:35',
'00:43',
'00:58',
'01:05',
'01:13',
'01:20',
'01:37',
'01:48',
'02:15',
'02:25',
'02:40',
'02:55',
'03:00',
'03:09',
'03:21',
'03:37',
'03:52',
'04:15',
'04:30',
'04:44',
'04:58',
'05:16',
'05:31',
'05:49',
'06:00',
'06:26',
'06:56',
'08:06',
'07:24',
'07:43',
'07:58',
'08:06',
'08:13',
'08:28',
'08:43',
'08:58',
'09:05',
'09:13',
'09:28',
'09:43',
'09:58',
'10:05',
'10:38',
'11:00',
'11:38',
'12:38',
'13:38',
'14:38',
'15:38',
'16:00',
'16:39',
'17:00',
'17:06',
'17:27',
'17:57',
'20:20',
'20:45',
'21:50',
'23:25',
'23:30',
'23:48'
];
$(function() {
var today = new Date();
var now = moment([today.getFullYear(), today.getMonth(), today.getMinutes(), today.getHours(), today.getMinutes()]);
var setted = '';
var count = 1;
for (var i=0; i<train_arrivals.length; i++){
var entry = train_arrivals[i];
time = entry.split(":");
var arrival = moment([today.getFullYear(), today.getMonth(), today.getMinutes(), time[0], time[1]]);
diff = arrival.diff(now, 'minutes');
if (!setted && diff > 0) {
$("#arrival_list").append($("<li id="+count+" style='font-size: x-large' class='bg-success'>").text(diff + ' min '));
setted = count;
} else
$("#arrival_list").append($("<li id="+count+" class='bg-info'>").text(diff + ' min'));
if (setted && count >= setted + 2) break;
if (!setted && count > 1)
$('#'+count).remove();
count++;
}
});
</script>
I have this code for this little web app http://nexttrain.elvismdev.com/
The idea is to show next train arrival to the station due the train arrivals times given at the beginning of the code, the value inside the green row is the first next train approaching to the station, after it are two more train arrivals showing up, and back from it, should show the how many times ago the last train was there. I can't figure it out what is wrong over there that I am getting the wrong value with that so long minutes left, when it should show only a short time period.
If somebody could just look at my code and point me what could I be missing, In real I am not so much proficient in javascript, and time calculations always drive me crazy with issues like this.
Also I am using moment.js
Instead of adding <ul> elements to the DOM (Document Object Model) and then deleting them again, why not try this approach: First find the nearest future departure time, and then work backwards and get the time immediately before that. Add the previous time to the DOM as a <ul>, and then add the nearest future time. Something like this:
var train_arrivals = [
'00:10',
'00:15',
'00:23',
'00:35',
'00:43',
'00:58',
'01:05',
'01:13',
'01:20',
'01:37',
'01:48',
'02:15',
'02:25',
'02:40',
'02:55',
'03:00',
'03:09',
'03:21',
'03:37',
'03:52',
'04:15',
'04:30',
'04:44',
'04:58',
'05:16',
'05:31',
'05:49',
'06:00',
'06:26',
'06:56',
'08:06',
'07:24',
'07:43',
'07:58',
'08:06',
'08:13',
'08:28',
'08:43',
'08:58',
'09:05',
'09:13',
'09:28',
'09:43',
'09:58',
'10:05',
'10:38',
'11:00',
'11:38',
'12:38',
'13:38',
'14:38',
'15:38',
'16:00',
'16:39',
'17:00',
'17:06',
'17:27',
'17:57',
'20:20',
'20:45',
'21:50',
'23:25',
'23:30',
'23:48'
];
$(function() {
var today = moment();
var todayString = today.format("YYYY-MM-DD");
var now = today;
var setted = '';
var count = 1;
for (var i=0; i<train_arrivals.length; i++){
var entry = train_arrivals[i];
var arrival = moment(todayString + ' ' + entry);
diff = arrival.diff(now, 'minutes');
if (!setted && diff > 0) {
if (i > 0) {
var prevEntry = train_arrivals[i - 1];
var prevArrival = moment(todayString + ' ' + prevEntry);
var prevDiff = prevArrival.diff(now, 'minutes');
$("#arrival_list").append($("<li id="+count+" class='bg-info'>").text(prevDiff + ' min'));
}
$("#arrival_list").append($("<li id="+count+" style='font-size: x-large' class='bg-success'>").text(diff + ' min '));
setted = count;
}
else if (diff > 0){
$("#arrival_list").append($("<li id="+count+" class='bg-info'>").text(diff + ' min'));
}
if (setted && count >= setted + 2) break;
count++;
}
});
Here's a working jsFiddle: http://jsfiddle.net/W84Gm/1/

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;

Categories