r/JavaScriptHelp • • Oct 18 '20

❔ Unanswered ❔ SyntaxError: Missing catch or finally after try...while compiling ejs

4 Upvotes

Could you please take a look at this stackoverflow question about

SyntaxError: Missing catch or finally after try ... when compiling ejs
I don't have any try statements in my files. My syntax is correct but I don't know the cause of the error. I have also checked the ejs docs. Maybe my computer is not compiling ejs correctly? Do you have any hints?


r/JavaScriptHelp • • Oct 06 '20

⚠️ Moderator ⚠️ New mod!

4 Upvotes

G'day everyone, I submitted a reddit request a while back for this sub as your previous mod seemed to abandon the sub. I'm going to start tidying things up shortly and then I'll unrestrict he sub. All the previous spam posts will be removed, it seems a bit petty to ban them though so the users who posted them can continue posting.

In the meantime, do any of you guys have any suggestions? All suggestions will be welcomed!

Thanks, Fastercoder4000

Update 1: all messages in response to modmails have been sent.


r/JavaScriptHelp • • Jan 17 '22

❔ Unanswered ❔ What's the difference between return and console.log ?

3 Upvotes

there's more to the problem than this, but for now, why does my for loop stop after 1 iteration when using return? I need the result to be what console.log displays looping through each element.

 const speciesArray = [ 

  {speciesName:'shark', numTeeth:50},    {speciesName:'dog', numTeeth:42},    {speciesName:'alligator', numTeeth:80},   {speciesName:'human', numTeeth:32}];

const sortSpeciesByTeeth = array => {

for (let i = 0; i < array.length; i++){

return array[i].numTeeth    }   } // returns 50

const sortSpeciesByTeeth = array => {

for (let i = 0; i < array.length; i++){

console.log(array[i].numTeeth)    }   } // returns 50, 42, 80, 32


r/JavaScriptHelp • • Dec 20 '21

✔️ answered ✔️ What shows in the console? I got 6. The question says it's 4. HELP ME!!! (Kevin Hart voice)

3 Upvotes

var sum = 0;

for (var = i; i<=3; i++) {

if (i==2) {

continue;

}

sum += i;

}

console.log(sum);


r/JavaScriptHelp • • Jul 13 '21

❔ Unanswered ❔ Press enter at end of function

3 Upvotes

Hey guys,

A quick question that I hope someone can help out with.

I've got a simple function that enters a string into an input:

$(document).ready(function(){
$("#asset_return a").click(function(){
var value = $(this).html();
var input = $('#search_text');
input.val(value);
var focus = $('#search_text').focus();
var submit = $('#search_text').submit();
});
});
</script>

What I need it to do is press enter at the end of the function - I tried submit but to no avail. Any ideas?


r/JavaScriptHelp • • Jun 06 '21

✔️ answered ✔️ Function vs block - var vs let

3 Upvotes

I have been working lightly with JavaScript for about 4 months now - so Im fairly new to this. I am brushing up on let vs var and what I find is that let is block scoped and var is function scoped. But the thing is, a function is (also) a block of code.

How do I make it more clear what the difference is? And what is the difference between a block of code vs a function?


r/JavaScriptHelp • • Mar 31 '21

✔️ answered ✔️ Beginning JS, first code need help

3 Upvotes

Anyone see what I did wrong here? I keep getting “undefined” as output. It’s supposed to look at the array and return the highest value. Probably something little I forgot but I’m out of ideas.

function secondHighest(array){ var max = array[0]; for (var i = 0; i < array.length; i++) { if (array[i] > max) { max = array[i]; }

} return max }

console.log(secondHighest(5,7,4));


r/JavaScriptHelp • • Oct 28 '20

❔ Unanswered ❔ Script to scroll down to bottom of Facebook page?

3 Upvotes

Hi friends, I need to scroll down to the bottom of the page without doing it manually which takes forever. (profile, not the feed)

I used this script - https://gist.github.com/eykanal/a0b30e035d8c15995deeffec6ab21866

The only problem is that when I do that and I want to scroll back up to review the posts it keeps bouncing back down. Does that mean the code is still running? how do I stop it once it get done?

