r/JavaScriptHelp • • Aug 23 '18

While loop freezes browser

1 Upvotes

Hey all. Fairly simple problem for you here. I just want to know any alternatives to the while loop with this code:

// This document has been nominated for the "Least Efficent Javascript of The Year" award

$(document).ready(function(){
  while (true) {
    $("#s1").delay("slow").fadeIn();
      setTimeout(function(){
        $("#s1").delay("slow").fadeOut();
      }, 3000);

      setTimeout(function() {
        $("#s2").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s2").delay("slow").fadeOut();
          }, 3000);
      }, 4000);

      setTimeout(function() {
        $("#s3").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s3").delay("slow").fadeOut();
          }, 3000);
      }, 8000);

      setTimeout(function() {
        $("#s4").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s4").delay("slow").fadeOut();
          }, 3000);
      }, 12000);

      setTimeout(function() {
        $("#s5").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s5").delay("slow").fadeOut();
          }, 3000);
      }, 16000);

      setTimeout(function() {
        $("#s6").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s6").delay("slow").fadeOut();
          }, 3000);
      }, 20000);

      setTimeout(function() {
        $("#s7").delay("slow").fadeIn();
          setTimeout(function(){
            $("#s7").delay("slow").fadeOut();
          }, 3000);
      }, 24000);
    }
});

I know it's pretty ineffecient right now. Sorry for the mess.


r/JavaScriptHelp • • Dec 06 '18

Importing JSON object variables into SCSS

1 Upvotes

I have a JSON with all my colors for my app in it (like a theme), these can be changed depending on the user outside of the app. I know I can get the JSON and store it in a variable and use this inline styled in the html, but I think a better way would have it imported and used in my scss files. Any ideas on how this could be done?

Example of the JSON:

{

"colors":{

"primary":"#4286f4",

"secondary":"#ffffff",

"accent":"#ef0000"

},

"graphics":{

"login-bg":"/img/login.png",

"logo":"/img/logo.png"

}

}

Example of how I have it working now:

<button class="primary-btn" [style]="background-color: theme['colors']['primary'] ? theme['colors']['primary'] : ''">I'm a button</button>

Example of where I'd want it in my styles.scss:

.primary-btn {

background-color: theme['colors']['primary']

}


r/JavaScriptHelp • • Dec 14 '18

Jquery string filter help

1 Upvotes
<div class='myDiv'>
    <table summary='Bulk Tracking'>
      <span title='Bulk Tracking'>Bulk Tracking</span>
      
      <tr>
        <td>IL</td>
        <td>NR</td>
        <td><span class='ms-nowrap'>12/1/2018</span></td>
        <td>65</td>
        <td class='lastCell'>Waiting For</td>
      </tr>
      <tr>
        <td>TX</td>
        <td>FT</td>
        <td><span class='ms-nowrap'>12/9/2018</span></td>
        <td>22</td>
        <td class='lastCell'>Waiting For</td>
      </tr>
      <tr>
        <td>WY</td>
        <td>ND</td>
        <td><span class='ms-nowrap'>12/25/2018</span></td>
        <td>721</td>
        <td class='lastCell'>Waiting For</td>
      </tr>
      <tr>
        <td>MT</td>
        <td>NR</td>
        <td><span class='ms-nowrap'>12/7/2018</span></td>
        <td>33</td>
        <td class='lastCell'>Waiting For</td>
      </tr>
      <tr>
        <td>AK</td>
        <td>LR</td>
        <td><span class='ms-nowrap'>12/7/2018</span></td>
        <td>222</td>
        <td class='lastCell'>Waiting For</td>
      </tr>
      <tr>
        <td>VA</td>
        <td>ARR</td>
        <td><span class='ms-nowrap'>12/8/2018</span></td>
        <td>15</td>
        <td class='lastCell'>Received</td>
      </tr>
    </table>
    </div>

HTML

