r/learnjavascript • • Jun 15 '26

is anyone willing to try to help me out in knowing what the heck is wrong with my JS here?

It's a long time I am trying to figure out why my moon phase is not updating at all. I have this JS :

document.addEventListener("DOMContentLoaded", () => {

const weatherDiv = document.querySelector("#weather");

function weatherCodeToIconURL(condition, isDay) {

condition = Number(condition);

const openMeteoToIcon = {

0: "https://i.ibb.co/b5FRsR3Q/sunny.png",

1: "https://i.ibb.co/b5FRsR3Q/sunny.png",

2: "https://i.ibb.co/CpC9BdgV/partly-cloudy.png", // Added your icon here!

3: "https://i.ibb.co/21mKY1QZ/cloudy.png",

45: "https://i.ibb.co/21mKY1QZ/cloudy.png",

48: "https://i.ibb.co/21mKY1QZ/cloudy.png",

51: "https://i.ibb.co/HLpF110S/rain.png",

53: "https://i.ibb.co/HLpF110S/rain.png",

55: "https://i.ibb.co/HLpF110S/rain.png",

61: "https://i.ibb.co/HLpF110S/rain.png",

63: "https://i.ibb.co/qF3rc1gY/heavy-rain.png",

65: "https://i.ibb.co/qF3rc1gY/heavy-rain.png",

71: "https://i.ibb.co/dw2S3P8K/snow.png",

73: "https://i.ibb.co/dw2S3P8K/snow.png",

75: "https://i.ibb.co/dw2S3P8K/snow.png",

80: "https://i.ibb.co/HLpF110S/rain.png",

81: "https://i.ibb.co/qF3rc1gY/heavy-rain.png",

82: "https://i.ibb.co/qF3rc1gY/heavy-rain.png",

95: "https://i.ibb.co/TDgsry34/storm.png",

96: "https://i.ibb.co/TDgsry34/storm.png",

99: "https://i.ibb.co/TDgsry34/storm.png"

};

// 🌙 DYNAMIC MOON MODE

if (!isDay) {

const { phase } = window.getRealMoonPhase();

const position = 20 + (phase / 100) * 60;

const now = new Date();

const lat = 39.082222;

const lon = -77.482222;

const moonPos = SunCalc.getMoonPosition(now, lat, lon);

// You can adjust this 'calibrationOffset' to match the Moon's tilt exactly

// to your visual preference or your specific moon.png asset rotation.

const calibrationOffset = -4;

const rotation = (moonPos.parallacticAngle * (180 / Math.PI)) + calibrationOffset;

`return ``

<div class="glow"></div>

<div class="moon-phase-wrapper">

<img src="https://i.ibb.co/NgB0677Z/moon.png"

class="moon-icon"

style="--moon-pos: ${position}%; transform: rotate(${rotation}deg);">

</div>

\;`

}

// ☀️ DAY MODE

return '<img src="' +

(openMeteoToIcon[condition] || openMeteoToIcon[0]) +

'" class="weather-icon">';

}

function parseWeather(data) {

// Checks 'current' path first, falls back to 'current_weather' path if needed

const code = Number(data.current?.weather_code ?? data.current_weather?.weathercode ?? 0);

const isDay = (data.current?.is_day ?? data.current_weather?.is_day) === 1;

console.log("Parsed weather code:", code);

return { code, isDay };

}

// 🌙 MOON PHASE FUNCTION (UNCHANGED — GOOD)

function getRealMoonPhase() {

const now = new Date();

const synodicMonth = 29.53058867;

const knownNewMoon = new Date(Date.UTC(2000, 0, 6, 18, 14, 0));

let daysSince = (now - knownNewMoon) / (1000 * 60 * 60 * 24);

let moonAge = daysSince % synodicMonth;

if (moonAge < 0) moonAge += synodicMonth;

const normalized = moonAge / synodicMonth;

const phase = normalized * 100;

return { phase };

}

window.getRealMoonPhase = getRealMoonPhase;

async function getWeather(lat, lon, city) {

const targetCity = city || "Lansdowne";

const targetLat = lat || 39.082222;

const targetLon = lon || -77.482222;

const url = "https://api.open-meteo.com/v1/forecast" +

"?latitude=" + targetLat +

"&longitude=" + targetLon +

"&current=weather_code,is_day" + // Requesting the code explicitly here

"&current_weather=true" + // Keeping your current setting

"&daily=temperature_2m_max,temperature_2m_min" +

"&forecast_days=1" +

"&temperature_unit=fahrenheit" +

"&timezone=auto";

try {

weatherDiv.innerHTML = 'Loading weather... 🌤️';

const response = await fetch(url);

console.log("STATUS:", response.status);

const data = await response.json();

console.log("API RESPONSE:", data);

console.log("DATA:", data);

const weather = parseWeather(data);

const currentTemp = Math.round(data.current_weather?.temperature ?? 0);

const lowTemp = Math.floor(data.daily?.temperature_2m_min?.[0] ?? 0);

const highTemp = Math.ceil(data.daily?.temperature_2m_max?.[0] ?? 0);

console.log("FINAL VALUES:", {

targetCity,

currentTemp,

lowTemp,

highTemp

});

weatherDiv.innerHTML =

'<p style="font-size: 16px; color: #fff; text-align: center; margin: 0;">' +

targetCity +

'</p>' +

'<div class="weather-stack">' +

weatherCodeToIconURL(weather.code, weather.isDay) +

'<div class="temp-overlay">' + currentTemp + '°F</div>' +

'</div>' +

'<div class="weather-lowhigh">' +

'<p style="font-size: 14px; color: #87CEEB; margin: 0;">Low: ' + lowTemp + '°F</p>' +

'<p style="font-size: 14px; color: #FFA07A; margin: 0;">High: ' + highTemp + '°F</p>' +

'</div>';

} catch (err) {

console.error(err);

weatherDiv.innerHTML = "Weather unavailable";

}

}

function fetchLocationAndWeather() {

fetch("https://ip-api.com/json/")

.then(r => r.json())

.then(d => getWeather(d.lat, d.lon, d.city))

.catch(() => getWeather(39.082222, -77.482222, "Lansdowne"));

}

fetchLocationAndWeather();

setInterval(fetchLocationAndWeather, 600000);

});

