r/JavaScriptHelp • • Dec 31 '21

✔️ answered ✔️ Why is my "for" loop not working properly?

2 Upvotes

I am trying to create a button element for each corresponding letter in currentQuestion for the quiz I am making. However, when I run the loop. It creates a button element for ALL answers to every question in the quiz. Does anyone know why? Thank you!

var quizQuestionsContainer = document.getElementById("quiz");
var quizQuestion = document.getElementById("quiz-question");
var buttonsContainer = document.getElementById("buttons-container");
var startButton = document.getElementById("start");

startButton.addEventListener("click", function() {
  buttonsContainer.removeChild(startButton);
  quizQuestions.removeChild
  displayQuestion();
});

var displayQuestion = function() {
  quizQuestions.forEach ((currentQuestion) => {
    currentQuestion.answers
      for (letter in currentQuestion.answers) {
      var optionButton = document.createElement("button")
      optionButton.id = "option-button"
      optionButton.textContent = currentQuestion.answers[letter];
      buttonsContainer.appendChild(optionButton);
    }
    quizQuestion.innerText = currentQuestion.question
  });
};


// quiz questions 
var quizQuestions = [
    {
      question: "Inside the HTML document, where do you place your JavaScript code?",
      answers: {
        a: "Inside the <script> element",
        b: "Inside the <link> element",
        c: "Inside the <head> element",
        d: "In the <footer> element"
      },
      correctAnswer: "a",
      feedback: "Nice job! You place your JavaScript inside the <script> element of the HTML Document is correct."
    },
    {
      question: "What operator is used to assign a value to a declared variable?",
      answers: {
        a: "Double-equal (==)",
        b: "Colon (:)",
        c: "Equal sign (=)",
        d: "Question mark (?)"
      },
      correctAnswer: "c",
      feedback: "Awesome! The correct way to assign a variable is with an equal sign(=)."
    },
    {
      question: "What are the six primitive data types in JavaScript?",
      answers: {
        a: "sentence, float, data, bigInt, symbol, undefined",
        b: "string, number, boolean, bigInt, symbol, undefined",
        c: "sentence, int, truthy, bigInt, symbol, undefined",
        d: "string, num, falsy, bigInt, symbol, undefined"
      },
      correctAnswer: "b",
      feedback: "Stellar! JavaScript has a total of six primitive data types: string, number, boolean, bigInt, symbol, undefined."
    },
    {
        question: "What is the difference between && and ||?",
        answers: {
          a: "The logical operator && returns true if both expressions are true while the logical operator || returns true if one expression or the other returns true.",
          b: "The logical operator && returns true if one expression is true while the logical operator || returns true if both expressions returntrue true.",
          c: "The logical operator && returns true if none of the expressions are true while the logical operator || returns true if one expression or the other returns true.",
          d: "The logical operator && returns true if both expressions are true while the logical operator || returns false if one expression or the other returns true."
        },
        correctAnswer: "a",
        feedback: "High-five! The logical operator && returns true if both expressions are true while the logical operator || returns true if one expression or the other returns true. Check out some of the other operators available to you in the MDN Web Docs."
      },
      {
        question: "How do we declare a conditional statement in JavaScript?",
        answers: {
          a: "difference...between",
          b: "for loop",
          c: "while loop",
          d: "if...else"
        },
        correctAnswer: "d",
        feedback: "Amazing! if... else is most definitely how we declare a conditional statement. This is something you will use every day as a JavaScript developer."
      },
      {
        question: "How do we stop a loop from from repeating indefinitely?",
        answers: {
          a: "A loop will stop executing when the condition is true.",
          b: "We have to explicitly end the loop with the break keyword.",
          c: "A loop will stop executing when the condition is false.",
          d: "When we have iterated through half of the condition."
        },
        correctAnswer: "c",
        feedback: "Fantastic! In JavaScript a loop will stop executing when the condition is false. Have a look at the documentation to solidify your knowledge of loops."
      },
      {
        question: "Which statement below is not true about functions in JavaScript?",
        answers: {
          a: "Functions can be reused throughout your code",
          b: "A function must always be assigned an identifier",
          c: "Functions can receive arguments that can alter the output of a function",
          d: "Functions are able to be recursive."
        },
        correctAnswer: "b",
        feedback: "You're doing great! Functions without identifiers are called anonymous functions which are used quite frequently used in JavaScript. Make sure you are familiar with functions and how they work."
      },
      {
        question: "What are the two types of scope JavaScript uses?",
        answers: {
          a: "Outside and Inside",
          b: "Surrounding and Inner",
          c: "Abroad and Local",
          d: "Global and Local"
        },
        correctAnswer: "d",
        feedback: "Nice job! JavaScript has two forms of scope, global and local. Have a look at the documentation on scope because it is something that will continuously during your JavaScript journey."
      },
      {
        question: "As a developer, I want to be able to remove the last element of my array and I want to also be able to add a new element to the beginning of my array. Which two array methods should I use?",
        answers: {
          a: "concat() and shift()",
          b: "forEach() and pop()",
          c: "pop() and unshift()",
          d: "push() and sort()"
        },
        correctAnswer: "c",
        feedback: "Awesome! The pop array method removes the last element of an array and the unshift method adds an element to beginning of the array."
      },
      {
        question: "How do we access a value stored in an object?",
        answers: {
          a: "Period notation, Square bracket notation",
          b: "Dot notation, Bracket notation",
          c: "Dot notation, Curl bracket notation",
          d: "Equal notation, Abstract notation"
        },
        correctAnswer: "b",
        feedback: "Stellar job! We have two ways of accessing data inside of an object, dot notation and bracket notation. Have a look at the documentation to better understand the behavior of objects."
      }
  ];

