r/JavaScriptHelp • • Jul 11 '21

✔️ answered ✔️ .contains is not a function

1 Upvotes

Edit:

const UN = urlParams.get('username'); const check = UN.toString(); if(check.includes(" ")){ window.location.href = "URL Removed" }

I'm trying to redirect the user if their username contains a space, but I'm getting

Uncaught TypeError: check.contains is not a function

as a result my code:

const UN = urlParams.get('username'); const check = UN.toString(); if(check.contains(" ")){ window.location.href = "URL Removed" }

r/JavaScriptHelp • • Jul 03 '21

❔ Unanswered ❔ Typescript frameworks/packages for blitz.js

1 Upvotes

I started working on a project with Blitz.js. I'd like to add an admin panel to it, and was looking at react-admin. I know the project is going to be mainly typescript, SQLite and Postgres with API support. Is is possible to combine the react-admin with the authentication, API, and DB that blitz.js provides? Is there a tutorial on how to achieve something like this? Or is there a better dashboard template I can follow to achieve the same result with less effort?


r/JavaScriptHelp • • Jun 25 '21

💡 Advice 💡 Not show the time/seconds until ‘record’ starts on html5 player

1 Upvotes

This code allows the page vistor to click a ‘display’ button to show the camera view on the page, but not start the video recording (they can select a seperate ‘record’ button to start recording). However, the timer/seconds start upon selecting ‘display’ the camera view. I’d like help with having the time/seconds not start until ‘record’ button is clicked. Any help/guidance is appreciated. Here’s the code:

let blobs = [];
let stream, mediaRecorder, blob;

let video = document.getElementById("video");
var displaying = false;
var recording = false;
async function display() {
  stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  });
  video.srcObject = stream;
  displaying = true;
}
function startRecording() {
  if(displaying){
    mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.ondataavailable = (event) => {
    // Let's append blobs for now, we could also upload them to the network.
      if (event.data) {
        blobs.push(event.data);
      }
    };
    mediaRecorder.onstop = doPreview;
    // Let's receive 1 second blobs
    mediaRecorder.start(1000);
    recording = true;
  }
}

function endRecording() {
  if(recording){
    // Let's stop capture and recording
    mediaRecorder.stop();
    stream.getTracks().forEach((track) => track.stop());
    recording = false;
  }
}

function doPreview() {
  if (!blobs.length) {
    return;
  }
  // Let's concatenate blobs to preview the recorded content
  blob = new Blob(blobs, { type: mediaRecorder.mimeType });
  video.srcObject = null;
  video.src = URL.createObjectURL(
    blob,
  );
}

Here is the html:

<video id="video" autoplay controls muted playsInline></video>
<button id="display" onclick="display()">Display Camera</button>
<button id="start" onclick="startRecording()">Start Recording</button>
<button id="stop" onclick="endRecording()">Stop Recording</button>

And here is an example:

https://codepen.io/pmw57/pen/LYWwOZj

it was suggested that I should remove the video controls from the video first and then add them back when the recording starts., but I don't know how to do that.

any help is appreciated.


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 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 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 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 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 • • 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 • • 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 • • Apr 30 '21

❔ Unanswered ❔ How would I search through this type of array?

1 Upvotes

So I am using ajax to pull a php array and I want to search through the array using javascript.

The php array is multidimensional.

normally in php I would just do foreach(myarray as m), I want something similar and having difficulties figuring it out. I am very new to javascript.

Here is a snippet of what the php array looks like: snippet


r/JavaScriptHelp • • Apr 29 '21

❔ Unanswered ❔ Trying to get new "div"s appended onto a button's parent.

1 Upvotes

I'm a very early beginner JavaScript learner, and I'm trying to make a program with JS and HTML. I want my end program to be able to create new divs, each with buttons to create additional divs inside them. I was able to use an original div when the code first starts that I could put the first layer of divs in, but I'm having trouble now that I want to create that second layer of divs. The problem is that I don't know what to write before the ".appendChild(myChildDiv)" to target the div that is the parent of the buttons, as those parents +buttons are created dynamically within my first main div. Hopefully seeing my project will clear up any confusion about what I mean by that.

If anyone knows of a way I can create divs dynamically within a parent div without selecting the parent div by id or name alone, let me know!

my JavaScript:

var mainDiv = document.getElementById("mDiv");
var selFighter;
var numFighters = 0;