$(document).ready(function() {
    addTargetClasses();
    checkReceived();
});
(function($) {
    $(function() {
        var orgDates = $('table tr td span');

        var message = '';
        orgDates.each(function(i, elem) {

            parts = $(this).text().split('/');
            dt = new Date(parts[2], parts[0] - 1, parts[1])
                .getTime();
            diffdate = Math.floor((dt - new Date().getTime()) /
                (86400 * 1000));

            if (diffdate === 0 || diffdate === -1) {
                return;
            }
            if (diffdate > 0 || $(this).parents(
                    'tr.targetRow').find('lastCell').hasClass(
                    'crossout')) {
                return;
            }

            if ((diffdate + 2) < 1) {
                if (diffdate.length == 1) {
                    console.log(diffdate);
                }
                if ((diffdate + 2) == 0) {
                    diffdate = (diffdate + 1) + ' day ago';
                } else {
                    diffdate = (diffdate + 1) + ' days ago';
                }
            }

            diffdate = diffdate.toString().slice(1);



            state = $(elem).parents(
                '.targetTable tr.targetRow').find(
                "td:nth-child(2)").text();
            mailType = $(elem).parents(
                '.targetTable tr.targetRow').find(
                " td:nth-child(4)").text();

            message += state + ' ' + mailType + ' was due ' +
                diffdate + '<br/>';
        });

        $.alert({
            theme: "my-theme",

            title: "<span style='font-size:25px;'>" +
                "</span>",
            content: "The following bulk is past the expected received date:" +
                "<br/>" + "<br/>" + message,
            draggable: true,
            animationBounce: 1.5,
            buttons: {
                Dismiss: function() {}
            }
        });

        $('span[title*="Bulk Tracking"]').after(
            "<button id='alert_btn' type='button'>See Alerts</button>"
        );
        $('#alert_btn').after(
            '<div id="emmacontainer" class="emmacontainer"><div class="container__inner"><div class="subDiv"></div> </div></div>'
        );

        $('.subDiv').append(message);

        $('#emmacontainer').hide();
        $('#alert_btn').click(function() {
            $('#emmacontainer').slideToggle(400);
        });


    })
})
(jQuery);

function addTargetClasses() {
    $("table[summary*='Bulk'] ").addClass("targetTable");
    $(".targetTable tr").addClass("targetRow");
}

function checkReceived() {
    $('.targetTable td.lastCell:contains("Received")').addClass('crossout');
};

JS

Currently when I run this code I get this output:

IL NR was due 13 days ago
TX FT was due 5 days ago
MT NR was due 7 days ago
AK LR was due 7 days ago
VA ARR was due 6 days ago

This is correct but I'm looking for a way to combine lines that have the same number of 'days ago'.

So I want something like this:

IL NR was due 13 days ago
TX FT was due 5 days ago
MT NR and AK LR were due 7 days ago
VA ARR was due 6 days ago

Does anyone have any ideas or can point me in the right direction?


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 • • May 11 '21

✔️ answered ✔️ remove object from JS object/array

1 Upvotes

Hi,

I'm quite new to working with JSON.. I have an array of JSON objects in my localStorage. I'm trying to delete a specific object in that array. This task seems to be super complicated, anything that I'm trying that I find online turns out to be "not a function".

Just to make sure I didn't mess up how I save it in my localStorage (though I doubt that the error comes from that mistake)

in my localStorage, I have: (when I check the console > application (chrome)) :

Key: myItems
value:
{
"foo":{"tag":"foo","title":"footitle","desc":"foodesc"},
"bar":{"tag":"bar","title":"bartitle","desc":"bardesc"},
"yada":{"tag":"yada","title":"yadatitle","desc":"yadadesc"}
}

This should be fine so far.

How do I delete an object from that there? I guess it's not an array but an object? So I cannot use splice to start with.

I want to delete for example "bar", either by index (I can find a workaround to do that) or by tag (which would be easier).

Right now it seems it's saved as JS objects in the localStorage, does that make sense? Should it be JSON instead to save space? I guess it's easier (or the only way) to remove an object from the array/object of objects if it's a javascript object though, so need to parse it before I do anything to it anyway, right?

Thanks for help!


r/JavaScriptHelp • • Jun 19 '21

❔ Unanswered ❔ Why 'mouseover' does not work to simulate hover in some cases?

1 Upvotes

I'm trying to simulate a hover event, but while on certain elements it works as expected, on one in particular it doesn't.

This is what's not working:

function simulateMouseover(target) {
  var event = new MouseEvent('mouseover', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  }); 
  var canceled = !target.dispatchEvent(event);
  if (canceled) {
    // A handler called preventDefault.
    alert("canceled");
  } else {
    // None of the handlers called preventDefault.
    alert("not canceled");
  }
}

Then call it on a stored global element:

simulateMouseover(temp1); 

The example needs a use case, so here's a random FB gaming live, where you can only get the publish time of a stream programmatically if you hover over the date of it.

https://www.facebook.com/RealScottyBlades/videos/179401634042952

While calling the function on the avatar of a person that commented works (shows the pop-up), for the date at the top it does not. Any suggestion why this is the case, or how could I fix it in pure JS?

Cheers


r/JavaScriptHelp • • Jun 04 '21

❔ Unanswered ❔ .sort with Numbers

1 Upvotes

Good evening everyone, I am confused with the .sort method when it comes to numbers. This is the code I have to test.

const array = [2,4,3,1,5]