<!-- HTML --> 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Fundamentals Quiz</title>
    <link rel="stylesheet" href="./assets/css/style.css">
</head>
<body>
    <h1>JavaScript Fundamentals Quiz</h1>

<!-- display questions -->
<div class="quiz-container">
  <div id="quiz">
    <p id="quiz-question">Quiz Question Text Here</p>
  </div>
</div>

<!-- buttons -->
<div id="buttons-container" class="buttons-container">
    <button id="start">Start Quiz</button>
</div>

<!-- display results -->
<div id="results"></div>

<script src="./assets/js/script.js"></script>
</body>
</html>

r/JavaScriptHelp • • Dec 09 '21

💡 Advice 💡 Assistance

2 Upvotes

Reposting as that I put it in the wrong subreddit.!

I am a complete noob when it comes to JavaScript. Honestly, this is one of the most difficult languages I've been trying to grasp. In the last couple of weeks I've been taking my course. I signed up thinking that it'd be a little similar coming to the web development I took prior. But I was sadly mistaken...

I honestly feel like a dumbass, I've been trying to build an API for my final assignment. And honestly I just don't get the material. It's there but just to remember what to call, and how to execute it. It's just mind-boggling to me. If anyone's available to possibly , Go over some things with me. And give me a few pointers I'd really appreciate it. :(


r/JavaScriptHelp • • Nov 24 '21

❔ Unanswered ❔ Copy to clipboard without HTML?????

2 Upvotes

How do I copy to the clipboard without using html, but with only JavaScript? Is there even a way?


r/JavaScriptHelp • • Nov 20 '21

❔ Unanswered ❔ Error: Infinite loading

2 Upvotes

https://ibb.co/0QPNBV9

I get this error. I am in need of help.

Here are the codes:

var salesChartCanvas = $('#salesChart').get(0).getContext('2d')

var salesChartData = {

labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],

datasets: [

{

label: 'Digital Goods',

backgroundColor: 'rgba(60,141,188,0.9)',

borderColor: 'rgba(60,141,188,0.8)',

pointRadius: false,

pointColor: '#3b8bba',

pointStrokeColor: 'rgba(60,141,188,1)',

pointHighlightFill: '#fff',

pointHighlightStroke: 'rgba(60,141,188,1)',

data: [28, 48, 40, 19, 86, 27, 90]

},

{

label: 'Electronics',

backgroundColor: 'rgba(210, 214, 222, 1)',

borderColor: 'rgba(210, 214, 222, 1)',

pointRadius: false,

pointColor: 'rgba(210, 214, 222, 1)',

pointStrokeColor: '#c1c7d1',

pointHighlightFill: '#fff',

pointHighlightStroke: 'rgba(220,220,220,1)',

data: [65, 59, 80, 81, 56, 55, 40]

}

]

}

var salesChartOptions = {

maintainAspectRatio: false,

responsive: true,

legend: {

display: false

},

scales: {

xAxes: [{

gridLines: {

display: false

}

}],

yAxes: [{

gridLines: {

display: false

}

}]

}

}