function newFighter() {
  var fDiv = document.createElement("div");
  var addTBtn = document.createElement("button");
  var fNameLabel = document.createElement("label");
  var fNameDiv = document.createElement("div");
  var topfDiv = document.createElement("div");
  var botfDiv = document.createElement("div");
  var addT;
  numFighters += 1;
  document.getElementById('test').innerHTML = numFighters;


  fNameDiv.appendChild(fNameLabel);
  topfDiv.appendChild(addTBtn);
  fDiv.appendChild(fNameDiv);
  fDiv.appendChild(topfDiv);
  fDiv.appendChild(botfDiv);
  document.getElementById("mDiv").appendChild(fDiv);

  fNameDiv.className = "fName";
  topfDiv.className = "topfDiv";
  botfDiv.className = "botfDiv";
  fDiv.className = "fDiv";
  addTBtn.className = "addTBtn";
  fNameLabel.className = "fName";

  addTBtn.innerHTML = "Add ticks";
  addTBtn.setAttribute("onclick", "addTick('this')");
  fNameLabel.innerHTML = "temp";
  fNameLabel.setAttribute("contenteditable", "true");
}

function addTick() {
  var tick = document.createElement("div");
  this.appendChild(tick);
  tick.className = "tick";
}

my HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Tick Tracker</title>
    <style>
      label {
        color: darkorange;
      }
      .fDiv{
        margin-top: 20px;
        min-height: 100px;
      }
      .topfDiv {
        border: 4px outset grey;
        background-color: #3b3a3a;
        color: orange;
        overflow-y: visible;
        border-style: inset;
        min-height: 75px;
        min-width: 200px;
        display: block;
        position: static;
      }
      .botfDiv {
        border-style: dashed;
        height: 50px;
      }
      div.fName {
        background-color:inherit;
        width: fit-content;
        min-width: 20px;
        height: 25px;
        border: 5px;
        overflow-x: scroll;
        border-style: groove;
        border-color: grey;
        padding-bottom: 5px;
      }
      label.fName{
        font-size: 25px;
        white-space: nowrap;
        bottom: 5px;
        justify-content: center;
      }
      .addTBtn {
        border: 3px outset grey;
        font-size: 20px;
        height: 75px;

      }
      .newFighterBtn {
        position: fixed;
        z-index: 1;
        font-size: 20px;
      }
      .tick {
        background-color: darkorange;
        width: 6px;
        height: 6px;
        border-style: dashed;
      }


      body {background-color: #3b3a3a;}
      h1 {color: darkorange;}
      button {font-size: 3.5vw; color: darkorange; background-color:#3b3a3a;}
    </style>
    <script src="TickTracker.js"></script>
  </head>
  <body>
    <h1 style="white-space:nowrap;">D&D Tick Tracker</h1>

    <button type="button" onclick="newFighter()" class="newFighterBtn"> New Fighter </button>
    <button type="button" onclick="testFighter()" style="position: fixed; z-index: 1; font-size: 20px; left: 150px"> Begin count </button>
    <button type="button" onclick="addTick()" style="position:relative; left: 300px;"> test tick </button>

    <div id="mDiv" class="mDiv" style="overflow: scroll;">
    <p>.</p>
    <p id='test'></p>



    </div>
  </body>
</html>

r/JavaScriptHelp • • Apr 26 '21

❔ Unanswered ❔ How Grid Garden or Flexbox Froggy compares output?

Thumbnail
self.frontend
1 Upvotes

r/JavaScriptHelp • • Apr 23 '21

❔ Unanswered ❔ Discord bot mute command doesn't work

1 Upvotes

Hello. I am trying to code a discord bot for my discord server in JavaScript. But my clear command doesnt work. I add the code for it down below. please help and explain why it didn't work. Thanks!

code:

client.once('ready', () => {
console.log('egg bot is ready!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
    }else if(command === 'youtube') {
client.commands.get('youtube').execute(message, args);
    }else if(command === 'invite') {
client.commands.get('invite').execute(message, args);
    }else if(command === 'ban') {
client.commands.get('ban').execute(message, args);
    }else if(command === 'mute') {
client.command.get('mute').execute(message, args);
    }else if (command === 'clear'){
client.commands.get('clear').execute(message, args);
    }
});
client.login('MY TOKEN IS HER');

and there is a call from the main file:

const Discord = require('discord.js');
const client = new Discord.Client();

const prefix = 'h!';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}

client.once('ready', () => {
console.log('egg bot is ready!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
    }else if(command === 'youtube') {
client.commands.get('youtube').execute(message, args);
    }else if(command === 'invite') {
client.commands.get('invite').execute(message, args);
    }else if(command === 'ban') {
client.commands.get('ban').execute(message, args);
    }else if(command === 'mute') {
client.command.get('mute').execute(message, args);
    }else if (command === 'clear'){
client.commands.get('clear').execute(message, args);
    }
});
client.login('MY TOKEN IS HERE');


r/JavaScriptHelp • • Apr 23 '21

❔ Unanswered ❔ When I execute ajax request I get error "Uncaught InternalError: too much recursion". Why could this be happening?

1 Upvotes

jquery:

function follow() {
   const followBtn = $('.mypage__follow');

   followBtn.click(function () {
      $.ajax({
         type: 'POST',
         url: 'php-scripts/my-pageHandler.php',
         dataType: 'html',
         data: {
            followBtn: followBtn
         },
         success: function (data) {
            alert(data);
         }
      });
   });
}

php:

function follow()
{
   if (isset($_POST['followBtn'])) {
      echo 'Works';
   }
}

r/JavaScriptHelp • • Apr 22 '21

💡 Advice 💡 For some reason the class/type "randomBouncingBall" isn't working, can someone pls help me?!

1 Upvotes

//class for a bouncing ball

class BouncingBall

{

//fields ("properties") of the ball

float x, y; //x and y position

float dx, dy; //x and y speed

float r; //radius

color ballColour; //Colour

//constructor for a bouncing ball instance

BouncingBall(float xInit, float yInit, float rInit, color colourInit, float dxInit, float dyInit)

{

x = xInit;

y = yInit;

r = rInit;

ballColour = colourInit;

dx = dxInit;

dy = dyInit;

}

BouncingBall randomBouncingBall() {

return new BouncingBall(random(100, 151), random(100, 151),

random(15, 36),

color(random(0, 256),

random(0, 256),

random(0, 256)),

random(-2.0, 2.0), random(-2.0, 2.0)

);

}

//draws the ball

void render()

{

stroke(1);

fill(ballColour);

ellipse(x, y, r*2, r*2);

}

//animates and bounces the ball

void update()

{

//move the ball

x += dx;

y += dy;

//keep the ball bouncing within the screen

//hit the left edge and going left?

if(( x - r <= 0) && (dx < 0))

{

dx = -dx;

}

//hit the right edge and going right?

if((x + r >= width - 1) && (dx > 0))

{

dx = -dx;

}

//hit the top edge and going up?

if((y - r <= 0) && (dy < 0))

{

dy = -dy;

}

//hit the bottom edge and going down?

if ((y + r >= height - 1) && (dy > 0))

{

dy = -dy;

}

}

}

final color WHITE = color(255);

//variable for the ball

BouncingBall ball1, ball2, ball3;

void setup()

{

size(500, 500);

smooth();

ball1 = new randomBouncingBall();

ball2 = new randomBouncingBall();

}

//draws a single frame and animates the ball

void draw() {

//move balls

ball1.update();

ball2.update();

//clear the screen

background(WHITE);

//draw the balls

ball1.render();

ball2.render();

}


r/JavaScriptHelp • • Apr 18 '21

❔ Unanswered ❔ How can I get my messages to show up properly?

1 Upvotes

I have two buttons - one that sends two messages with a one-second interval, and the other only sends one message, with the second left as undefined (this will be clearer once you see the code). How do I stop undefined from showing up?

<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' ' + currency)">HUNT</button>
<br>
<button onclick="addLog('Resources sold')">SELL</button>