array.sort((a,b) => {
  console.log(a, b)
	if(a > b) return 1
  if(a < b) return -1
  })
console.log(array)

Every tutorial I see says that the code reads it as a = 2 and b = 4 when comparing. Bu as you see in the printed line, a is actually 4 and b is actually 2. Why is this?

As well, the code should read 4 is greater than 2, return 1. What does 1 mean?

And if we were comparing 4 and 3, it would read 3 (a) is less than 4 (b) and it would return -1 and at this point the code is ran twice, why? Also, what does -1 mean?

This is the output

Output:

4 2
3 4
3 4
3 2
1 3
1 2
5 3
5 4
[ 1, 2, 3, 4, 5 ]

Thanks!


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 18 '21

❔ Unanswered ❔ Javascript is so frustrating, help!

1 Upvotes

Hello guys! I'm starting to learn to program.

I've trying to learn Javascript for the past few months, and I find it very difficult to learn; I've been using Codecademy PRO and I don't seem to understand the logic of how things work and I always forget how to do things.

Any advice for learning Javascript as a first programming language?


r/JavaScriptHelp • • Jun 04 '21

✔️ answered ✔️ How do ask for input?

1 Upvotes

I am a newbie at js and I'm trying to make a test code How can i ask the user for input and set the text given as a variable?


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 • • Jun 06 '21

✔️ answered ✔️ Get index of dropdown and display associated info

1 Upvotes

Hello,

I am consuming an API in a backend lambda (using NodeJs v14), and filtering results, then using the results to send an HTML page to users. A form.

Upon loading, the user can select from the dropdown and element and enter more fields manually. Then submit the form.

How can I pull other information about the selection? there's more data associated with the select, I'm displaying 2 of 4, and on select, I'd like to populate 2 more fields on the form with the values associated with the selection, let the user modify them if need be, and upon POSTing the form, send those fields as well.

I'm very new to all of this, NodeJS/Javascript, so don't assume anything, I know nothing. Well, almost.

Thanks!

Here's the HTML form the lambda spits out:

    <form action="/processForm" method="post">
            <div id="schedule" class="form-group">
                <label for="Shows" class="col-xs-3 control-label">Shows:</label>
                <select id="Shows" name="Shows" class="form-control">
                  <% filteredResults.forEach(function(filteredResult, index) { %>
                  <option value="<%= filteredResult.p_episode_seriestitle %>"> <%= filteredResult.p_episode_seriestitle + " - " + filteredResult.channel %></option>
                  <% }); %>
                </select>
         </div>

For the selection made, I want to capture in the form associated data to that entry, namely:

filteredResult.date (event date)

and filteredResult.code (unique ID).


r/JavaScriptHelp • • Jun 23 '21

❔ Unanswered ❔ Help with School Project

1 Upvotes

Hi all, I'm pretty new to JS and I've hit a point in my coding school where my project is to build a diner menu with several different functions. The problem is that I don't have the first clue how to actually make this happen. I've spent months having information dumped on me, so they just expect me to know how to put all that information together into something functional, but it feels a bit like being handed a box of broken glass and being told to put it back together as a window, without ever having any clue what the window looked like in the first place.

Project requirements look like this:
- show them the entire menu (print out)
- A user selects an entree.
- “Waitress” makes a comment based on their selection
- comment can either be a comparison of the two items, or random comment pulled from a comment vault.
- Tell them the price
- repeat the above options for side choices (comment and a price)
- total up the cost
All I have so far is a couple of arrays with food items and waitress comments:

const entrees = [

{

item: "Guacamole Burger",

price: 8.99,

dinnerPrice: 2,

mealTag: ["lunch", "dinner"]

},

{

item: "Fish & Chips",

price: 6.99,

dinnerPrice: 2,

mealTag: ["lunch", "dinner"]

},

Etc...

const commentVault = [

{

comment: "An excellent choice!",

comment: "That one's my favorite!",

comment: "That's actually our special for the day!",

comment: "You're going to love that one!",

}

Etc...

Can anyone help me with this? Literally any advice would be appreciated.


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 • • Feb 14 '18

Help with simulating a ATM functionality

1 Upvotes

I’m working on a web interface to manage the banking tasks of players in a tabletop rpg.

Each player would have their own webpage that would act as an ATM. They could enter the amount they would like to deposit or withdraw and when the corresponding button is pushed its adds or subtracts from their account (also need to make overdraft impossible). For deposits 98% would be added to their account balance for deposits and the remaining 2% would be added to the banker’s account. All account balances would be kept on the server side.

Can this be accomplished easily with JavaScript?

Any help would be greatly appreciated.


r/JavaScriptHelp • • Feb 14 '18

Help with Google Charts code

1 Upvotes

I'm hoping somebody can assist with a Google Chart I'm trying to get configured. The chart can be seen here.

Basically, I need the numbers on each column to be in currency format when you hover over them. I have not been able to figure out how to change it.

Thank you


r/JavaScriptHelp • • Oct 22 '18

JavaScript not running right?

1 Upvotes

HTML file:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<link rel="stylesheet" href="styles.css">

<script src="script.js"></script>

</head>

<body>

<canvas id="mainCanvas" style="border:1px solid #d3d3d3">nope...</canvas>

</body>

</html>

JavaScript file:

document.write("Hello world.");

var mainCanvas = document.getElementById("mainCanvas");

var c = mainCanvas.getContext("2d");

c.width = 800;

c.height = 900;

c.beginPath();

c.lineWidth = "1";

c.strokeStyle = "red";

c.rect(10, 10, 110, 100);

c.stroke();

Problem:

I see the canvas. I see the &quot;Hello world.&quot; But I don&#39;t see the red box (this box is just for testing right now). BUT!!! If I put my JavaScript code in the HTML file insice a &lt;script&gt;&lt;/script&gt; then I get the red box. So what am I doing wrong?


r/JavaScriptHelp • • Dec 04 '17

Been stuck for days...

1 Upvotes

So I finished this project I've been working on on freeCodeCamp. I had a shit ton of code basically doing the same thing so I challenged myself to figure out how to consolidate the code so both my HTML file and my JS file would be much smaller and neat. (Trying to put in place good habits early). So, basically I'm trying to clone this node in my HTML to repeat itself 10 times, then I'm trying to append the data I'm pulling from the API I'm using to each clone of HTML I have. This is what I have so far and I feel like I'm so close, but I'm only getting frustrated now. https://pastebin.com/jzBsemkt

And here is the HTML code that I'm trying to consolidate as well. https://pastebin.com/4emC9zZX

I'm getting back the data that I want but it's coming through the element and displayed as actual HTML in the window. I'm not sure how I can change my code so that it comes through as the data that I want. If you look closely at the console it's showing all the data I want being appending but its coming through as a string wrapped in double-quotes.

Any insight on how to each this would be greatly appreciated. Thanks!


r/JavaScriptHelp • • Nov 29 '17

Javascript help

1 Upvotes

Hey can someone help me with cookies for a school assignment. The game I made is a murder mystery and I have to find objects. When I click the objects I want them to be saved to cookies and be able to get the images on a different page but only once they are clicked. Can someone help??


r/JavaScriptHelp • • Nov 30 '17

I have a javascript that I use in the bookmark bar that needs a tweek.. if at all possible

1 Upvotes

javascript:(function(){var options = document.getElementsByTagName('option');for(var i = 0; i < options.length; i++) options[i].selected = true;var signup=document.getElementById('signup');signup=signup.getElementsByTagName('button');signup[0].onclick();})();

This script effectively does what I need it to do, but only in one tab regardless of which browser I'm using (chrome, firefox, and even explorer). Is there a way to get it to function across all open tabs at the same time?


r/JavaScriptHelp • • Nov 29 '17

I need some help

1 Upvotes

Im working on a website but i need help there is something somewhere that converts the word sites into site. which ends up breaking my link. for example http://ruckus09/sites/index.html turns to http://ruckus09/site/index.html i want to create something in JS that when I click the link itll take the string http://ruckus09/+"sites"+/index.html then puts that whole thing together and takes them to the proper site. any help guys? thanks


r/JavaScriptHelp • • Jul 28 '18

Need help figuring out wheres waldo

1 Upvotes

Waldo is hiding in some strings.

You've been given a string named waldoString. Waldo will be hiding in it somewhere. Return the index of where in the string 'Waldo' starts.

function findWaldo(str) {

var waldoPosition;

// Code below here

return waldoPosition; }

I've been stuck on here for about an hour and I've tried many inputs. I feel like I'm missing something very simple but I can't get my head straight on this problem.


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 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 • • Aug 05 '21

❔ Unanswered ❔ How to solve filter method retuning undefined?

1 Upvotes

I'm trying to store PurchaseStatus in that products.data. Those products which doesn't have purchase status should be retuned to 0.

Here I'm getting the purchase status, the problem is products which haven't purchased returns undefined in product.data. How can I solve this issue or is there any alternative best solution for this?

I'm new to JS and thanks in advance

products.data = await getAllPurchases().then((purch) => products.data.map(inte => {
inte['_purchaseStatus'] = purch.data.filter(pur => pur.ProductID === inte.id).map(purcha =>
purcha.PurchaseStatus)[0];
return inte;
})).catch(e => console.log(e));