// This will get the first returned node in the jQuery collection.

// eslint-disable-next-line no-unused-vars

var salesChart = new Chart(salesChartCanvas, {

type: 'line',

data: salesChartData,

options: salesChartOptions

}

)


r/JavaScriptHelp • • Nov 18 '21

💡 Advice 💡 Snippet Problem Not Loading Correctly In Browser (Jekyll)

2 Upvotes

So I'm really not a JS guy in the slightest, but wanted to basically render a CSV as table on my Jekyll site - I have this working with the following script.

Only problem is it never seems to load the table first time, I need to click refresh in the browser for it to appear - does anyone have any ideas as to what could be the cause of this?

Cheers!

<script>
	window.onload = function() {
		with(new XMLHttpRequest()) {
			onreadystatechange = cb;
			open('GET', 'https://raw.githubusercontent.com/clintjb/A350-Tracking/main/flight_data_a350.csv', true);
			responseType = 'text';
			send();
		}
	}

function cb() {
	if (this.readyState === 4) document.getElementById('A350')
		.innerHTML = tbl(this.responseText);
}

function tbl(csv) {
	return csv.split('\n')
		.map(function(tr, i) {
			return '<tr><td>' +
				tr.replace(/,/g,'</td><td>') +
				'</td></tr>';
		})
		.join('\n');
}
</script>
<table border="0" style='font-size:50%' id="A350"></table>

r/JavaScriptHelp • • Nov 12 '21

❔ Unanswered ❔ different output from when I first run page to when I refresh page (callback /timing related?)

2 Upvotes

I'm learning about callbacks and have noticed a problem. There are no callbacks in this particular code but I think there is something to do with timing.

When I run my code for the first time, the console output after I call getUsers1() should give this:

Array(6) [ "Sam", "Ellie", "Toady", "Jake", ]

But it outputs this:

Array(6) [ "Sam", "Ellie", "Toady", "Jake", "Jake1", "Jake2" ]

If I refresh the browser, it works as intended. What's going on?

Thanks!

PS how do I change flair (browser version)? I see nothing in the edit post options.

Here is my code:

<meta charset='utf-8'>

<script>

var users = ["Sam", "Ellie","Toady"]

function addUser(username){

`users.push(username);`

};

function getUsers1(){

`console.log(users);`

}

addUser('Jake');

getUsers1(); //FIRST LINE OF CONSOLE OUTPUT

s=addUser('Jake1');

console.log(s)

function getUsers2(){

`console.log(users);return users;`

}

t=addUser('Jake2');

t=getUsers2();

console.log(t)

</script>


r/JavaScriptHelp • • Nov 11 '21

❔ Unanswered ❔ Silly error that I can't work out : variable is undefined

2 Upvotes

Hi,

I'm making a game where you have to click on svg boxes of a certain colour. Anyway, after some changes I have an error that I can't work out:

Uncaught TypeError: current_elem is undefined

current_elem is defined on this line

var current_elem=document.getElementById("rect-red");

, why is my code not seeing it?

I haven't tidied up my code for my question, I think it will be a dumb mistake and it will be clear anyway.

Thanks a lot.

Full html /css/js

https://pastebin.com/LHE5HySF

!DOCTYPE html>

<html>

<head>

`<title>Javascript + DOM</title>`

<meta charset="utf-8">

`<style>`

body{color: pink;background-color: black;font-size:1.2em;}

div{border: 2px solid pink;}

#container {

display: grid;

grid-gap: 20px;

grid-template-rows: 1fr;

grid-template-columns: 1fr 1fr;

justify-items: end;

align-items: end;

}

#rect-red{

fill: red;

stroke-width: 3;

stroke: black;

}

#rect-green{

fill: green;

stroke-width: 3;

stroke: black;

}

#rect-blue{

fill: blue;

stroke-width: 3;

stroke: black;

}

#rect-orange{

fill: orange;

stroke-width: 3;

stroke: black;

}

svg {

background-color: dimgrey;

/*border: 2px solid pink;*/

/*display: inline-block;*/

padding : 5px ;

/*top-bottom left-right*/

margin : 10px ;

}

</style>

</head>

<body>

<div id="container">

<div id="boxes">

<svg id='boxes' x='500' height="300" width="300" viewPort="0 0 300 300" >

<g transform="scale(2.0)">

