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 • • 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);


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

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

Thumbnail
self.frontend
1 Upvotes

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 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 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 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 • • 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 • • 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 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 • • 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 • • Jan 04 '18

What am I doing wrong?

2 Upvotes

I have been trying to make my own website for some time. But I can't seem to nail the last piece of js.


<function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; }

<script type="text/javascript"> jQuery(function($) { $(document).ready( function() { $('.navbar').stickUp(); }); }); </script>


Can someone help me with what I am doing wrong?

Thanks in advanced.

Pirate_Bunny


r/JavaScriptHelp • • May 16 '18

Velocity + For loop (kinda)

1 Upvotes

I am relatively new to javascript, but I have read the posting rules and I have two questions that were not mentioned. The code can be found here on code.org (required for school):

https://studio.code.org/projects/applab/bXOxJZLyeddI45H7EmpmIMCZqsbuOKe_5lz0l3v3rVw If you would like to mess around with it, simply press remix which will create a local version that you can tamper with. (Sorry for Messiness - I am relatively new to js)

My first question is a question which isn't necessarily specific to this game. I currently have it set up to where the velocity of "snake" is set to 0, by using both snake.velocity and the individual snake.velX and snake.velY. Each direction (up(), down(), left(), right()) simply sets the velocity to 10 in each direction. What I've found, however, is that after performing deathAction(), the velocity clearly increases. How do I make it so that the velocity never grows above 10 in this instance? Or alternatively, how do I actually reset the velocity so it only increases to 10 again?

My second question is more specific, but simpler. A new "snake" segment is created after each Collision, but I simply don't know how to make it so the first added (second total) "snake" segment follows the rest of the snake. Relevant code would be found in the functions snakeExtend() and snakeObj().

This are the two problems that I need immediate help with, but feel free to let me know if there are any other mistakes you notice or ways in which I could improve.


r/JavaScriptHelp • • Dec 20 '15

JS Tutorial: interactive animated sprites with 15 lines of code

1 Upvotes

Beginner to pre-intermediate.

You don't need to use HTML5 to use spritesheets in your games or webpages

http://sprite.slicker.me/tutorial/tutorial.htm


r/JavaScriptHelp • • Oct 26 '17

Capturing UserMedia (audio only), resampling and sending to NodeJS

2 Upvotes

Hey redditors

Hopefully amongst you there is someone who has dealt with this problem before. I know it sounds simple but after two days looking on every portal imaginable I give up trying to find the answer my self and I turn to you guys.

Unfortunately I know nothing about audio, sample-rates, bitrates, etc. And probably thats where my problem lays

Here it is: I’m building a softphone web client in JS

Client UI is supposed to load the UserMedia and capture the Audio, resample and stream in real time. Not collect and save to some file like a lot of online forums demonstrate.

I need the audio to be in Raw audio (pcm) format. 16000 samplerate. In chunks of 200ms ~320bytes (each chunk with the Raw audio header)

These chunks are to be sent over SocketIO to the NodeJS where the rest is already in place.

SocketIO, NodeJS and UI components are already done. So it’s literally this last bit.

Any help is greatly appreciated

EDIT: Here's a JSBin of what I've got so far. It looks almost accurate, but No actual sound comes out on the other end. https://jsbin.com/tuxebij/edit?html,js,output


r/JavaScriptHelp • • Mar 14 '18

How do you put a script in the header?

1 Upvotes

I'm making this site for my friend's computer company. We made a logo in processing, and we want to put the logo in the header portion of the site. We'd take a screenshot, but it's moving. Right now it keeps being put at the bottom of the footer. Here is what it looks like:

<html> <head> <TItle>

    </TItle>
    <link rel="stylesheet" type="text/css" href="page.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script> <!--this is just a CDN for p5js, processing's language-->
</head>
<body>
    <div class="container">
        <header>
            <script src="circle.js"></script><!--This is where I want to put the logo-->
        </header>
        <article>
            <!--Some content here-->
        </article>
    </div>

Now the circles in P5js code looks like this:

t = 0;

function setup() { createCanvas (windowWidth, windowHeight); background (0, 0, 0); }

function draw() { translate(width/2, height/2); background (0, 0, 0);

a = -abs(18sin(tPI/100)-30); t = t + 1; if (t > 400){ t = 0; }

strokeWeight(50);

noFill();

stroke(255, 0, 0);
ellipse(0, 12+a, 200, 200);

stroke(0, 255, 0);
ellipse(12+a, -12-a, 200, 200);

stroke(0, 0, 255);
ellipse(-12-a, -12-a, 200, 200);

	stroke(255, 0, 0);
rotate(HALF_PI);

arc(12+a, 0, 200, 200, 0, PI);

noFill();
stroke(255);
ellipse(0, 0, 200, 200);

} And the CSS looks like this:

body { font-family:Lucida Console, Monaco, monospace; background:black; } .container { width: 100%; border: 1em; }

header, footer { padding: 1em; color: white; background-color: black; clear: left; text-align: center; } article { margin-left: 10px; border-left: 1px solid gray; padding: 1em; overflow: hidden; background-color:#f2f2f2; border-right: 1px solid gray; }

MY MAIN QUESTION IS HOW DO I GET THE SCRIPT IN THE HEADER PORTION


r/JavaScriptHelp • • Mar 23 '18

Need help with undefined error

1 Upvotes

I keep getting an undefined error whenever I try to use any of the data inside a JSON array, it's supposed to take the data from the webpage and use it to push it via a button to a separate webpage that merges it with a word document.

I declared the variable using

const data_view_372 = Platform.models['view_372'].data.toJSON();

and then I have a loop go through a shifts table and add it to my url variable.

for(a = 0; a < 3; a++){
  url += '&WorkDay'+ a +'='+ encodeURI(data_view_372[a].field_273_raw.identifier);
  url += '&HoursPerDay'+ a +'='+ encodeURI(data_view_372[a].field_289_raw);
  url += '&HoursPerWeek'+ a +'=' + encodeURI(data_view_372[a].field_290_raw);
  url += '&StaffPerShift'+ a +'='+ encodeURI(data_view_372[a].field_278_raw);
  url += '&PeriodTotalHours'+ a +'='+ encodeURI(data_view_372[a].field_289_raw);
  url += '&WeeklyTotalHours'+ a +'='+ encodeURI(data_view_372[a].field_290_raw);
  console.log(url)
}

I've tried researching what it could be but so far my only real progress was to try .identifier or .field_273_raw[a].identifier but neither have worked.

I'm probably missing something really obvious because I'm a beginner so please don't destroy me.


r/JavaScriptHelp • • Oct 24 '17

making edit to my javascript coding for yahtzee game

1 Upvotes

This is my yahtzee game will someone look into this and tell me what mistakes I made and what I should do to fix it. Will you also let me know of a good website to use to test my codes at. Thank you for your time

var dices = new Array(0,0,0,0,0); var hold = new Array(0,0,0,0,0); var scoreArray = new Array(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1); var largeStraightArray = new Array(new Array(2,3,4,5,6),new Array(1,2,3,4,5)); var turn = 1; var timesThrown = 0; var scoreLock = true; var yahtzeeBonus = 0; var subtotal = new Array(0,0); var total = 0;

/*

  • Start declaration of all the functions */ function getDices(){ for (i=1;i<=5;i++) { $("#dice"+i).html(dices[i-1]); } } function throwDices(){ for (i=0;i<5;i++) { if(hold[i]===0) dices[i] = Math.floor(Math.random()*6)+1; } } function setHold(dsNummer){ knop = $("#hold"+dsNummer); value = knop.val(); i = parseInt(((dsNummer)-1),10);

    if(value=="Hold"){ hold[i]=1; $("#holdline"+dsNummer).css("background-color","#000"); knop.val("Unhold"); } else{ hold[i]=0; $("#holdline"+dsNummer).css("background-color","transparent"); knop.val("Hold"); } } function removeHoldLines(){ for(i=1;i<6;i++){ $("#holdline"+i).css("background-color","transparent"); $("#hold"+i).val("Hold"); } } function setScore(veld, score){ $("#"+veld).html(score); } function checkScore(eyes){ var score=0;

    for(i=0;i<6;i++){ if(dices[i]==eyes) score+=eyes; } return score; } function sortNumber(a,b){ return a-b; }

function checkXOfAKind(x){ var same = 1; dices.sort(sortNumber); var last = dices[0];

for(i=1; i<5; i++){ if(same==x) break; if(last===dices[i]) same++; else same=1;

  last = dices[i]; 

}

return same; } function threeOfAKind(){ var score=0; var same = checkXOfAKind(3);

if(same>=3) score=chance();

return score; } function fourOfAKind(){ var score=0; var same = checkXOfAKind(4);

if(same>=4) score=chance();

return score; } function fullHouse(){ var score=0; dices.sort(sortNumber); var count = 1; var found3 = false, found2 = false; for (i=1; i < 5;i++) { if (dices[i] == dices[i-1])
count++; else { if (count == 3) found3 = true; else if (count == 2) found2 = true; count=1; } } if (count == 3) found3 = true; else if (count == 2) found2 = true; if (found3 && found2) score=25;

return score; } function smallStraight(){ var score=0; var same = false; dices.sort(sortNumber);

var curSeqLen=1; var lastDie=dices[0];

// if the lowest number is a 4, or the highest number is a 3, it cannot be small straight 
if (dices[0] >= 4 || dices[4] <= 3) 
   same = false; 

for (i = 1; i < 5; i++) { 
    // the current die is one greater than the last one, the numbers are in sequence 
    if (dices[i] == lastDie+1){ 
        curSeqLen++; 
    } 
    else if (dices[i] == lastDie){} 
    // the consecutive dice are not in order, still might be a straight in there 
    else{ 
        curSeqLen=1; 
    } 
     
    if (curSeqLen >=4) 
       same = true; 
        
    lastDie = dices[i]; 
} 

if(same) score=30;

return score; } function largeStraight(){ var score=0; dices.sort(sortNumber);

var same = false; var hetzelfde2 = false;

for(i=0;i<5;i++){ if(largeStraightArray[0][i]==dices[i]){ same = true; } else { same = false; break; } } for(i=0;i<5;i++){ if(largeStraightArray[1][i]==dices[i]){ hetzelfde2 = true; } else { hetzelfde2 = false; break; } } if(same || hetzelfde2) score=40;

return score; } //check whole dicesArray against it's first element, every element has to be the same function checkYahtzee(){ for(i=0;i<5;i++){ if(dices[0]===dices[i]) same = true; else { same = false; break; } } if(same) return true; else return false; } function chance(){ var score=0; dices.forEach(function(x){score+=x;});

return score; } function getSubtotal(id){ var score = 0; var halt = 6; if(id===1){ id=6; halt=13; } for(i=id;i<halt;i++){ plusScore = (scoreArray[i] === -1) ? 0 : scoreArray[i]; }

return score; } function getTotal(){ return subtotal[0]+subtotal[1]+yahtzeeBonus; }