any and all other solutions or other/better scripts will be **highly** appreciated

I am a beginner (literally looked into this just yesterday) so hope this was informative enough


r/JavaScriptHelp • • Oct 15 '20

✔️ answered ✔️ Comp Sci - Assignment

3 Upvotes

Hi, so I have a comp sci assignment which requires me to do so:

Create a small program that demonstrates your understanding of the materials researched. Your program must have, at least, the following:

  • Objects

  • At least one of:

    • Abstract classes

    • Interfaces

    • Inheritance

  • Files, by including:

    • Reading and writing of a text file, or

    • Reading and writing of a binary file, or

    • Reading from an API and writing to a text file, or

    • Reading/writing JSON information, or

    • Reading from and writing to a database (e.g. SQL, MongoDB, etc.)

  • Conversion of datatypes (int to string
    , string to int
    , float to int
    , etc.)

    • This is most easily completed when you are reading/writing files

I decided to make my program themed about space - so a class about planets all that. I've started working on the program but I'm confused about the "conversion of datatypes." How does that work? I'm completely new to Javascript and therefore I would appreciate any help!


r/JavaScriptHelp • • Oct 15 '20

⚠️ Moderator ⚠️ Total reopening of sub!

3 Upvotes

For real now! Do any of you guys have any suggestions? You'll notice that we have some shiny new flairs and new rules! Please check them all out. Enjoy the sub :)


r/JavaScriptHelp • • 3d ago

r/JavaScriptHelp is available for adoption

2 Upvotes

/r/JavaScriptHelp is ready for a fresh start, new energy, new direction, and someone like you to bring it back to life. If you’ve been thinking about growing your impact without starting from scratch, this is your chance!

Ready to take it over?

Head to r/RedditRequest to submit your request and make it yours before it’s taken.

First things first

To request this subreddit, make sure you:


r/JavaScriptHelp • • Mar 23 '22

❔ Unanswered ❔ noVNC and require.js

2 Upvotes

I have an existing project using require.js which uses an older version of noVNC. I need to upgrade the noVNC so I can use user/password authentication, but I'm having no luck getting the noVNC to compile to an AMD version.

I've run across various instructions, but they usually follow this pattern:

git clone https://github.com/novnc/noVNC/
cd noVNC
npm update
node ./utils/use_require.js --as amd --clean

With the 1.3 version of noVNC, the use_require.js script does not take an "--as" parameter, and the compiled version it spits out doesn't appear to be a require.js version - it doesn't start with a define. Trying to use it results in this error:

Uncaught ReferenceError: exports is not defined
    <anonymous> http://127.0.0.1:8080/testapp/lib/novnc/rfb.js?v=1648066918354:5

I tried adding "var exports={}" to the top of the page, but that screws up all kinds of things - presumably some other components are trying to detect commonjs vs AMD and get confused.

In the master version from github the use_require.js file is renamed to convert.js but has the same problem. Trying to compile the 1.2 version yields this cryptic error:

/home/dwargo/noVNC-1.2.0/utils/use_require.js:130
        throw new Error("you must specify an import format to generate compiled noVNC libraries");
        ^