<rect class='rect' id='rect-red' x="10" y="10" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-green' x="80" y="10" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-blue' x="10" y="80" width="60" height="60" rx="15" ry="15" />

<rect class='rect' id='rect-orange' x="80" y="80" width="60" height="60" rx="15" ry="15" />

</g>

</svg>

</div>

<div id="instruction-box">

<br>

<button onclick="question()"> START </button>

</div>

<div id="message-box">

<br>

Messages

</div>

</div>

</body>

<script type="text/javascript">

var svg_rectangles= document.getElementsByClassName('rect');

//svg_rectangles is not an array. It is HTMLCollection and it does not have //forEach method. You must convert it to an array first:

var svg_elements = Array.prototype.slice.call(svg_rectangles);

svg_elements.forEach(makeClickEvent);

//var stateArray=0;

var stateArray=initialiseStateArray(svg_elements);

function initialiseStateArray(svg_elements) {

//LIST (old way)

// var StateArray = [];

//DICT

var stateArray = {};

svg_elements.forEach(addToStateArray);

function addToStateArray(current_elem) {

//LIST (old way)

//stateArray.push([current_elem,false])

//false is unclicked

//DICT

stateArray[current_elem.id]=false;

}

console.log('STATE ARRAY INITIALISED')

console.log(stateArray)

return stateArray

}

var current_elem=document.getElementById("rect-red");

function setState(current_elem,state) {

stateArray[current_elem.id]=state;

console.log('STATE ARRAY VALUE SET');

string=' '+current_elem.id + ' > ' +state

console.log(string);

console.log(stateArray);

return stateArray;

}

setState(current_elem,true);

function resetStateArray(stateArray) {

for(var key in stateArray) {

stateArray[key]=false;

}

console.log('STATE ARRAY RESET');

console.log(stateArray);

return stateArray;

}

stateArray=resetstateArray(stateArray);

function makeClickEvent(current_elem) {

current_elem.addEventListener("click", outputMessage);

stateArray=updateClickedStatus(stateArray,current_elem);

function outputMessage(current_elem) {

var output = document.getElementById("message-box");

rect_name=event.target.id

message= rect_name + " clicked!"

output.textContent = message;

//update the state, set all to false then set the one that has been clicked to true

}

function updateClickedStatus(current_elem) {

setState(current_elem,true)

}

}

function question() {

//get a box

current_elem=svg_elements[0] ;

//print the instruction

var instruction = document.getElementById("instruction-box");

var box = document.getElementById("rect-orange");

rect_name=event.target.id

message= "Click on "+box.id

instruction.textContent = message;

//reset svg_state_array

}

</script>

</html>


r/JavaScriptHelp • • Nov 04 '21

❔ Unanswered ❔ (New to JS) Help With Delaying a Script

2 Upvotes

Hi,

I've been tasked with adding the below script to a clients website to load an online booking widget, however it's absolutely tanking the page load speed.

I was hoping there is a way to stop the script loading until a button is clicked, or at least delay the loading of the script to allow the page to load.

<script type='text/javascript'>!function(b,c){b.saloniqid='119423d7-1209-4ee5-8e1b-f8a71f0b7345',b.saloniqsite='https://bookings.saloniq.co.uk';var d,g,e='onlinebookingwidget-loader',f=c.getElementsByTagName('script')[0];c.getElementById(e)||(d=c.createElement('script'),d.id=e,d.async=!0,d.src=b.saloniqsite+'/scripts/onlinebookingwidget-loader.js?d='+Date.now(),g=f?f.parentNode:c.getElementsByTagName('head')[0],g.insertBefore(d,f))}(window,document);</script>

Thanks!


r/JavaScriptHelp • • Oct 23 '21

💡 Advice 💡 how to handle Insert multi rows query when is duplicate or violates foreign key

2 Upvotes

I'm using nodejs, express, postgres as sql server. I created Javascript API that sends queries to the server, And i want when i send a multi-line insert query to the server if one or more of the lines already in the system the query will continue without those in the server And if foreign key error happen(is not present in table "tablename") it will ask the client(wait for response) if to add it to the foreign table and then continue with the query.