//start call functions when page is loaded $(function(){ $("#throwButton").click(function(){ scoreLock = false;

       if(timesThrown===0) 
           $(".holdButton").attr("disabled","disabled"); 
            
       if(timesThrown<3){ 
          $(".holdButton").removeAttr("disabled"); 
           throwDices(); 
           getDices(); 
            
           ++timesThrown; 
       } 
       if(timesThrown==3){ 
           //reset everything 
           $(this).attr("disabled","disabled"); 
           $(".holdButton").attr("disabled","disabled"); 
           hold = Array(0,0,0,0,0); 
           timesThrown = 0; 
           for (i=1;i<=5;i++) { 
               $("#hold"+i).val("Hold"); 
               $("#holdline"+i).css("background-color","transparent");
           }        
       } 
   }); 
    
   $(".holdButton").click(function(){ 
       i = $(this).attr("id"); 
       nr = i.substring(4); 
       //console.log(nr); 
       setHold(nr); 
   }); 
    
    
   /* 
    * When a scoreSquare is clicked then fill in teh score and and  the turn, reset timesThrown, hold array and hold buttons, if 13 turns  have passed then end the game' 
    */ 
   $(".scoreSquare").click(function(){ 
      if(turn==13){ 
       $("#throwButton").val('Game finished').attr("disabled","disabled");    
     } else { 
      $("#throwButton").removeAttr('disabled'); 
     } 
     if(checkYahtzee() && scoreArray[11]===50){ 
        yahtzeeBonus +=100; 
     } 
     timesThrown = 0; 
     $(".holdButton").attr("disabled","disabled"); 
       hold = Array(0,0,0,0,0); 
       removeHoldLines(); 
     id = parseInt(($(this).attr("id")),10); 
      
     if($(this).html()==='' && !scoreLock && scoreArray[id]===-1){ 
         
        //console.log(id); 
        switch(id){ 
           case 6: 
              scoreArray[6] = threeOfAKind(); 
              break; 
           case 7: 
              scoreArray[7] = fourOfAKind(); 
              break; 
           case 8: 
              scoreArray[8] = fullHouse(); 
              break; 
           case 9: 
              scoreArray[9] = smallStraight(); 
              break; 
           case 10: 
              scoreArray[10] = largeStraight(); 
              break; 
           case 11: 
              scoreArray[11] = yahtzee; 
              break; 
           case 12: 
              scoreArray[12] = chance(); 
              break; 
            
           default: 
              scoreArray[id] = checkScore(id+1); 
        } 
        $("#"+id).html(scoreArray[id]); 
        scoreLock = true; 
         
         
        subtotal[0] = getSubtotal(0); 
        $("#sixtyThree").html(subtotal[0]); 
        if(subtotal[0]>=63){ 
           $("#extra").html('35'); 
           subtotal[0] += 35; 
        } else { 
           $("#extra").html('0'); 
        } 
        $("#subtotal").html(subtotal[0]); 
        subtotal[1] = getSubtotal(1); 
        $("#yahtzeeBonus").html(yahtzeeBonus); 
        $("#subtotal2").html(subtotal[1]); 
        total = getTotal(); 
        $("#totalScore").html(total); 
         
         
         
        ++turn; 
     } 
  }); 

});