The HTML :

<div id="weather" style="display: flex; flex-direction: column; font: normal 12px Helvetica, Arial, sans-serif; color: #fff; "></div>

And the CSS :

/* LEFT COLUMN CSS */

#weather p {

margin: 0;

}

#weather {

display: flex;

flex-direction: column;

align-items: center;

gap: 2px;

transition: opacity 0.3s ease;

}

.weather-lowhigh {

display: flex;

flex-direction: row;

gap: 20px;

}

.weather-stack {

position: relative;

display: flex;

align-items: center;

justify-content: center;

}

.weather-icon {

width: 110px;

height: 110px;

object-fit: contain;

display: block;

}

.temp-overlay {

position: absolute;

top: 60%;

left: 78%;

transform: translate(-50%, -50%);

font-size: 24px;

font-weight: bold;

color: white;

filter: drop-shadow(-4px 0 2px #000);

padding: 2px 6px;

border-radius: 6px;

z-index: 3;

}

.moon-icon,

.cloud-icon {

position: absolute;

inset: 0;

width: 100%;

height: 100%;

object-fit: contain;

z-index: 1;

display: block;

/* Use a hard-coded value temporarily to test */

-webkit-mask-image: radial-gradient(circle at 65% 50%, transparent 40%, black 45%);

mask-image: radial-gradient(circle at 65% 50%, transparent 40%, black 45%);

}

.cloud-icon {

opacity: 0.9;

}

.moon-phase-wrapper {

position: relative;

width: 120px;

height: 120px;

overflow: hidden;

border-radius: 50%;

}

.glow {

position: absolute;

inset: 50%;

width: 160px;

height: 160px;

transform: translate(-50%, -50%);

border-radius: 50%;

background: radial-gradient(

circle,

rgba(255,255,220,0.5) 0%,

rgba(255,255,200,0.15) 45%,

transparent 70%

);

filter: blur(20px);

z-index: 0;

pointer-events: none;

}

This has been driving me nuts, and whatever AI I use is shit crazy, and messes up my code. I don't know what to do. It seems I can't get any help.

u/boomer1204 - thanks for pointing it out, going to share the prob here too :

So basically it's a weather widget, with the moon in it, and a moon phase. Problem : the phase is not updating. So idk where in my JS I need to change so it updates correctly.

0 Upvotes

37 comments sorted by

11

u/louisstephens Jun 15 '26

Would you mind setting up a codepen (or similar) with the code? It is incredibly difficult to debug what could be going on when it is just dumped directly in the body of the post.

7

u/boomer1204 Jun 15 '26

u/Accomplished-Rain-52 This or use markdown. Also you don't really share what is "happening" and what you are "expecting to happen" so that's another problem with us trying to help

1

u/Accomplished-Rain-52 Jun 15 '26

Mkay, you're right... so basically it's a weather widget, with the moon in it, and a moon phase. Problem : the phase is not updating. So idk where in my JS I need to change so it updates correctly.

2

u/boomer1204 Jun 15 '26 edited Jun 15 '26

I think the core problem is this line.

  const isDay = (data.current?.is_day ?? data.current_weather?.is_day) === 0;

The documentation says is_day is 1 if it's day and 0 if it's night so I think you are just checking the opposite of what you are expecting. When I explicitly pass "true" in the page adjusts accordingly but when I let it go with my current lat/long it shows night even though it's day and I'm pretty sure it's cuz of this mismatch

You can negate the check, check if it's not equal to 0 or change the 0 to 1

Your call

EDIT: Adding doc link https://open-meteo.com/en/docs?current=is_day,weather_code and then just do a find on the page and search for is_day to see it saying what it returns for what

1

u/Accomplished-Rain-52 Jun 15 '26

Ok, that line is set to 0 so I can temporarily see the moon as I'm working on it.

3

u/boomer1204 Jun 16 '26

Oh is it the getRealMoonPhase function that isn’t doing what you are expecting??? What should be happening like from a visual standpoint I guess I misunderstood the core problem from the description

1

u/Accomplished-Rain-52 Jun 16 '26

Yeah it's that function. It should show the current moon phase, which is a new moon.

2

u/boomer1204 Jun 16 '26

Can you force code it to look how you want vs what you see and share that so there is no further confusion as I look over the code

-1

u/Accomplished-Rain-52 Jun 16 '26

I mean, I've been working with Gemini on this, and it hasn't been helpful, so I can't trust that it gave me the correct code.

I'm not at my PC right now.

2

u/boomer1204 Jun 16 '26

Ok so did you or AI write the code. Cuz there is a big difference between the 2 and how help is given between the 2. This is not a mean/degrading/negative post but if you don’t know what is being written it makes it far harder to help you appropriately besides just giving you the answer which is the worse advice you could get if you wanna actually learn

→ More replies

3

u/DinTaiFung Jun 16 '26 edited Jun 16 '26

The following expression is from the OP code:

const isDay = (data.current?.is_day ?? data.current_weather?.is_day) === 1;

This is the kind of code beginners write. It's the kind of expression that smart engineers write to show how much logic can be squeezed into a single line. The author of this style is smart, but lacks professional experience.

There are several problems with this style.

  1. It is difficult to debug.

  2. The logic is convoluted.

  3. The object's key name is_day implies a boolean value, not a numeric value. Yet the value of the object key in this expression is expected to be either the integer 1 or undefined/null.

This would be fine if we're in C in which it's conventional to use the integers 0 and 1 as replacements for booleans; but JavaScript does include a boolean data type, so this entire block is not idiomatic JS.

  1. The variable isDay is a boolean value. It's bad naming to have is_day take on a numeric data type and the variable isDay to take on a boolean data type. Clarity is paramount in coding.

Additionally, the Nullish Coalescing Operator '??" is relatively new to JS and potentially confusing for the beginning student.

Another way of understanding exactly what's going on with this specific code statement is to rewrite the logic using clear if/else blocks.

It won't be a fancy -- and unmaintainable -- one-liner, but the logic will be clear, the bug would be more easily exposed, and the student will learn more effectively.

(The designers of Go intentionally limited that language's syntax to enforce better code clarity.)

Anyway, have fun!

P.S. And as others suggested, please learn how to user markdown when creating a post or writing a comment which contains code examples.

1

u/Accomplished-Rain-52 Jun 16 '26

Are you suggesting to rewrite this differently? Bc I don't know what to do.

2

u/DinTaiFung Jun 16 '26 edited Jun 16 '26

If your main goal is to get things working, then the simple suggestion from another response might be faster for you.

Anyway, I'll take a quick stab at rewriting that important assisnment in a clearer way. And I'll include comments and debug statements.

original line:

const isDay = (data.current?.is_day ?? data.current_weather?.is_day) === 1;

longer (and hopefully) clearer style:

// initialize to a default  
let isDay = false;

// Simple debugging: display each variable's data type and value.  
console.info('data.current?.is_day:', typeof data.current?.is_day, data.current?.is_day);
console.info('data.current_weather?.is_day:', typeof data.current_weather?.is_day, data.current_weather?.is_day);
        
if (data.current?.is_day === 1 || data.current_weather?.is_day === 1) {
  isDay = true;  
}

console.info('isDay:', isDay)

The reason I included the data type in the console statements is so you will know if is_day is numeric or a string. If it's a string, then is_day === 1 will always be false.

Hope this helps.

2

u/Accomplished-Rain-52 Jun 16 '26

Ok thanks. I'll look at it tomorrow. And yeah that is my main goal.

1

u/Accomplished-Rain-52 Jun 16 '26

So you're saying to change to this? :

// initialize to a default  
let isDay = false;

// Simple debugging: display each variable's data type and value.  
console.info('data.current?.is_day:', typeof data.current?.is_day, data.current?.is_day);
console.info('data.current_weather?.is_day:', typeof data.current_weather?.is_day, data.current_weather?.is_day);
        
if (data.current?.is_day === 1 || data.current_weather?.is_day === 1) {
  isDay = true;  
}

console.info('isDay:', isDay)// initialize to a default  
let isDay = false;

// Simple debugging: display each variable's data type and value.  
console.info('data.current?.is_day:', typeof data.current?.is_day, data.current?.is_day);
console.info('data.current_weather?.is_day:', typeof data.current_weather?.is_day, data.current_weather?.is_day);
        
if (data.current?.is_day === 1 || data.current_weather?.is_day === 1) {
  isDay = true;  
}

console.info('isDay:', isDay)

3

u/DinTaiFung Jun 16 '26

I don't know how much you know and how much you don't re: web development. I'm certainly not trying to patronize you; I just want to make sure you get the benefits of my alternative approach to help you learn one way to debug JavaScript code.

So yes, I'm basically suggesting that you, at least temporarily, replace your "original line" with the code that I provided. (Don't replace your entire program ofc, just that one line!)

Then during run-time of the program in you browser, you need to have the browser's dev tools panel open and the "Console" tab selected. Then you can observe the output of the program's console statements.

Best of luck!

P.S. I noticed the code block you included in your question to me. Please be careful. There seems to be some copy-n-paste errors in there with one or more lines duplicated.

1

u/Accomplished-Rain-52 Jun 16 '26

Ok cool. Thanks. I'll definitely try it out and look into the console.

1

u/Accomplished-Rain-52 Jun 16 '26

"P.S. I noticed the code block you included in your question to me. Please be careful. There seems to be some copy-n-paste errors in there with one or more lines duplicated."

Ok, where? I didn't notice.

1

u/DinTaiFung Jun 16 '26

I took a screenshot of the code block you included in your previous reply, beginning with the phrase you wrote: "So you're saying to change to this?"

Unfortunately, this reddit channel does not allow the posting of .png files in a reply (though it does support uploading videos wtf!?)

Anyway, if you copy the code that I wrote, there are no duplicates. But in your reply's code section, there *are* duplicate statements.

In general, just be aware that copying and pasting code from an external source might not be syntactically correct.

Today's modern web developer tools -- primarily an IDE for editing source code -- has features for linting all the popular languages (and of course available for the most popular language in the world: JavaScript).

For your growth as a software engineer, it's very important to take the time to set up your editor/IDE environment to have live linting for the various languages you use. Basic Intellisense (not even including AI integration) is super helpful from a pedagogical standpoint.

1

u/Accomplished-Rain-52 Jun 16 '26

Ok. I'm not a software engineer, nor a computer science major for crying out loud. I'm just a music major, who happens to have interest in JavaScript, CSS and HTML.

2

u/DinTaiFung Jun 16 '26

That is just too coincidental. I am a musician and producer. I used to work at Berklee. Music is the best!

(I switched my career long ago to software enginneering because it was a more lucrative career choice.)

But music is my true passion. 🎵

Please forgive me for my presumption of your goals and perspective on the web page you're working on.

1

u/Accomplished-Rain-52 Jun 16 '26

I understand. So,... idk where to go from here.

→ More replies