So far i did this code, but can not figure out where to start with this problem:

    insert(){
    	return new Promise( async (resolve, reject) => {
    		const client = await this.PoolCONN.connect();
    
    		client.query(query, (err, results)=>{
    			
    			if(err){
    				const error = this.HandlError(err)
    				client.release();
    				return reject(error);
    			};
    			
    			client.release();
    			return resolve(results);
    
    		});
        })
    }

    HandlError(error){
	const ErrorCode = error.code;
	let errorName = "";
	let msg = "";
	switch (ErrorCode) {
		case '23505': // duplicate values
			
			msg = ``;
			errorName = "duplicate";
			break;                
		case '23503': // foreign_key_violation
			msg = ``
			errorName = "foreign key"
			break;                
		default:
			break;
	}

	return {
		error: errorName,
		errorMSG: msg,
	}
    }

NOTE: I know I'm asking for a lot I'm a bit lost


r/JavaScriptHelp • • Sep 21 '21

❔ Unanswered ❔ Why is the data not saving into a live database despite it working in a local server?

2 Upvotes

I am deploying a Website to a live domain via 000webhost.com. My problem is that when I run the application from localhost, It saves the data into the database successfully. But when inserting the data from the live website, it does not insert the data into the SQL server. Also, I did not receive any errors so I'm a bit confused. Here is a link to my Github repo: https://github.com/Rustyrice/rustyrice.github.io.git


r/JavaScriptHelp • • Sep 17 '21

❔ Unanswered ❔ Problem with sessionStorage

2 Upvotes

I currently have a mostly working script that compares two checkbox ID's when the compare button is pressed.

However, after using a sessionStorage script I found online, I found that now my checkbox values don't update unless I refresh the page (since sessionStorage makes it so the browser only sees the last selected value, and not the new one).

Is there any way to KEEP sessionStorage--as in, have the browser remember the last selected checkbox value--but also update the value in the checkboxes WITHOUT refreshing the page?

Much appreciated!

<input data-selector="edit-submit" type="submit" id="edit-submit" value="Search" class="button js-form-submit form-submit btn btn-primary form-control">
<input data-selector="edit-reset" type="submit" id="edit-reset" name="op" value="Reset" class="button js-form-submit form-submit btn btn-primary form-control">
<button type="button" class="btn btn-sm btn-primary" id="compare">Compare</button>
<input type="checkbox" id="td0" class="form-check-input" value="">
<input type="checkbox" id="td1" class="form-check-input" value="">
<input type="checkbox" id="td2" class="form-check-input" value="">
<input type="checkbox" id="td3" class="form-check-input" value="">
<input type="checkbox" id="td4" class="form-check-input" value="">
<input type="checkbox" id="td5" class="form-check-input" value="">
<input type="checkbox" id="td6" class="form-check-input" value="">
<input type="checkbox" id="td7" class="form-check-input" value="">

function onReady() {
    $(function(){
  $("input:checkbox").change(function(){
    var len = $("input:checkbox:checked").length;
    if(len == 0)
      $("#compare[type='button']").prop("disabled", true);
    else
      $("#compare[type='button']").removeAttr("disabled");
  });
});
   $(function(){
    $('input:checkbox').each(function() {
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
     });

    $('input:checkbox').on('change', function() {
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
   });
});

var all_checkboxes_search = jQuery(':checkbox');
jQuery('#edit-submit').on('click', function(event){
    all_checkboxes_search.prop('checked', false).change();
  });

var all_checkboxes_reset = jQuery(':checkbox');
jQuery('#edit-reset').on('click', function(event){
    all_checkboxes_reset.prop('checked', false).change();
  });

$(function() {
  $("input:checkbox").change(function(index){ 
    var limit = 4;
    if($("input:checkbox:checked").length >= limit) {
      this.checked = false;
  }
});

  var txt = $('input:checked')
  .map(function() { 
  return this.id;
  })
  .get().join(',');
 
$("#compare[type='button']").click(function() { 
    alert(txt);
   });
 });
}
$(document).ready(onReady);

r/JavaScriptHelp • • Aug 25 '21

✔️ answered ✔️ How do I split a word to retrieve part of it? Problems with substring?

2 Upvotes

So I come from a pl/sql background, so I think I am making a basic error here..

But I have looped through a series of elements which I know will each contain a class named "ibType-" followed by a type "string"/"id"/"long" etc.

for example,

This is my code

