/r/learnjavascript
This subreddit is for anyone who wants to learn JavaScript or help others do so.
Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend.
This subreddit is a place for people to learn JavaScript together. Everyone should feel comfortable asking any and all JavaScript questions they have here.
With a nod to practicality, questions and posts about HTML, CSS, and web developer tools are also encouraged.
No Self-Promotion. The following are not allowed: Requests for subscribers, asking for "test users" for your new JS course, offering paid mentorships, and/or premium courses. Even if there is a coupon discount, no. If you're in doubt, message the mods first.
Good Titles - Write a descriptive title. Titles that begin with "hey guys" will be removed.
Related Subreddits
If you want to post something self-promotional, please message the mods first. Personal blog posts that are relevant to the subreddit's stated subject matter don't need prior approval (and are encouraged!).
/r/learnjavascript
I recently wrote an article in which I measured the distance between two objects using JavaScript.
This helped me determine whether an enemy is within a tower's range.
Check it out and drop your thoughts in the comments!
Hi Folks, i'm making a card game in Javascript.
Cards can move to multiple different hands and decks, and at any point in time the range of things that can have focus can change quite quickly.
I have it so the DOM changes properly and the cards (<figure/>) are properly reparented into their decks or hands (<section/>). They are given a Tab Order explicitly and this works fine and logically, for any given moment. BUT!
Since layout matters, I'd also like to be able to implement cursors as WASD to move around the cards and decks.
I could envisage making a list of links in the data to say what is up, down, left and right of each other, but as both the positions of things, and whether or not they're focusable, can change quite a LOT and I don't like the idea of re-creating a data structure for this every time the game state changes.
After all: it's all there on the screen.
So is there an obvious way to figure out which focusable object is the closest to the current one, in given screen direction.
I'm struggling to come up with the best way to think about this problem - what other approaches would make sense?
Thanks!
I'm rather new to coding, but I've grown interested in it recently, especially due to a personal project I'd like to undergo. One major roadblock I'm hitting at the moment is that I'd like to pull from a table in a database or such (like I've currently got information in a google sheets doc) and have it auto populate based on the name entered in the main spot.
Basically, if I put a name into a text box, it should auto populate the appropriate information correlating with said name from the data table.
I know typing out a full answer might be difficult and I'd honestly like to understand the why, not just the how. So if anyone knows of some resources that might be able to help, I'd be so very grateful!
Built a calendar library with js, I am wondering if there are tutorials on how to build 2d canvas library, 2d animation library, 3d rendering engine or similar.
Say that I have these html strings....
<input class="SUBMIT_BUTTON" id="SUBMIT_BUTTON_1" refID='clock' type="submit" value="Clock">
<input class="SUBMIT_BUTTON" id="SUBMIT_BUTTON_2" refID='radio' type="submit" value="Radio">
I don't want to get hung up on the names..... just assume I have to work with these.
I know that I can do something like this in javascript:const buttons = document.getElementsByClassName("SUBMIT_BUTTON");
but how can I pick the refID='clock' or the refID='radio' elements?
I need to be able to drill down to:
class="SUBMIT_BUTTON" refID='clock'
or the
class="SUBMIT_BUTTON" refID='radio'
elements so I can change the text of the button on either of those elements.
I know how to reference them by ID or by CLASS, but not by CLASS[refID='clock'] or CLASS[refID='radio' ]
- thanks
Say that I have these html strings....
<input class="SUBMIT_BUTTON" id="SUBMIT_BUTTON_1" refID='clock' type="submit" value="Clock">
<input class="SUBMIT_BUTTON" id="SUBMIT_BUTTON_2" refID='radio' type="submit" value="Radio">
I don't want to get hung up on the names..... just assume I have to work with these.
I know that I can do something like this in javascript:const buttons = document.getElementsByClassName("SUBMIT_BUTTON");
but how can I pick the refID='clock' or the refID='radio' elements?
I need to be able to drill down to:
class="SUBMIT_BUTTON" refID='clock'
or the
class="SUBMIT_BUTTON" refID='radio'
elements so I can change the text of the button on either of those elements.
I know how to reference them by ID or by CLASS, but not by CLASS[refID='clock'] or CLASS[refID='radio' ]
- thanks
Javascript is weird compared to other languages.
I started programming in university using languages like Pascal, C++, and Java. Even though they were lower-level languages (closer to the machine). Javascript was definitely the weirdest one among them all.
Even though it's getting executed from top to bottom as in any other language, you are able to access variables or functions before even declaring them.
That's a javascript feature, which is known as hoisting, which I discussed deeply in the linked video below.
Hello people, sorry to bother everyone again. I would just like to know how one would export a script tag from the front and read it in another JS file.
Im going to write a npm for FileReader, will publish it and share the link when I'm done.
FileReader can be a lot of code to write over and over again.
Im good with Java just the JavaScript is still kinda new to me.
On the External JS file I need a file name to create a link.
I would prefer to do it from the HTML and not create another js file just to export a value.
Also would like to do it without fetch API's
Is there an import body.json or something I need for the external JS File. Do I read the entire HTML file and search for element values like express or what? Would I have to code this in Java?
Like this or something
import("./data.json", { with: { type: "json" } });
There is got be a way that has already been coded, right like most of you guys say. Don't re-invent the wheel
<script name="ex.js" type="module"> what would the link be?
New to JS, junior engineer at my first job. I got assigned an EDI project, we use mirth for our transactions. I can't seem to get the parsing down for this EDI message, GPT / Claude is no help. Can anyone take a look and help out please. I've been doing this for hours and hours and my deadline is tomorrow.
function parse_204_for_create_shipment_V3(msg, needs_approval_status, location_keys) {
var msgObj = getStdJsonCreateShipment();
var all_commodity_types = {
"PLT": "Pallets",
"CTN": "Pieces"
}
msgObj.uuid = channelMap.get("UUID")+"";
msgObj.shipment.external_id = channelMap.get("UUID")+"";
msgObj.shipment.company_api_key = location_keys['company_api_key'];
msgObj.shipment.location_api_key = location_keys['location_api_key'];
// Below keys used for testing:
msgObj.shipment.shipment_type = "Truckload";
msgObj.shipment.subtype = "Third Party";
switch (msg['B2']['B2.06']['B2.06.1'].toString()) {
case 'PP':
msgObj.shipment.payment_type = "Prepaid"
break
case 'CC':
msgObj.shipment.payment_type = "Collect"
break
case 'TP':
msgObj.shipment.payment_type = "Third Party Pay"
break
}
msgObj.shipment.po = msg['B2']['B2.04']['B2.04.1'].toString();
msgObj.shipment.from_company_name = msg['N1'][1]['N1.02']['N1.02.1'].toString();
msgObj.shipment.from_address_1 = msg['N3'][1]['N3.01']['N3.01.1'].toString();
msgObj.shipment.from_address_2 = msg['N3'][1]['N3.02']['N3.02.1'].toString();
msgObj.shipment.from_city = msg['N4'][1]['N4.01']['N4.01.1'].toString();
msgObj.shipment.from_state = msg['N4'][1]['N4.02']['N4.02.1'].toString();
msgObj.shipment.from_zip = sanitizeZipcode(msg['N4'][1]['N4.03']['N4.03.1'].toString());
msgObj.shipment.from_contact_name = msg['N1'][1]['N1.02']['N1.02.1'].toString();
msgObj.shipment.to_company_name = msg['N1'][2]['N1.02']['N1.02.1'].toString();
msgObj.shipment.to_address_1 = msg['N3'][2]['N3.01']['N3.01.1'].toString();
msgObj.shipment.to_city = msg['N4'][2]['N4.01']['N4.01.1'].toString();
msgObj.shipment.to_state = msg['N4'][2]['N4.02']['N4.02.1'].toString();
msgObj.shipment.to_zip = sanitizeZipcode(msg['N4'][2]['N4.03']['N4.03.1'].toString());
msgObj.shipment.needs_approval = needs_approval_status.toString();
`if (msg['G62'].length() > 0) {`
`var deliver_not_before = ""`
`var deliver_not_later = ""`
`var ship_not_later = ""`
`var ship_not_before = ""`
`var earliest_deliver_time = ""`
`var earliest_pickup_time = ""`
`var latest_pickup_time = ""`
`var latest_deliver_time = ""`
`for (var i = 0; i < msg['G62'].length(); i++) {`
`var segmentDate = msg['G62'][i]['G62.01']['G62.01.1'].toString();`
`var segmentTime = msg['G62'][i]['G62.03']['G62.03.1'].toString();`
`if (segmentDate == '53' ){`
deliver_not_before = msg['G62'][i]['G62.02']['G62.02.1'].toString();
`} else if ( segmentDate == '54') {`
deliver_not_later = msg['G62'][i]['G62.02']['G62.02.1'].toString();
`} else if ( segmentDate == '38') {`
ship_not_later = msg['G62'][i]['G62.02']['G62.02.1'].toString();
`} else if (segmentDate == '37') {`
ship_not_before = msg['G62'][i]['G62.02']['G62.02.1'].toString();
`}`
`if (segmentTime == 'G') {`
earliest_deliver_time = msg['G62'][i]['G62.04']['G62.04.1'].toString();
`} else if (segmentTime == 'I') {`
earliest_pickup_time = msg['G62'][i]['G62.04']['G62.04.1'].toString();
`} else if (segmentTime == 'K') {`
latest_pickup_time = msg['G62'][i]['G62.04']['G62.04.1'].toString();
`} else if (segmentTime == 'L') {`
latest_deliver_time = msg['G62'][i]['G62.04']['G62.04.1'].toString();
`}`
`}`
`msgObj.shipment.pickup_date = ship_not_before`
`msgObj.shipment.delivery_date = deliver_not_before`
`}`
if (msg['L11']) {
try {
for (var i = 0; i < msg['L11'].length(); i++) {
if ((msg['L11'][i]['L11.02']['L11.02.1']) == 'BM') {
msgObj.shipment.received_edi_information.BM = msg['L11'][i]['L11.01']['L11.01.1'].toString();
}
if ((msg['L11'][i]['L11.02']['L11.02.1']) == 'TN') {
msgObj.shipment.received_edi_information.TN = msg['L11'][i]['L11.01']['L11.01.1'].toString();
}
if ((msg['L11'][i]['L11.02']['L11.02.1']) == 'SI') {
msgObj.shipment.received_edi_information.SI = msg['L11'][i]['L11.01']['L11.01.1'].toString();
}
}
} catch (ex) {
logger.error(ex);
}
}
if (msg['OID'].length() > 0) {
try{
msgObj.shipment.received_edi_information.OQ = msg['OID'][1]['OID.01']['OID.01.1'].toString();
} catch (ex) {
logger.error(ex);
}
}
if ((msg['G61'].length() > 1)) {
msgObj.shipment.from_email = msg['G61'][1]['G61.02']['G61.02.1'].toString();
var phoneNumer = msg['G61'][1]['G61.04']['G61.04.1'].toString();
} else {
msgObj.shipment.from_email = msg['G61']['G61.02']['G61.02.1'].toString();
var phoneNumer = msg['G61']['G61.04']['G61.04.1'].toString();
}
// Check if phone number or not
msgObj.shipment.from_phone = phoneNumer.replace(/-/g, "");
msgObj.shipment.send_from_email = "false";
msgObj.shipment.send_to_email = "false";
if (msg['L5'][0]) {
var commodity_type = msg['L5'][0]['L5.05']['L5.05.1'].toString();
msgObj.shipment.shipment_units[0].commodity_package = all_commodity_types[commodity_type];
msgObj.shipment.shipment_units[0].commodity_name = msg['L5'][0]['L5.02']['L5.02.1'].toString();
}
if (msg['NTE']) {
var special_msg = "";
for (var i = 0; i < msg['NTE'].length(); i++) {
special_msg += msg['NTE'][i]['NTE.02']['NTE.02.1'];
}
msgObj.shipment.shipment_special_instructions = special_msg;
}
msgObj.shipment.shipment_units[0].commodity_quantity = msg['AT8'][0]['AT8.05']['AT8.05.1'].toString();
msgObj.shipment.shipment_units[0].commodity_length = 0.0;
msgObj.shipment.shipment_units[0].commodity_width = 0.0;
msgObj.shipment.shipment_units[0].commodity_height = 0.0;
msgObj.shipment.shipment_units[0].commodity_dimension_unit = "in";
msgObj.shipment.shipment_units[0].commodity_weight = msg['AT8'][0]['AT8.03']['AT8.03.1'].toString();
channelMap.put("msgJson", JsonUtil.prettyPrint(JSON.stringify(msgObj)))
return msgObj
}
EDI message format I am trying to parse:
ISA*00* *00* *ZZ*FAKECOMPANY *ZZ*RANDOMCO *250202*1204*U*00401*000567890*0*P*`~
GS*SM*FAKECOMPANY*RANDOMCO*20250202*1204*98765*X*004010~
ST*204*98765~
B2**RANDOMCO**123456789**PP~
B2A*01*LT~
L11*XYZ123*11~
L11*CONTAINER*6Y~
L11*TEAM*ZZ~
L11*OUTBOUND*12~
G62*64*20250202*1*1415~
MS3*RANDOMCO*A**M~
AT5*EXP~
NTE**TOTAL DISTANCE = 250 MI~
N1*OB*FAKECOMPANY*ZZ*9876543210001~
N3*1234 SAMPLE STREET*SUITE 500~
N4*DALLAS*TX*75201*USA~
G61*OC*Dispatch*TE*555-123-4567~
G61*OC*Support*EM*support@fakecompany.com~
N1*BT*Sample Logistics*ZZ*ZZ~
N3*789 Logistics Ave~
N4*Houston*TX*77001*USA~
N1*BN*FAKE LOGISTICS CORP~
N7**123456*********XJ****01234*******78XJ~
S5*1*CL*35000*L*20*PC~
L11*ABC9876*BM~
L11*6543210*CO~
L11*XYZ-B-ABC9876-1*SI~
G62*10*20250203*Y*0930~
AT8*G*L*35000*20~
N1*SF*SAMPLE WAREHOUSE (S)*93*08-00123~
N3*456 Warehouse Lane~
N4*Memphis*TN*38116*USA~
G61*SH*Alex Johnson*TE*555-789-1234~
OID*SI*XYZ-B-ABC9876-1**TE*20*L*35000~
L5*1*LIQUID CHEMICAL SOLUTION*60*N**12345*PL~
AT8*G*L*35000*20~
G61*HM*SAFETYLINE*TE*888-999-0000~
LH1*LB*35001*UN1234*******II~
LH2*CHEMICAL SOLUTION MIX~
S5*99*CU*35000*L*20*PC~
L11*ABC9876*BM~
L11*6543210*CO~
L11*XYZ-B-ABC9876-1*SI~
G62*02*20250203*Z*1000~
AT8*G*L*35000*20~
NTE**Order subject to T&Cs found at http://fakecompany.com/Terms\~
NTE**ENSURE SAFE HANDLING UPON ARRIVAL~
NTE**REQUIRES SECURE STORAGE~
NTE**DELIVERY WINDOW: ____________~
NTE**CALL CONTACT AT 555-222-3333 PRIOR TO DELIVERY~
NTE**WAREHOUSE EQUIPPED WITH FORKLIFT~
N1*CN*MIDWEST CHEMICAL SOLUTIONS*93*07-654321~
N3*9999 Chemical Blvd~
N4*Chicago*IL*60601*USA~
G61*DC*Logistics*TE*555-555-5555~
OID*SI*XYZ-B-ABC9876-1**TE*20*L*35000~
L5*1*LIQUID CHEMICAL SOLUTION*60*N**12345*PL~
AT8*G*L*35000*20~
G61*HM*SAFETYLINE*TE*888-999-0000~
LH1*LB*35001*UN1234*******II~
LH2*CHEMICAL SOLUTION MIX~
L3*35000*N***65432******20*L~
SE*61*98765~
GE*1*98765~
IEA*1*000567890~
I have been learning JavaScript for about half a month now and I am learning DOM manipulation. I was watching the 12 hour course by BroCode. He was teaching about Event Listeners and teaches us how to move the div element using keydown event listener. He does it by changing the style.top property however I want to do it differently and use the transform property. Moving my element in the Y-axis works fine but it does not move in the X-axis. Here is the code:
const myBox=document.getElementById("myBox"); const moveAmount=100; //coordinates let x=0; let y=0; document.addEventListener("keydown",event=>{ if(event.key.startsWith("Arrow")){ event.preventDefault(); switch(event.key){ case "ArrowUp": y-=moveAmount; break; case "ArrowDown": y+=moveAmount; break; case "ArrowLeft": x-=moveAmount; break; case "ArrowRight": x+=moveAmount; break; } myBox.style.transform=`translate(${x}px,${y}px)`; // myBox.style.top=`${y}px`; // myBox.style.left=`${x}px`; console.log(x+" "+y); } })
CSS:
body{ position: relative ; margin:0px; } #myBox{ background-color: lightblue ; width:200px; height:200px; font-size:7.5rem; font-weight: bold ; text-align: center ; position: relative ; }
Edit: I have no idea why the formatting of the code is like that.
I'm currently developping a fairly large (containerized) Django app. It's growing in use and I'm starting to need to make the UI more fluid with dynamic elements.
So far, we have overhauled the templates with lot of jQuery. That makes it possible to update the DOM and the database without reloading every page. A lot of our Django views are called via AJAX, accomplish some actions and return JSON responses.
jQuery is beginning to feel wonky and unstable, as we are dealing with asynchronous calls, constant tinkering with the DOM, and such.
I was considering upgrading to a more complex JS Framework.
It seems Vue.js would be a good fit but lots of options would not work with a simple CDN approach? It seemes made for handling *all* of the frontend, but that would need a radical switch of the app toward a separated front and back. Or would it not?
Alpine.js comes across as a lightweight option, that could be a nice next stepping stone. But would it be so much better than jQuery and justify that switch?
Which would you recommend, and why? Or do you have any other suggestions?
Many thanks!
With how fast the JS ecosystem moves I sometimes have a hard time keeping up to date with everything.
Right now I'm subscribed to the newsletter JavaScript Weekly, which does a solid job covering a wide range of updates. I also recently came across the podcast This Week in JavaScript. I like that each episode is only 3-4 minutes long, which makes it more digestible.
Do you guys think that's enough or are there other resources I should follow?
(FYI I'm not affiliated with either of these, just genuinely looking for the best ways to stay in the loop lol).
I don't know why I realized this just now, but package.json is a kind of a free-for-all. NPM as a tool "owns" it, but Node.js piggybacks on it for module resolution as opposed to having a node.config.js file, as well as other tools.
But there isn't a "package.json organization" or a "package.json standard" so how are namespacing conflicts avoided? Consider this ( sorry for code as image reddits code block is being silly ATM)
If theres no "Packge.json metadata foundation" or something how does the JS ecosytem prevent this stuff from happening? In 99% of cases tools have their own config files.
I suppose this is not a pure JS question but hopefully it is not wholly inappropriate.
When it comes to encoding JSON for processing at client (JS), there seems to be many options. Any comments or guide on which is normal, better or more standard?
For example (picked from random internet post)
[{ "id": 28, "Title": "Sweden" }, { "id": 56, "Title": "USA" }, { "id": 89, "Title": "England" }]
versus
{"28": "Sweden", "56": "USA"}
and leave it to the JS side to deal with key/value iteration instead of accessing by property name like id and Title.
I know both works as long as it is handled properly. Assume this is not for a public API but just a REST API only used by internal front end.
Every base32 module I install has no defined ".encode()" function.
I'll const base32 = require("module"),
Only to have an issue when I try the .encode() function.
Posting from phone. I've tried about 5 different libraries. I'm copy-pasting right from the GitHub readmes.
I’m updating my website. I have used Wordpress for years and have been unhappy with my recent pixelgrade theme purchase. The theme developer privatized and has no plans of upgrading the theme to keep up with Wordpress updates, which causes Ajax loading issues. Seeing a lot of inspiring and interactive websites using Green Shock... which makes me want to use scroll triggers and animations across my site. While familiar with expressions in after effects and some basic css, I haven’t coded in a while but feel confident I can pick this up within the right application. Do you recommend ditching Wordpress for Webflow? Or do you think it’s worthwhile using the structure of a theme in Wordpress and adding gsap capabilities?
So far I've only found confusing and hours-long tutorials, that are suuuper slow with their teaching style. I did like some roblox stuff a while ago but I wanna actually learn how to code
So, me and a friend are trying to learn to code in Javascript. and we are looking for a free software that allows multiple people to work on the same code. Any suggestions. Also if you have expeirence using any of the following programs could you tell me about them. CodeSandbox, Repl.it, JSFiddle, or Visual Studio. Note: neither of us have any expeirence coding so if you could try to dumb it down a little it would be appreciated.
I have a test setup on codepen to better help illustrate my issue,
Namely, I am using fabric.js to develop a web based notation app, however when a css transform is applied to the parent element holding the fabric js client, its coordinate system does not update with this rotation.
This causes points to no longer appear under the mouser pointer when the canvas is clicked, for my app it means the pen no longer draws lines underneath the pointer, but rather away from it.
I have tried applying a rotational translation to the original click location, but as per the demo, its falling short of the actual click location.
Any help would be greatly appreciated.
Just found an app (don't know who made it) that gives you a JavaScript console right on your phone: Inspect and Edit HTML. Basically, mobile dev tools! No need to plug into a desktop—just test, debug, and tweak JS on the go.
This means you can do:
⚠️ Caveats:
Anyone else using cool mobile dev tools? Would love to hear!
I am creating a project where I want one div node to act as the area where a user can use a object to display content, say name:, title:, and img:. But after the object is created, the user (or another) can then create another of the same object, and it displays in the same row and be appended to the same div.
I'm curious how that would work and dev create interactive programs like that
Hello!
So i decided to teach web dev to my brothers, ages (26 - 27) and i started with html/css which they can already create/copy website designs with no problem.
Then i started to teach Javascript. I started with the basics, variables, conditions, functions, all good.
But the problem came, the loops. I teached for/while then moved to using those with real world examples/exercices and it fall apart.
Or it was my way of teaching, or they cant imagine in they heads the "loop" flow, i don't know.
In one of the exercises i had a array with names and i used FOR to search if a specific name was present and it was so hard for them to "see it". A simple For with If condition inside.
I think they are missing the logic way of thinking. One problem that i see is that they think that, using the example of the for/if, is the only way of doing this.
What tips can i get to improve or show how loops and other logic methods works from this point forward?
Hi. I’m a cs student and I got a math class coming up next semester called “Curve and surface design” and we have to use html canvas with JavaScript to draw Bézier curves and the like. The thing is I don’t know anything about JavaScript let alone html. I basically know C/C++ and already took a DSA and OOP class. I searched for tutorials on YouTube but the ones I found assume you already know html and JavaScript. Do you know any resources that could help me or do you have any kind of roadmap? Thank you!
Hello! Hopefully this post is appropriate for this community, I just found this subreddit very helpful last time I had questions. I want to apologize if I use the wrong terminology for things, I’m still learning.
I’m starting my first ever project (yay!!) designing a website. I’ve learned HTML/CSS and JavaScript on freeCodeCamp which, if you don’t know, displays multiple code files and gives you a live preview of your work.
Now that I’m starting my own project, I’m a little lost because the display is completely different. I’m using IOS, my MacBook has the latest update, and I’m using BBEdit for my code. There is an option to see a preview of your code which opens a window in a browser of your choice, I chose Safari.
The problem is when I do this, I don’t actually see the preview. It opens showing my lines of code and I have no way of seeing an actual preview of the website I’m trying to design. Does anyone know how to fix this? Or at least a direction I can take to fix this issue? Ideally, I would love to see a live preview of my work, like in freeCodeCamp, but I’ll take whatever I can get 😅
Hi everyone, I created an html file with a javascprit script that allows you to do fade operations between two audio files. The files are played in two players, Player1 and Player2 respectively. On PC/Mac it works but on iPhone I don't get the gradual increase/decrease of volume. The files are played but they stop suddenly.
I didn't succeed with Howler or Tone either. I'm sure I'm doing something wrong. Could you suggest something to refer to?
document.addEventListener("DOMContentLoaded", function () {
const players = [document.getElementById("audioPlayer1"), document.getElementById("audioPlayer2")];
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const gainNodes = [];
let isActionInProgress = false;
// Configura ogni lettore con un GainNode
players.forEach((player, index) => {
try {
const source = audioContext.createMediaElementSource(player);
const gainNode = audioContext.createGain();
source.connect(gainNode).connect(audioContext.destination);
gainNodes.push(gainNode);
// Sincronizza le barre del volume con i GainNode
players.forEach((player, index) => {
const volumeBar = document.getElementById(\
volumeBar${index + 1}`);`
const gainNode = gainNodes[index];
if (gainNode && volumeBar) {
setInterval(() => {
const currentVolume = gainNode.gain.value * 100;
volumeBar.value = Math.round(currentVolume); // Aggiorna il valore della barra
}, 100); // Aggiorna ogni 100ms
}
});
} catch (error) {
console.error("Errore durante la configurazione di AudioContext per:", player, error);
gainNodes.push(null);
}
});
console.log("Array dei lettori audio:", players);
console.log("Array dei GainNode associati:", gainNodes);
// Funzione per il fade
function fade(gainNode, startValue, endValue, duration, onComplete) {
const currentTime = audioContext.currentTime;
gainNode.gain.cancelScheduledValues(currentTime);
gainNode.gain.setValueAtTime(startValue, currentTime);
gainNode.gain.linearRampToValueAtTime(endValue, currentTime + duration);
if (onComplete) {
setTimeout(onComplete, duration * 1000);
}
}
// Funzione per avviare un brano con fade-in e fermare altri con fade-out
function playWithFade(button) {
if (isActionInProgress) {
console.error("Un'azione è già in corso. Attendi il completamento.");
return;
}
const audioSrc = button.dataset.src;
const initialVolume = parseFloat(button.dataset.initialVolume) || 0;
const fadeInTime = parseFloat(button.dataset.fadeinTime) || 0;
const holdTime = parseFloat(button.dataset.holdTime) || 0;
const fadeOutTime = parseFloat(button.dataset.fadeoutTime) || 0;
const fadeOutVolume = button.dataset.fadeoutVolume !== undefined
? parseFloat(button.dataset.fadeoutVolume)
: initialVolume;
const loop = button.dataset.loop === "true";
audioContext.resume().then(() => {
console.log("AudioContext ripreso correttamente.");
}).catch(error => {
console.error("Errore durante la ripresa dell'AudioContext:", error);
});
const availablePlayer = players.find(p => p.paused && p.currentTime === 0);
if (!availablePlayer) {
console.error("Nessun lettore disponibile.");
return;
}
const gainNode = gainNodes[players.indexOf(availablePlayer)];
if (!gainNode) {
console.error("GainNode non disponibile per il lettore.");
return;
}
const currentTrackDisplay =
availablePlayer.id
=== "audioPlayer1"
? document.getElementById("currentTrack1")
: document.getElementById("currentTrack2");
// Aggiorna il nome del brano in esecuzione
currentTrackDisplay.textContent = button.innerText || "Brano sconosciuto";
currentTrackDisplay.style.color = "green";
// Ferma altri lettori con fade-out graduale
players.forEach((player, index) => {
if (!player.paused && player !== availablePlayer) {
const otherGainNode = gainNodes[index];
const otherTrackDisplay =
player.id
=== "audioPlayer1"
? document.getElementById("currentTrack1")
: document.getElementById("currentTrack2");
// Imposta fadeOutTime a 5 secondi
const fadeOutTime = 5;
// Esegui fade-out graduale
fade(otherGainNode, otherGainNode.gain.value, 0, fadeOutTime, () => {
player.pause();
player.currentTime = 0;
// Usa la funzione dedicata per aggiornare il display
updateTrackDisplay(player, otherTrackDisplay);
});
}
});
// Se è specificato solo il volume iniziale
if (fadeInTime === 0 && holdTime === 0 && fadeOutTime === 0) {
console.log("Avvio della traccia con volume fisso:", initialVolume);
// Imposta il volume iniziale direttamente
gainNode.gain.setValueAtTime(initialVolume, audioContext.currentTime);
availablePlayer.src = audioSrc;
availablePlayer.loop = loop;
availablePlayer.currentTime = 0;
availablePlayer.play().then(() => {
console.log("Riproduzione avviata con successo a volume fisso:", initialVolume);
}).catch(error => {
console.error("Errore durante la riproduzione:", error);
});
isActionInProgress = false; // Nessuna azione complessa in corso
return; // Termina qui perché non ci sono fade da gestire
}
// Configura il lettore per il nuovo brano
isActionInProgress = true;
availablePlayer.src = audioSrc;
availablePlayer.currentTime = 0;
availablePlayer.loop = loop;
availablePlayer.play().then(() => {
console.log("Riproduzione avviata con successo.");
}).catch(error => {
console.error("Errore durante la riproduzione:", error);
isActionInProgress = false;
});
// Gestione del fade-in, hold-time e fade-out
fade(gainNode, initialVolume, 1, fadeInTime, () => {
if (holdTime > 0 && fadeOutTime > 0) {
setTimeout(() => {
fade(gainNode, 1, fadeOutVolume, fadeOutTime, () => {
isActionInProgress = false;
// Usa la funzione dedicata per aggiornare il display
updateTrackDisplay(availablePlayer, currentTrackDisplay);
});
}, holdTime * 1000);
} else {
// Caso in cui non ci sono holdTime o fadeOutTime definiti
isActionInProgress = false;
// Usa la funzione dedicata per aggiornare il display
updateTrackDisplay(availablePlayer, currentTrackDisplay);
}
});
// Evento per aggiornare la scritta quando il brano finisce
availablePlayer.onended = () => {
//if (!loop) {
currentTrackDisplay.textContent = \
${currentTrackDisplay.textContent.split(" ")[0]} fermato`;`
currentTrackDisplay.style.color = "red";
}
//};
}
// Funzione Unica per Stop
function stopAudio(button) {
if (isActionInProgress) {
console.error("Un'azione è già in corso. Attendi il completamento.");
return;
}
const fadeOutTime = parseFloat(button.dataset.fadeoutTime) || 0; // Default 0s
const fadeInTime = parseFloat(button.dataset.fadeinTime) || 0; // Default 0s
const holdTime = parseFloat(button.dataset.holdTime) || 0; // Default 0s
players.forEach((player, index) => {
if (!player.paused) {
const gainNode = gainNodes[index];
if (!gainNode) {
console.error("GainNode non disponibile per il lettore.");
return;
}
const currentTrackDisplay =
player.id
=== "audioPlayer1"
? document.getElementById("currentTrack1")
: document.getElementById("currentTrack2");
const currentGain = gainNode.gain.value; // Volume corrente
isActionInProgress = true;
if (fadeInTime > 0 && holdTime > 0) {
// Stop FIHO (Fade-In, Hold, Fade-Out)
fade(gainNode, currentGain, 1, fadeInTime, () => {
setTimeout(() => {
fade(gainNode, 1, 0, fadeOutTime, () => {
player.pause();
player.currentTime = 0;
isActionInProgress = false;
currentTrackDisplay.textContent += " fermato";
currentTrackDisplay.style.color = "red";
console.log("Riproduzione interrotta con successo.");
});
}, holdTime * 1000);
});
} else {
// Solo Fade-Out
fade(gainNode, currentGain, 0, fadeOutTime, () => {
player.pause();
player.currentTime = 0;
isActionInProgress = false;
currentTrackDisplay.textContent += " fermato";
currentTrackDisplay.style.color = "red";
console.log("Riproduzione interrotta con successo.");
});
}
}
});
}
// Assegna eventi ai pulsanti di riproduzione
document.querySelectorAll("button[data-src]").forEach(button => {
button.addEventListener("click", function () {
playWithFade(this);
});
button.addEventListener("touchstart", function () {
playWithFade(this);
});
});
// Assegna eventi ai pulsanti di stop
document.querySelectorAll(".stopAction").forEach(button => {
button.addEventListener("click", function () {
stopAudio(this);
});
});
// Controlla che il Player sia fermo e aggiorna la scritta in rosso
function updateTrackDisplay(player, displayElement) {
if (player.paused && player.currentTime === 0) {
displayElement.textContent = \
${displayElement.textContent} fermato`;`
displayElement.style.color = "red";
console.log("Lettore fermo. Scritta aggiornata in rosso.");
} else {
console.log("Lettore ancora attivo o non fermo. Nessun aggiornamento.");
}
}
});
Hello guys I am graduated in IT but I didn't focus on college much programming language only do basic there and give exam but I start learning web development I am also professional graphic designer but now I wanna learn web developement ... I completed html csss and also javascript but now I am confused should I start node js? Or practice more in javascript after completing the javascript course on Udemy angela course I didn't understand much so I again get a YouTube channel course and I am getting very much there
Now I start node or not please suggest me Thankyou
My engine aims to compile AS3 + MXML + (Adobe Flex's "CSS") projects to HTML5. It should allow building graphical user interfaces and skinning them through that Adobe Flex's "CSS" subset (not the standard CSS that is used in the browser).
I see no possibility of compiling that Flex's CSS into browser CSS for the following reasons:
UIComponent
classes.UIComponent
classes can define custom CSS properties. For example, you may want to pass a logo
as a bitmap, as in logo: Embed("logo.svg")
..style1 {}
.x.y[property="value"] .z.w {}
PropertyReference(...)
could perhaps be used to pass any ActionScript value in CSS, and not only things like bitmaps and strings?My only solution that cames in mind to applying cascading style sheets, then, is really iterating every child in the UIComponent
tree based on every CSS rule, in every frame. Is this performance worrying?
Checking if something is going on or is it just me. I cannot paste code anymore correctly, everytime i do it is way out of format and enter does not work at all.
Hey everyone,
I add these 10 libraries on npmtrends for reference:
If you are using something other than these that you find quite helpful in your day-to-day job please do share, not doing so will result in runtime undefined
and ReferenceError
😊!
Hi guys. I'm a college student. I have some basic knowlegde about coding (HTML, CSS, a bit of JS, data structure, OOP and stuff). I'm planning to build a website for my final project, using HTML, CSS and Node JS (I know very little about JavaScript in general, also no experience in developing back-end part of website)
So my questions are:
what should I learn first before going for NodeJS?
Do you guys suggest any website or youtube video that can guide me from scratch?
Thank you for reading.