Error: you must specify an import format to generate compiled noVNC libraries
    at makeLibFiles (/home/dwargo/noVNC-1.2.0/utils/use_require.js:130:15) 
    at Object.<anonymous> (/home/dwargo/noVNC-1.2.0/utils/use_require.js:322:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

Looking at the source of use_require.js it seems like --as specifies the input format, so I have no clue what to do about that.

I'm on my second day of throwing this thing at a wall with no luck - I'm hoping someone has walked this road before. I guess I can hand-paste the define blocks from the old version, but that seems painful.


r/JavaScriptHelp • • Mar 14 '22

❔ Unanswered ❔ Get count and format

2 Upvotes

I have an object dateRange ={ 2021-08-06 - 2021-09-06 : 0, 2021-09-06 -2021-10-06 : 0}

I also have another array dateArr=[2021-08-06, 2021-11-06]. Desired res = [{key: 2021-08-06 - 2021-09-06 , value: 1}, { key: 2021-09-06 -2021-10-06 , value: 0}] where value contains the number of occurrences of values inside dateArr as per dateRange.

How can I achieve this?


r/JavaScriptHelp • • Mar 12 '22

❔ Unanswered ❔ Help with momentjs

2 Upvotes

I've an array abc containing date and time. How can I convert it into time slots of 1 day with limits determined by startDate and endDate with 'x' containing time slots and 'y' containing count of occurrence in those time slots. I have also attached the fiddle below for reference.

http://jsfiddle.net/killMeSak/Lwj2mb7t/9/


r/JavaScriptHelp • • Mar 08 '22

💡 Advice 💡 Any advice?

2 Upvotes

I'm trying to get the user to be able to put there name in the string and replace Demar with it any help would help.

.<!DOCTYPE html>

<html lang="en">

<head>

	<meta charset="utf-8" />

	<title></title>

</head>

<body>	

	<script>

		Var myString = "Kevin, Kobe, Kyrie, Lamelo, Demar";

		mar myRegEXP = /Demar/;

		

		myString = myString.replace (myRegExp, "GiGi");

		alert(myString);

	</script>

	</body>

r/JavaScriptHelp • • Mar 06 '22

💡 Advice 💡 need help with google javascript map

2 Upvotes

hi!
I'm building a project which shows the live location of active users on an app but I'm not able to update the position of the marker on the map due to which when the website receives a new location it just add a new marker instead of updating the last marker.

can anyone help me with this?

#javascript #

<script>
        let map;
        let params3;

        params3 = JSON.parse(localStorage.getItem('test6'));
        





        function initMap() {
            //Map options
            var options = {
                zoom: 12,
                center: { lat: 30.695, lng: 80.124 }
            }
            // new map
            map = new google.maps.Map(document.getElementById('map'), options);
            // customer marker
            var iconBase = './icon6.png';

            //array of Marrkeers
            // var markers = [
            //     {
            //         coords: { lat: 28.6934080, lng: 77.1242910 }, img: iconBase, con: '<h3> This Is your Content <h3>'
            //     },
            // ];



            //loopthrough markers
            
            if (params3) {
                console.log(params3);

                for (var i = 0; i < params3.length; i++) {
                    //add markeers
                    addMarker(params3[i]);
                    // console.log(params3[i]);
                }

            }


            //function for the plotting markers on the map
            function addMarker(props) {

                if (props.status == 'ONLINE') {
                    var marker = new google.maps.Marker({
                        position: props.coords,
                        map: map,
                        // icon: props.img
                    });
                    var infoWindow = new google.maps.InfoWindow({
                        content: props.con,
                    });
                    marker.addListener("click", () => {
                        infoWindow.open(map, marker);
                    });

                }

            }
}
</script>

r/JavaScriptHelp • • Feb 14 '22

❔ Unanswered ❔ Need help while saving file

2 Upvotes

I'm trying to implement a functionality where I need to save a file from cloud storage to my local machine. The API expects a local file destination (to save file) as one of the parameters. I want to set this destination based on user prompt.
Is there a way I can do this using React / Javascript where a user can select this location?


r/JavaScriptHelp • • Feb 12 '22

✔️ answered ✔️ Noob needs help with a button

2 Upvotes

I'm working with html, css and javascript and I can't figure out how to make a button do what I want it to.

<button id=btn class="button" onclick="rmv()"> Click here!</button>

<script>

function rmv() {

var element = document.getElementById("heading");

element.remove ();

var element = document.getElementById("paragraph");

element.remove();

var element = document.getElementById("btn");

element.remove(); }

</script>

I've managed to make the button 'disappear' itself and the text that was on the page before it was clicked, but I also want to it to make the page change colors and new text to appear, but I don't know how. I succeeded in making the colors change and the text appear but on a different page:

<style>

@keyframes background-color {

0% {background-color: #f3bcc0}

20% {background-color: #acf3cc}

40% {background-color: #f5eb18}

60% {background-color: #cbe832}

80% {background-color: #ff9317}

100% {background-color: #c7658f}

}

body{

animation: background-color 5s infinite;

animation-direction: alternate;

}

h1 {text-align: center;}

</style>

<h1> Text </h1>

Could someone write the code for the button to do this? I would really appreciate the help, I know it's probably a silly question but i just started learning a few days ago :)


r/JavaScriptHelp • • Feb 07 '22

❔ Unanswered ❔ SyntaxError! please help....

2 Upvotes

I am doing a Rock, Paper, or Scissors project

code:

const getUserChoice=userInput =>
{
if(userInput==='rock'){
return userInput;
}else if(userInput==='paper'){
return userInput;
}else if(userInput==='scissors'){
return userInput;
}else{
return 'error';
}
}
function getComputerChoice(){
const randomnumber=Math.floor(Math.random()*3);
switch(randomnumber){
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
function determineWinner(userChoice,computerChoice){
if(userChoice===computerChoice){
return 'the game was a tie';
} if(userChoice==='rock'){
if(computerChoice==='paper'){
return 'computer won!';
}else{
return'you won!'
}
}else if(userChoice==='paper'){
if(computerChoice==="scissors"){
return 'computer won!';
}else{
return "you won!";
}
}else if(userChoice==='scissors'){
if(computerChoice==='paper'){
return 'computer won!';
}else{
return 'you won!';
}
}
}
function playGame(userChoice,computerChoice){
let userChoice = getUserChoice('scissors');
const computerChoice = getComputerChoice();
console.log('You threw: ' + userChoice);
console.log('The computer threw: ' + computerChoice);
console.log(determineWinner(userChoice,computerChoice));
}
playGame();

//when I use this code, it keeps showing /home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:54 let userChoice = getUserChoice('scissors'); ^ SyntaxError: Identifier 'userChoice' has already been declared

//but if I replace the last function code with the following:

const playGame = () => { let userChoice = getUserChoice('scissors');

const computerChoice = getComputerChoice(); console.log('You threw: ' + userChoice); console.log('The computer threw: ' + computerChoice); console.log(determineWinner(userChoice,computerChoice)); } playGame();

it works, please help, I don't know the reason.


r/JavaScriptHelp • • Jan 24 '22

❔ Unanswered ❔ Auto-Resize an Emoji According To The Website In Use

2 Upvotes

This Emoji translates quite well to various forums across the web (Originally a Discord 22x22 Emoji).

I would like to "teach" my computer to change the image =size? when I "paste" it into site X ,so that the Emoji maintains a size akin to that of the text.

I have no idea how to do this (no programming experience) .When I copy-paste a sentence-Emoji combo from Discord into various forums , the Emoji transforms into an unproportional size compared relatively to the text (in Discord it seems to be rendering at 22x22, but when pasted to forum X it seems to become a 40x40 rendering.

I've had this suggestion: 

const regex = /\[IMG\]https:\/\/cdn\.discordapp\.com\/emojis.*\[\/IMG]/gm; const str = \[IMG=https://cdn.discordapp.com/emojis/935270790675431484.webp?size=44&quality=lossless]; if (regex.test(str)) { //regex to replace the size}`

But, again, no knowledge in programming. Is the aforementioned code Javascript?

Here's the Platinum Trophy image as it appears on the browser version of Discord in the Elements tab (left-click > Inspect) , in DevTools (Chrome):

<IMG aria-label=":PlatinumTrophy:" src="https://cdn.discordapp.com/emojis/935270790675431484.webp?size=44&amp;quality=lossless" alt=":PlatinumTrophy:" draggable="false" class="emoji" data-type="emoji" data-id="935270790675431484">

I see there's a "size=44" section ? Would I be correct in saying that in order to achieve my desired size all I have to do is to somehow teach my computer a function where the "44" goes in and ,say, "20" comes out? If so , how do I go about achieving this? 

I've tried post to r/learnjavascript but I got the " Please fix the above requirements " error when posting, so I thought I'd post here.


r/JavaScriptHelp • • Jan 20 '22

❔ Unanswered ❔ Are there any good libraries for skeleton loading screens for vanilla js?

2 Upvotes

I want to create a skeleton for a horizontal bar chart, but I'm having trouble finding a good library for it. Most of them are either for React or Vue and my page is in vanilla js.

The closest thing I could find was css-skeletons, which lacks support for horizontal bar charts (only vertical bar charts are considered).


r/JavaScriptHelp • • Jan 11 '22

❔ Unanswered ❔ Wellness Check Project Code Issues

2 Upvotes

Hello, I'm trying to set up a script in Google Scripts (uses JS) to send a Covid Wellness Check form to certain groups of people. I barely got a c- in my python coding class and I've never even worked with JS, so I'm shooting my shot on here.

I want to receive an email with the wellness check every day unless it's Martin Luther King Jr. Day (a national holiday on Jan. 17 here in the states). I'm aware the time of day may cause an issue later on, but for now I'm just trying to accomplish what mentioned above.

Why am I not receiving an email when I run this script?

function test() {    var days = [ScriptApp.WeekDay.Monday, ScriptApp.WeekDay.Tuesday, ScriptApp.WeekDay.Wednesday, ScriptApp.WeekDay.Thursday, ScriptApp.WeekDay.Friday];    var current = new Date()    var MLKJDay = new Date(2022,0,17,0,0,0,0)    if (current !== MLKJDay){      ScriptApp.newTrigger("emailMe")}      else {      return;} }           function emailMe() {    MailApp.sendEmail({       to:’[my email address]’,       subject:’Wellness Check Test',       body:'',   }) }


r/JavaScriptHelp • • Jan 07 '22

❔ Unanswered ❔ Image directory query and display

2 Upvotes

Hey guys,

I am completely lost on this one so I will try my best to explain my situation and what I am trying to achieve.

If you look at a website like Channelate.com you can see that they use a database called comicctrl to present their content.

I can't really justify using a database per content page and so I just wanted to achieve the following:

- Link an image directory on my server to display its contents in a container on the webpage.
- Only display the newest image within the directory within the container.
- Add a 'forward' and 'backward' button that goes to the next newest or next oldest image in the directory and displays that instead.
- Add a 'random' button that randomly selects the image in the directory to display in the container.

On the face of it this seems like it should be completely achievable but I am struggling to find anything online that applies to this situation as I understand its a relatively specific use case.

thank you in advance!

Josh


r/JavaScriptHelp • • Jan 07 '22

❔ Unanswered ❔ Help with JS Webpage query

2 Upvotes

Hey guys,

I have a website that I am trying to implement a dark mode on. Unfortunately because of how it is set up applying the below script to 'body' does not apply to all of the elements i need it to apply to.

         });
              $( ".change" ).on("click", function() {
            if( $( "body" ).hasClass( "dark" )) {
                $( "body" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( "body" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });

As you can see this will apply a class to the body which amends the styling of the element. However I cannot seem to figure out how to apply this to multiple elements and so far the only fix I have is a super inelegant solution:

 $( ".change" ).on("click", function() {
            if( $( ".topbar ul.nav>li>a" ).hasClass( "dark" )) {
                $( ".topbar ul.nav>li>a" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( ".topbar ul.nav>li>a" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });
              $( ".change" ).on("click", function() {
            if( $( ".container" ).hasClass( "dark" )) {
                $( ".container" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( ".container" ).addClass( "dark" );
                $( ".change" ).text( "ON" );
              
            }
        });

As you can see I am just copying the script and pasting it below for all of the additional elements that I need the class added to. Does anyone know how I can reduce this because this is janky as hell and I cannot find anything online to help.


r/JavaScriptHelp • • Jan 03 '22

✔️ answered ✔️ Load a page then perform a click

2 Upvotes

After a backend call, I need to redirect a user to a page then put them on the correct tab. I tried this

$('body').load('http://localhost:8085/abc/def/123', function() { 
	document.getElementById('foo').click(); 
});

But there are some issues. Some of my layout loads incorrectly. Perhaps it's because the page is loaded into the body tag?

Is there perhaps some other way I can do this?

Thanks.