for(var i=0; i < form.elements.length; i++){
                            var e = form.elements[i];
                            var pos = e.className.lastIndexOf("ibType-");
                            console.log ("Starts at "+pos);
                            var classType = e.className.substring(pos);
                            console.log ("ClassType = "+classType);

The problem is that my first console.log is showing the position that the string "starts at", rather than ends at.

start-quote.js:91 Starts at 13
start-quote.js:93 ClassType = ibType-ID
start-quote.js:91 Starts at 0
start-quote.js:93 ClassType = ibType-STRING
start-quote.js:91 Starts at 13
start-quote.js:93 ClassType = ibType-ID
start-quote.js:91 Starts at 13

And the substring doesn't seem to do anything. In this example, I would like the value of classType to be "ID" "STRING" and "ID".

Can anyone point out my problem here?

Thanks in advance


r/JavaScriptHelp • • Aug 18 '21

💡 Advice 💡 How to create a grid from random generated numbers between min and max values?

2 Upvotes

I'm trying to draw a grid representing random generated integers between (-100-100) (Each cell / square corresponds to an integer). 100 corresponding to the hexadecimal value #FF0000 (red) and -100 corresponding to the hexadecimal value #00FF00 (green), then assigning a color to each cell between the two initial colors according to the value of the integer it represents. An example like "Github contribution grid"


r/JavaScriptHelp • • Jul 17 '21

💡 Advice 💡 JS & Typescript stuggle

2 Upvotes

Names Edgar, 44. Been manual QA for 12 years. Laid off during COVID after 7 years. Company made more money than ever during COVID. I'm now taking Test Automation Software bootcamp at DevMountain.

For the freaking life of me I am having an unbelievably and extremely difficult time retaining any code I'm being taught. I'm a bit dyslexic and also very hands on guy.

I'm struggling so much I had a breakdown tonight due to the fact I just have such a hard time retaining it then applying it appropriately.

I can use Sololearn pretty well to "answer" questions and do really well at questions and answers. But when I have to write/type things out appropriately I immediately draw a blank and it's as off my brain fills up with sand.

My environment is quiet, I listen to calm study music, jot down key things but then when I have to create code correctly in the right or at the appropriate place my brains hits a major roadblock.

It's so stressful now, I'm behind a unit and half. I'm extremely embarrassed with myself.

Any videos, books, sites that can help me retain it in a way "Explain it like I'm 5" method.

I'm using VSCODE with node.js and it's also typescript.

Maybe a volunteer tutor group that would help me over zoom when I'm not in class. My school schedule is 6-9pm MST M-W and Sat 9AM-12PM.

I'm about to give up wasting $5000 loan because I feel it's not sinking in yet. Feels like I'm destined to be stuck jobless as a manual QA and companies want mostly Automation now.

New to the community. Thank you all for your time.

It's 4:08am and have class at 9AM. Freaking brain won't turn off because of constant worry of failure. Need a couple hours sleep before class.

Cheer!


r/JavaScriptHelp • • Jul 13 '21

❔ Unanswered ❔ Get URL domain from RSS feed

2 Upvotes

Hello, I’m new to JavaScript.

Is it possible to get the URL domain from the link tag in a RSS feed (for instance the first item) and return this domain? Thx


r/JavaScriptHelp • • Jul 10 '21

💡 Advice 💡 How to be proficient in using Javascript for Web development?

2 Upvotes

Hi Guys!

I recently covered almost all parts of HTML and CSS. I've made loads of projects and confident enough to create a fully responsive web page like landing page, portfolio website, etc.

Now I'm stepping into the world of JS. I'm able to understand and use DOM, Event Handling, and arrays by building small projects. But now I'm unable to understand **objects, prototypes, OOPs concepts like classes, async and await, promises, etc** which is crucial for learning JS libraries like React(my next learning path), Angular, and Vue.

I don't know how and where we'll use these object property and OOPs concepts which stops me from building new projects.

So can you please provide me resources or guidance to understand and build projects using the above-mentioned JavaScript concepts so that I can be fluent enough to learn React and node.js?

Any form of advice, guidance, tutorial, or book recommendation with a proper plan or learning path to excel in those concepts will be much helpful to ace my frontend development skills.

Thanks in advance!


r/JavaScriptHelp • • Jul 09 '21

✔️ answered ✔️ Converting dates formats without timezone conversion?

2 Upvotes

I'm trying to do this without adding moment js to my project but i's seems more difficult than I'd like.

if I get a date that's formatted as : "2021-07-19T12:15:00-07:00"

Is there an efficient way to have it formatted as: "12:15 pm"

regardless of where me and my browser are located?

Thanks!


r/JavaScriptHelp • • Jul 01 '21

❔ Unanswered ❔ Beginner here - can someone translate into approximate logic what this bit of js is doing?

2 Upvotes

I just really can't understand it..

var t = e.filter(function(e) {

return null != e

});

return 20 < t.length ? t.slice(0, 20) : t


r/JavaScriptHelp • • Jun 30 '21

💡 Advice 💡 Any way to compress a cached file?

2 Upvotes

I have a successfully working page where a visitor can record a video via html5 < video > via web cam. Once it's recorded it automatically Plays the just recorded video (and then can be uploaded).Because it takes too long to upload, is there any way to compress or zip the browser cached (recorded) file, prior to upload, to help improve the upload speed?


r/JavaScriptHelp • • Jun 28 '21

❔ Unanswered ❔ Sql comment with a ' in the middle of it is stopping me from creating a string out of it

2 Upvotes

So I'm trying to get a comment from sql and put it into a js array, but it's giving me errors because it's built like this: "This is ' a comment", and so the second part becomes a non-string. And when trying to toString() the whole comment, the toString() method just becomes part of the string.


r/JavaScriptHelp • • Jun 16 '21

💡 Advice 💡 Noob question

2 Upvotes

I just started programming today. I want to add a comment. The video I watch tells me the way to add a comment I need to add two // (then it turn gray) but this doesn’t work. Any help?


r/JavaScriptHelp • • Jun 15 '21

✔️ answered ✔️ Hire a JS coder? Paid. Need calculated fields (sum, total, average) in pdf file.

2 Upvotes

Hello. I am in need of someone more well-versed in js than I am (which is not much at all). I can pay a little for any help that works.

The short version: I have a 20-question observation survey in a pdf Form. Of those 20 questions, each has a 1-2-3-4-5 scoring and not all of the questions will be answered each time. I'd like a (1) summary field that shows the sum of questions answered, a (2) max totals field for all answered (meaning if only 4 questions were answered, the max would 4 * 5(max score per question)), and a (3) percentage field (summary / max * 100 (to show percentage)).

I can see the logic of how to accomplish this but not the skills to do it. Anyone help?


r/JavaScriptHelp • • May 11 '21

💡 Advice 💡 Javascript mentorship

2 Upvotes

Hello all, I've just joined this group :)

I would like to get in touch with a Javascript mentor who has time to give feedback and share with me some JS best practices by real-life example. Most of my questions are Front-End related.

Currently am working on some own projects and running into some blockers due to experience.. I am interested learning by using JS in eg. Node, REACT, Typescript, EJS, Mongoose environments

I wonder if somebody out there would provide me with feedback and help me get the grips with some more specific concepts, that would be awsome.


r/JavaScriptHelp • • Apr 10 '21

✔️ answered ✔️ Get Content of URL Help

2 Upvotes

I’m wondering how to get the content of an external URL. I haven’t been able to find an answer to this anywhere on the internet.

This is the URL: https://random-word-api.herokuapp.com/word?number=1

Thanks for the help in advance.


r/JavaScriptHelp • • Mar 29 '21

💡 Advice 💡 Disappearing btn

2 Upvotes

I have created this countdown timer for a HTML site that I'm planning on launching. This page links to a sign up page via a button with an ID of 'btn'. I want this to disappear when the timer runs out like it currently shown the end message. But after googeling it, I can't seem to find an answer that seems to work!

I thought if anyone knew how to get this working then it would be the people of reddit!

TIA

var countDownDate = new Date("MAR 29, 2021 17:18:00").getTime();
var myfunc = setInterval(function() {
var now = new Date().getTime();
var timeleft = countDownDate - now;
var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

document.getElementById("days").innerHTML = days + "d "
document.getElementById("hours").innerHTML = hours + "h "
document.getElementById("mins").innerHTML = minutes + "m "
document.getElementById("secs").innerHTML = seconds + "s "

if (timeleft < 0) {
clearInterval(myfunc);
document.getElementById("days").innerHTML = ""
document.getElementById("hours").innerHTML = ""
document.getElementById("mins").innerHTML = ""
document.getElementById("secs").innerHTML = ""
document.getElementById("end").innerHTML = "You've missed registration this year! But don't worry, there is always next year!";
}
}, 1000);