r/JavaScriptHelp • • Apr 21 '18

Help with TypesScript

1 Upvotes

I'm tying to create type definitions for this somewhat complex structure. Can someone help point me in the right direction? Seems to be pretty difficult to type create interfaces and type definitions for Immutable.js structures.

const DEFAULT_STATE = Map({
 board: fromJS([ 
        [c.RED, 0, 0, 0, c.BLUE],
        [c.RED, 0, 0, 0, c.BLUE],
        [c.RED_MASTER, 0, 0, 0, c.BLUE_MASTER],
        [c.RED, 0, 0, 0, c.BLUE],
        [c.RED, 0, 0, 0, c.BLUE]
    ]),
 swapCard: c.DEFAULT_CARD,
 redMoveCard1: c.DEFAULT_CARD,
 redMoveCard2: c.DEFAULT_CARD,
 blueMoveCard1: c.DEFAULT_CARD,
 blueMoveCard2: c.DEFAULT_CARD,
 activeSlotCoord: Map({
 x: 4,
 y: 4
    }),
 candidateCoords: List(),
 activePlayer: c.BLUE,
 moveHistory: List(),
 isChoosingMoveCard: false
});

Thanks in advance.


r/JavaScriptHelp • • Nov 29 '18

Setting up environment for javascript

1 Upvotes

Setting up environment with the right tools is the very first step towards great development, which i am trying to explain in this video -

https://www.youtube.com/watch?v=c_bdXjLOwL0

https://medium.com/…/environment-setup-for-javascript-62a03…

Please suggest me your thoughts, hope you will learn something new 😃.