<div id="logs" style="display: flex; flex-direction: column-reverse;"></div> 
function addLog(logBefore, logAfter) {
    var par = document.createElement("p");
    var node1 = document.createTextNode(logBefore);
    var node2 = document.createTextNode(logAfter);
    par.appendChild(node1);

    var element = document.getElementById("logs");
    // Here you can also use element.childNodes.length
    const count = document.getElementById("logs").getElementsByTagName("p").length;
    if(count >= 18){
        element.removeChild(element.childNodes[0]);
    }
    element.appendChild(par);

    if (node2 !== undefined) {
        setTimeout(function () {

            console.log(logBefore)
            console.log(logAfter)

            var par = document.createElement("p");
            var node2 = document.createTextNode(logAfter);
            par.appendChild(node2);


            var element = document.getElementById("logs");
            // Here you can also use element.childNodes.length
            const count = document.getElementById("logs").getElementsByTagName("p").length;
            if (count >= 8) {
            element.removeChild(element.childNodes[0]);
            }
            element.appendChild(par);
        }, 1000);
    }
};

r/JavaScriptHelp • • Apr 16 '21

❔ Unanswered ❔ JQuery to replace a string anywhere on the page, EXCEPT in input boxes

1 Upvotes

I'm working on a project that will let people discuss stocks. As such, if anyone enters the $ plus a string of letters, I have a dead simple query in the UI to replace that with a link to yahoo finance. Here it is:

$(document).ready(function(){
var replaced = $("body").html().replace(/\$([a-zA-Z]+)\b/g,
'<a href="https://finance.yahoo.com/quote/$1">\$1</a>');
$("body").html(replaced);
});

My problem is, when people make a post it generates a preview, but I also hide the original draft in hidden inputs. When the substitution occurs, it breaks those inputs altogether, closing the tag too early.

I admit, I know only enough Javascript to be dangerous, so I'm wondering if anyone can show me how to tweak my existing JS and have it replace the text anywhere in the page, so long as it's not in a form fields value attribute.

Can anyone point me in the right direction at the very least?

Thanks!


r/JavaScriptHelp • • Apr 14 '21

✔️ answered ✔️ help with figuring out why a if statement is not evaluating to True

1 Upvotes

Hello,

I am trying to figure out why this statement is not executing and evaluating as I expected it to. I tried to find out with chrome debug tools and what I found out is that it is just not executing. I think answer lays in

if (key.toString() == currentservice.toString())

I added .toString() to make sure that both would evaluate but it did not help.

Can anyone tell me what I do wrong here?

here is the complete code:

let bonus1 = "text for what bonus1 entails"
let bonus2 = "text for what bonus2 entails"
let bonus3 = "text for what bonus3 entails"
let bonus4 = "text for what bonus4 entails"
let bonus5 = "text for what bonus5 entails"
let bonus6 = "text for what bonus6 entails"
let bonus7 = "text for what bonus7 entails"

//Dict with bonus variables as content
const Patterns = {
    "0,0,0,1,1,0,0,0,0,0,0,0,0,": [bonus1, bonus5, bonus6],
    "0,0,0,0,0,1,0,0,0,0,0,0,0,": [bonus4, bonus5],
    "1,0,0,0,1,0,0,0,0,0,0,0,0,": [bonus1, bonus5],
    "0,1,0,1,0,0,0,0,0,0,0,0,0,": [bonus5, bonus6],
    "0,0,1,1,1,0,0,0,0,0,0,0,0,": [bonus1, bonus5, bonus6],
    "0,1,0,0,1,0,0,0,0,0,0,0,0,": [bonus4, bonus5],
    "0,1,0,1,0,0,0,0,0,0,0,0,0,": [bonus4, bonus5],
    "1,1,0,0,1,0,0,0,0,0,0,0,0,": [bonus5, bonus3, bonus6],
    "1,0,0,0,0,1,0,0,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "1,0,0,0,1,0,0,1,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "0,1,0,0,1,0,1,0,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "0,0,1,1,0,0,0,0,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "1,0,0,0,0,0,0,1,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "0,0,0,0,1,0,1,0,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "0,0,0,1,0,0,0,1,0,0,0,0,0,": [bonus1, bonus5, bonus4],
    "0,0,0,0,0,0,0,1,0,1,0,0,0,": [bonus1, bonus5, bonus4],
    "0,1,0,0,0,0,0,0,0,1,0,0,0,": [bonus1, bonus5, bonus4],
    "0,0,0,0,1,0,0,0,0,1,0,0,0,": [bonus1, bonus5, bonus4],
    "1,0,0,0,0,0,0,0,0,0,1,0,0,": [bonus1, bonus5, bonus4],
    "1,0,0,0,1,0,0,0,0,0,1,0,0,": [bonus1, bonus5, bonus4],
    "0,1,0,0,0,0,0,0,0,0,0,0,1,": [bonus1, bonus5, bonus4],
    "0,0,0,0,1,0,0,0,0,0,0,0,1,": [bonus1, bonus5, bonus4],
    "0,0,0,0,0,0,0,1,0,0,0,0,1,": [bonus1, bonus5, bonus4],
}
//Currentsit() Executes on mouseclick of a form button
function currentSit() {
    let currentservice = "";
    $('.currentSit:checkbox').each(function () {
        currentservice += this.checked ? "1," : "0,";
    });
    document.getElementById("sitOld").innerHTML = currentservice;
    if (currentservice in Patterns) {
        for (key in Patterns) {
            if (key.toString() == currentservice.toString()) {
                document.getElementById("currentbonus").innerHTML = Patterns[value]; return false
            } else {
                document.getElementById("currentbonus").innerHTML = "With these services no bonus"; return false

            }
        }
    } else {
        console.log("this combination is not in Patterns")
    }
}

Thank you for your time.

Got it. did not notice it was evaluating two different strings.


r/JavaScriptHelp • • Apr 11 '21

❔ Unanswered ❔ Listen for 500 responses on Ajax calls

1 Upvotes

I'm listening to xhr events on a webpage, in order to catch any possible request failures. In order to listen to all of them, I'm applying this pseudo-monkey-patch:

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {

console.log(this.readyState); // this is always 4, but I'm trying to 
listen for when it's not successful
console.log(this.responseText); //the respoinse

});

reqOpen.apply(this, arguments);

It works when there is a successful response, but other than that it won't catch anything.

Is there any way I can try to catch unsuccessful requests (specifically requests that return a 500 response?

Thanks


r/JavaScriptHelp • • Apr 11 '21

💡 Advice 💡 How do you turn a cursor pointer into a dial?

1 Upvotes

Hi, first time working on javascript here, so I wanted to make it so that when you turn the dial all the way once, a capsule will pop out. When that happens when you click on the capsule a png will appear, after a few seconds it will disappear and the whole process will repeat until you get the one you want.

The problem is I don't really know where to start on how to do this, so I would appreciate the help.

📷
Here's what it looks like now: https://gyazo.com/9eedd59f5b690e4cafa762515f60ef26

(the black button is where the dial should be, I have a png for the dial but, Idk how to do that)

Here's the Javascript:

// JavaScript Document
var gasha_prize = [
'<img class="capsule-img" src="images/blue_capsule.png">',
'<img class="capsule-img" src="images/red_capsule.png">',
'<img class="capsule-img" src="images/green_capsule.png">',
'<img class="capsule-img" src="images/purple_capsule.png">',
'<img class="capsule-img" src="images/pink_capsule.png">',
'<img class="capsule-img" src="images/Gold_capsule.png">'
];
function prize_roll(this_element) {
if (this_element.getAttribute('data-prize') == 'no') {
this_element.setAttribute('data-prize', 'yes');
var gasha_machine_prize = document.getElementById('gasha_machine_prize');
gasha_machine_prize.innerHTML = '';
var random = Math.floor(Math.random() * gasha_prize.length);
gasha_machine_prize.innerHTML = '<div>'+ gasha_prize[random] +'</div>';
gasha_machine_prize.style.opacity = 1;
setTimeout(function() {
gasha_machine_prize.style.opacity = 0;
this_element.setAttribute('data-prize', 'no');
        }, 4000)
    }
}


r/JavaScriptHelp • • Apr 07 '21

❔ Unanswered ❔ is it possible to append zeros to input field in order to maintain a minimum dollar amount?

1 Upvotes

I have a text input box that lets users insert a dollar amount, but I want to have a minimum of $1,000.00 and also not allow cents. So Ideally when users type into the input it should only start changing at the placement of the number 1.

example, typing 54 should display $54,000.00 I'm using jquery mask to handle the comas and dollar symbol, but I don't see a built in function for my needs. any ideas?


r/JavaScriptHelp • • Apr 01 '21

❔ Unanswered ❔ some bug when dragging a carousell

1 Upvotes

What's wrong with my code?

https://foobar.roofaccess.org/carousell/

I have a carousell that I want to be NOT draggable on desktop but draggable on mobile devices. Also, on mobile, the element that I drag into focus should automatically be active, on desktop, only when I click it.

It works kind of fine, but when you drag on mobile, after the dragged element is active and you click it, it switches back to the previous element (assigns the active class to the previous element). You can check the console, I put a concole.log to make that clear.

Please help!

Here's my js script:

window.onload = function () {
    var theBirds = document.getElementsByClassName('bird');
    var temp = theBirds[0];
    var carousell = document.getElementById('carousell');
    var bird = "bird=";
    var cc = getCookie(bird);

    addAttribute();

    for (let b = 0; b < theBirds.length; b++) {
        if (addAttribute() == true) {
            theBirds[b].addEventListener('itemshown', function() {
                getValue(this);
                console.log('dragged');
            });
        } else {
            theBirds[b].addEventListener('click', function() {
                getValue(this);
                console.log('clicked');
            });            
        }
    }
        
    function addAttribute() {
        if(window.innerWidth < 600) {
            var drag = carousell.getAttribute('uk-slider');
            // "draggable" is not a separate attribute but part of the "uk-slider" attribute so I just set the whole attribute here
            drag = 'draggable: true; finite: true; center: true; velocity: 0;';
            carousell.setAttribute('uk-slider', drag);
            return true;
        } else {
            return false;
        }
    }
                    
    function getValue(element) {
        index = Array.prototype.indexOf.call(element.parentNode.children, element);
        UIkit.slider(".uk-slider").show(index);
        setCookie(index, 1);
        if (temp) {temp.classList.remove("current");}
        element.classList.add("current");
        console.log('bird: '+index);
    }

    function setCookie(value, days) {
        var d = new Date;
        d.setTime(d.getTime() + 24*60*60*1000*days);
        document.cookie = bird + value + ";path=/;expires=" + d.toGMTString();
    }

    function getCookie(bird) {
        var v = document.cookie.match('(^|;) ?' + "bird" + '=([^;]*)(;|$)');
        return v ? v[2] : 0;
    }
    
    function deleteCookie(bird) { 
        setCookie(0, 1); 
    }
    
}

r/JavaScriptHelp • • Mar 19 '21

💡 Advice 💡 Help with coding javascript on code.org applab

1 Upvotes

Hi. I am struggling here haha. I am making an app on code.org to tell the user the number of covid cases in a random state or country. The user can choose whether they want a state or a country. Then whether they want a state/country with a low/medium/high number of cases. When it is run, there is an error:

WARNING: Line: 84: setText() text parameter value (undefined) is not a uistring.ERROR: Line: 84: TypeError: Cannot read property 'toString' of undefined

Any help would be much appreciated thank you.

https://studio.code.org/projects/applab/LtR6Yrqt4qwuMTclvpME_3rl9bjBQ4ml_tB_pW4W6as


r/JavaScriptHelp • • Mar 17 '21

❔ Unanswered ❔ Need help making JS work with a Kinect

1 Upvotes

Hello everyone, I’m Victor. I’m not a coder in any way shape or form, so please be kind. I’m working with this Pen I found online for a graduation project and I’m trying to make it work with a Kinect. The goal is to turn the interaction that happens when the mouse hovers the dotted area reactive to people’s presences. This is the code I’m working on: https://codepen.io/victorvercillas/pen/oNYPodV

I know it’s possible I just have no idea where(or how) to start.

Important info: The Kinect I got available is 1st gen.

let x = 0, 
    y = 0, 
    strength = 200;

let mouseMoveHandler = function (e) {
    x = e.pageX;
    y = e.pageY;
};

var points = Array.from(document.querySelectorAll("circle"), (el) => {
    return {
      circle: el,
      x: Number(el.getAttribute("cx")),
      y: Number(el.getAttribute("cy")),
      ox: Number(el.getAttribute("cx")),
      oy: Number(el.getAttribute("cy"))
    };
});

function newElementPosCalc(element, x, y) {
  let dx = element.x - x;
  let dy = element.y - y;
  let angle = Math.atan2(dy, dx);
  let dist = strength / Math.sqrt(dx * dx + dy * dy);
  element.x += Math.cos(angle) * dist;
  element.y += Math.sin(angle) * dist;
  element.x += (element.ox - element.x) * 0.1;
  element.y += (element.oy - element.y) * 0.1;
  return element;
}

function animate() {
  points.forEach((el, i) => {
    // start repulsion calculation
    var newEl = newElementPosCalc(el, x, y);
    // end repulsion calculation
    el.circle.setAttribute("cx", newEl.x);
    el.circle.setAttribute("cy", newEl.y);
  });
  window.requestAnimationFrame(animate);
};

window.addEventListener("mousemove", mouseMoveHandler);
animate();

Some backstory:

The dots you see on the black square will be project on the ground from a projector pointing down. I’d like to make them reactive to whoever walks over them, with that repulsive effect you see on the code when you hover the mouse over the dots.

Thank you so much for anyone taking their time to try to help me in any way, just by reading this. Hope you’re having a good week!