How to convert HTML content to integers and compare values to display a winner?

I am using a dice roll API to populate the two <p> elements and display them above two characters. I would like to then take the number value of each of these so I can display a win/lose message. This code is not working. I have never really needed to use parseInt() before so I must not be using it correctly here.

const diceRoll1 = parseInt("#dice-roll1")
const diceRoll2 = parseInt("#dice-roll2")

function pickWinner() {
    if (diceRoll1 > diceRoll2) {
        $("h1").html("YOU WIN! You are the most adorable!")
    } else {
        $("h1").html("YOU LOSE! Noooo, so ugly! ):")
    }
};


<div class="roll-table">
                <p id="dice-roll1"></p>
                <p id="dice-roll2"></p>
</div>

What can I change here to compare the values of the two strings inside of #dice-roll1 and #dice-roll2?

React performance: developing recursive component JSON

i have developed a react component

  1. where JSON is array of object and each object could have another array which is same as parent array as prop. It can go till any depth.
  2. I have used a recursive component to render each component and by calling the same function recursive if the object has anychild/childs
  3. One of the specific requirement is whenever a node has to be checked/unchecked its Parent need to notified and Parent will change if all of its child are checked.

JSON data

[ 
{
   name: "name",
   checked: false
   child: [{
     name: "name",
     checked: false
    }]    
},

{
   name: "name"
   checked: false,
   child: [{
   name: "name",
   checked: false,
   child: [{
     name: "name",
     checked: false
    }]    
},
{
     name: "name",
     checked: false
    }]    
},
.....
]

App.jsx

const root = (JSONdata) => {
    const [data, setData] = useState(JSONdata)
    const updateData = (nodeToUpdate, positionOfNode) {
        //newData is different referance return by updateNodeAtSpeifiedDeepPosition function as we don't want to mutate data  set in state
        const newData = updateNodeAtSpeifiedDeepPosition(data, nodeToUpdate, positionOfNode);
        setData[newData]
    }
    return ( 
         <Tree data={JSONdata} updateData={updateData} />
    )
}

Tree.jsx

const Tree = (data) => {
    const [treeNode, setTreeNode] = useEffect(data)
    const renderTree = (nodes) => {
        <li onClick = { updateData) >
            If(treeNode.child) {
                <Tree data = {treeNode.child} />

            } </li>
    }

    return ( <ol >renderTree(treeNode) </ol>
    )
}

Its working but on each check or uncheck root is updated and all child are again re rendering as they have new reference.

Is there way to performance optimise it ?

Parse external json using Fetch API in jsfiddle [duplicate]

I hope to parse data from a public endpoint:
https://feeds.citibikenyc.com/stations/stations.json

Went I visit this URL, it populates data. When attempt to fetch in jsfiddle, I get a 200 “OK” status, but no data.

fetch("https://feeds.citibikenyc.com/stations/stations.json", { mode: "no-cors" })
  .then(response => {
    if (response.ok) {
      response.json().then(data => {
        console.log(data);
      });
    } else console.log('Error');
  })
  .catch(error =>
    console.log(error)
  );

https://jsfiddle.net/o60k1wgb/

I don’t appear to getting errors from the endpoint, so perhaps my fetch code is incorrect?

Using an imported type in JSDoc @typedef

I’m trying to reduce duplication in specifying my imported types as follows but I’m getting an error

/**
@typedef {import("../types/util")} util
@typedef {util.mapBehaviors} mapBehaviors
... lots of other typedefs based on util
*/
'util' only refers to a type, but is being used as a namespace here.

It’s weird because expanding the import explicitly works:

/**
@typedef {import("../types/util").mapBehaviors} mapBehaviors
... lots of other typedefs
*/

How can I use @typedef with an alias of an import?

How can I achieve something similar to a pointer to a string in javascript?

Is there a concept like a pointer to a string in javascript? Or how would this be done?

let s1 = "hi";
let s2 = "bye";

// I want to write my code like this [,].forEach();
// This is the bit where I want s1 and s2 in the [,] array to actually be pointers to a string
[s1,s2].forEach(s => {if(s.length < 3) s += "*";});

// I want console.log(s1) === "hi*"
// I want console.log(s2) === "bye" (unchanged)

ResizeObserver not being triggered on add & remove

I have a chat application which appends messages to the bottom, and when a limit is reached, it removes the oldest message. So it adds and removes a message at the same time. I’m using the ResizeObserver to detect changes in the chat area.

Hue.chat_resize_observer = new ResizeObserver(function () {
  Hue.goto_bottom()
})

Hue.chat_resize_observer.observe(Hue.el("#chat_area"))
Hue.chat_resize_observer.observe(Hue.el("#chat_area_parent"))

The issue I’m having is that the observer simply doesn’t get triggered on some messages, and my guess is because the message being inserted is the same height as the message that got removed. How could I get around this? Or maybe I could use another observer? I use the ResizeObserver because it takes into account all height changes, for instance on message added/removed or message height change. I’m thinking I could pair it with the MutationObserver or use setTimeout’s but those doesn’t seem like ideal solutions.

How can I redirect the parent page after OAuth 2 flow is complete?

My current flow is such:

  1. User clicks login to third party
  2. Upon grant, the third party redirects to configured redirect uri with code
  3. Forward code to backend to verify, etc.
  4. Return success/failure

My frontend is coded to close the popup when the login is successful, but the parent page still just remains the same – standard login page. The goal would be to redirect that page.

I’ve tried to add an event listener on the window object, but it’s not working.

...
  const loginWindow = window.open(oAuthUrl,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,height=450')
  loginWindow.onbeforeunload = function () {
    alert("new window closed");
  }
};

Is this possible?

how to pharse a json that return an arrey of object

so i did some backend changes to send 2 jsons from localhost.3001

it looks like this now :

  const response = await fetch(apiURL); // fetching the data from the api
  const apod = await response.json(); // parsing the data to json
const allData = [apod, lastSol()]; // creating an array with the data from the api and the last sol

  res.end(JSON.stringify(allData)); // return JSON response

and my react code looks like this

import React, { useState, useEffect ,} from "react";

const API = "http://localhost:3001/"


export default function NasaPhoto() {
      const [photoData, setPhotoData] = useState(null);

    useEffect(() => {
      fetchPhoto();
  
      async function fetchPhoto() {
        const res = await fetch(
          `${API}`
        );
        const data = await res.json();
        setPhotoData(data);
      }
      
    }, []);

  
    
  
    if (!photoData) return <div />;


  return (
    
   <h3> {photoData.title}</h3>
     
     )
     }

I’m having trouble pharing the new json when its inside an array

Invoking a function, by traversing an array of objects

I’m using prototypal inheritance in javascript. The parent class is an animal and an example of one of the child classes is a cheetah. All of the child classes have a function that is supposed to use the jQuery animate function to move the animals across the screen but I have to invoke it using a for loop in my init.js file. How do I do this?

This is the question:
Start the race – add a start button to your interface which makes sure that all
objects are lined up on one side of your screen and start moving across the screen at a
pace decided by their speed variables. NOTE: Remember you have access to a global
array of all the animals created in your application – (it’s defined in src/init.js ) so
you can loop through that array and tell each object to getReady . You’ll need to add a getReady method to each of your animal types. Note that not all animals have to get
ready in the exact same way but they must all move towards the start position when
getReady is invoked after the start button is clicked.

This is the init.js file

$(document).ready(function() {
var arr = window.animals = []; This is the array that all the animal objects are 
added to

$('.addAnimalButton').on('click', function(event) {
    /* This function sets up the click handlers for the create-animal
     * buttons on track.html. You should only need to make one small change to it.
     * As long as the "data-animal-maker-function-name" attribute of a
     * class="addAnimalButton" DOM node matches one of the names of the
     * maker functions available in the global scope, clicking that node
     * will call the function to make the animal.
     */

    /* animalMakerFunctionName is a string which must match
     * one of the animal maker functions available in global scope.
     * A new object of the given type will be created and added
     * to the stage.
     */
    var animalMakerFunctionName = $(this).data('animal-maker-function-name');

    // get the maker function for the kind of animal we're supposed to make
    var animalMakerFunction = window[animalMakerFunctionName];

    // make an animal with a random position

    var animal = new animalMakerFunction(
        $("body").height() * Math.random(),
        $("body").width() * Math.random(),
        Math.random() * 1000
    );

    $('body').append(animal.$node);
    window.animals.push(animal);

    for (var animalType in arr) {
        console.log(animalType instanceof Animal)
    }

    var get_readyBtn = document.querySelector(".get-ready");
    var body = document.querySelector("body");
    $(get_readyBtn).click(function() {
        animal.$node.css({
            'left': '10px',
            'width': '60px',
            'height': '60px'
        })
    })

});
});

This is the Animal/parent class

var Animal = function(top, left, timeBetweenSteps) {
this.$node = $('<span class="animal"></span>');
this.top = top;
this.left = left;
this.timeBetweenSteps = timeBetweenSteps;
this.step();
this.setPosition(this.top, this.left);
};

Animal.prototype.step = function() {
setTimeout(this.step.bind(this), this.timeBetweenSteps);
};

Animal.prototype.setPosition = function(top, left) {
this.position = {
    top: top,
    left: left
};
this.$node.css(this.position);
};

This is one of the subclasses, they’re all the same. This one is for a Leopard.

var Leopard = function(top, left, timeBetweenSteps) {
Animal.call(this, top, left, timeBetweenSteps);
}

Leopard.prototype = Object.create(Animal.prototype);

Leopard.prototype.constructor = Leopard;

Leopard.prototype.step = function() {
Animal.prototype.step.call(this);
this.$node.css('background-color', "orange"); //styles animal/div
}

var trackWidth = $(window).width(); //Used to get the width of the window


var raceTime = Math.floor((Math.random() * 5000) + 1) //Created to give each animal a 
new 
racing time, everytime the race is run

var startBtn = document.querySelector(".startRace"); //This function is supposed to 
move. This is the function that must be called using the loop in the init.js file
once the start button is clicked the animal moves the width of the window
$(startBtn).click(function() {
animal.$node.animate({
    left: trackWidth,
}, raceTime)
})

How can i append an element to the end of a list and prevent it from moving each time a new list item is created

<!-- Created by Ishak -->

how can i stop the outputted color from appending to the child element? i want the chosen colour to be displayed on the list item after save is cliked but the colour moves each time a new list item is added, ive tried duplicating the element & list item if it already exists but i think im just making it more complicated…

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>



</head>

<body>


<div id="myDIV" class="header">
</div>



<ul id="myUL">

  <li>Hit the gym</li>

  <li class="checked">Pay bills</li>

  <li>Meet George</li>

  <li>Buy eggs</li>

  <li>Read a book</li>

  <li>Organize office</li>

</ul>



 <div id="box" class="box">
       <header class="boxheader"></header>
       
           <button class="cancel">Cancel</button>
        <button id="save"  onclick="functionA();
         functionB(); 
         
         
         
         
         "  class="save" type="submit">Save</button>
                  
           </header>
       <textarea name="td" id="myInput" class="inputarea" type="text"  placeholder="Type something..."></textarea>
       <div onclick="setallbtnflag();"  id="allbtn" class="allbuttons">
           <button id="redbtn" class="btnred" onclick="setredbtnflag();"></button>
 
       </div>
       </div>
       
       
       <button id="add" class="add" 
></button>

<div tagName="red" id="redbtnclone"></div>

<div id="grnbtnclone" 
class="grnbtnclone"></div>


<div id="bluebtnclone" class="bluebtnclone"></div>

<div id="yellowbtnclone" class="yellowbtnclone"></div>

<div id="orangebtnclone" class="orangebtnclone"></div>


<script>

// initialize red btn flag

var redbtnflag = false;
var bluebtnflag = false;
var grnbtnflag = false;
var allbtnflag = false;
var yellowbtnflag = false;
var orangebtnflag = false;
var temp = 0;
 var j = document.getElementById("redbtnclone");
 
  
    
// Create a "close" button and append it to each list item

var myNodelist = document.getElementsByTagName("LI");

var i;

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

  var span = document.createElement("SPAN");

  var txt = document.createTextNode("u00D7");

  span.className = "close";

  span.appendChild(txt);

  myNodelist[i].appendChild(span);

}


// Click on a close button to hide the current list item

var close = document.getElementsByClassName("close");

var i;

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

  close[i].onclick = function() {

    var div = this.parentElement;

    div.style.display = "none";

  }

}


// Add a "checked" symbol when clicking on a list item

var list = document.querySelector('ul');

list.addEventListener('click', function(ev) {

  if (ev.target.tagName === 'LI') {

    ev.target.classList.toggle('checked');

  }

}, false);


// Create a new list item when clicking on the "Add" button



function functionA() {

 

 var li = document.createElement("li");  
  
li.appendChild(j);

        


  var inputValue = document.getElementById("myInput").value;

  var t = document.createTextNode(inputValue);

  li.appendChild(t);



 if(inputValue.length < 1) {


     alert("You must write something!");
    
} else if (redbtnflag == false) {

 
  
 alert("pls choose a colour!");
  
  return false;

 
 
  



    // code that will execute if all above conditions are false
  


   
  } else {





    document.getElementById("myUL").appendChild(li);

  }
  temp = document.getElementById("myInput").value
  document.getElementById("myInput").value = "";


  var span = document.createElement("SPAN");

  var txt = document.createTextNode("u00D7");

  span.className = "close";

  span.appendChild(txt);

  li.appendChild(span);


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

    close[i].onclick = function() {

      var div = this.parentElement;

      div.style.display = "none";


    }
  }
}



</script>

    <span id="vh" class="output"></span>
       <script type="text/javascript">

//* when the red button is clicked, it will be displayed on the next page beside a list item after save is clicked

function setredbtnflag() {redbtnflag = true;}
function setgrnbtnflag() {grnbtnflag = true;}
function setallbtnflag() {allbtnflag = true;}
function setbluebtnflag() {bluebtnflag = true;}
function setyellowbtnflag() {yellowbtnflag = true;}
function setorangebtnflag() {orangebtnflag = true;}
  


  //when add button is clicked, the box will hide or show
  
    $('#add').click(function(){
   $(".box").toggle();
});

// only toggle box when both the colour and input have been clicked
 function functionB(){

 if (temp.length < 1 && redbtnflag == true) {
    
 redbtnflag = true
   
 } else {    

if (temp.length > 0 && redbtnflag == true) {


redbtnflag = false

  // var li = document.createElement("li");

     

 
j.className = "redbtnclon";
  
  
  
 //removes outline when buttonflag = false
 document.getElementById("redbtn").style.outline = "";     
   
   document.getElementById("redbtn").style.border = "";
     
 } 
}

 }    
 


    </script>

<style>
/* Created by Ishak */



body {
  margin: 0;

min-width: 250px;

}


/* Include the padding and border in an element's total width and height */

* {
box-sizing: border-box;

}


/* Remove margins and padding from the list */

ul {
margin: 0;
padding: 0;

}


/* Style the list items */

ul li {
cursor: pointer;

position: relative;

padding: 12px 8px 12px 40px;

list-style-type: none;

background: white;

font-size: 18px;

transition: 0.2s;

margin-left:10px;

margin-right:10px;

box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;

border-radius:3px;

margin-bottom:10px;

**

/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;

-ms-user-select: none;

user-select: none;

}


/* Set all odd list items to a different color (zebra-stripes) */

ul li:nth-child(odd) {

background: #f9f9f9;

}



/* When clicked on, add a background color and strike out text */

ul li.checked {

background: #888;

color: #fff;

text-decoration: line-through;

}


/* Add a &quot;checked&quot; mark when clicked on */

ul li.checked::before {

content: '';

position: absolute;

border-color: #fff;

border-style: solid;

border-width: 0 2px 2px 0;

top: 10px;

left: 16px;

transform: rotate(45deg);

height: 15px;

width: 7px;

}


/* Style the close button */

.close {

position: absolute;

right: 0;

top: 0;

padding: 12px 16px 12px 16px;

}


.close:hover {

background-color: #f44336;

color: white;

}


/* Style the header */

.header {

background-color: green;

width:100%;

height:40px;

color: white;

text-align: center;

}


/* Clear floats after the header */

.header:after {

content: &quot;&quot;;

display: table;

clear: both;

}


/* Style the input */

input {

margin: 0;

border: none;

border-radius: 0;

width: 75%;

padding: 10px;

float: left;

font-size: 16px;

}

.box{
    width:95%;
    height:360px;
    border:none;
    box-shadow: rgba(0, 0, 0, 0.09) 0px 2px 1px, rgba(0, 0, 0, 0.09) 0px 4px 2px, rgba(0, 0, 0, 0.09) 0px 8px 4px, rgba(0, 0, 0, 0.09) 0px 16px 8px, rgba(0, 0, 0, 0.09) 0px 32px 16px;
    
    bottom:130px;
    position:absolute;
    left:9px;
    background-color:#fff;
    display:none;
    
    
    
    
}

.btnred{
    width:35px;
    height:35px;
    background-color:#ff3300;
    border-style:double;
    border-radius:100%;
    margin-right:10px;
    border-color:#f06c6c;
    
}
.btngreen{
    width:35px;
    height:35px;
    background-color:#66cc33;
    border-radius:100%;
    margin-right:10px;
    border-style:double;
    border-color:#3c8556;
    
    
    
}
.btnblue{
    width:35px;
    height:35px;
    background-color:#409ade;
    border-radius:100%;
    margin-right:10px;
     border-style:double;
     border-color:#0554ff;
}
.btnyellow{
    width:35px;
    height:35px;
    background-color:#e3c800;
    border-radius:100%;
    margin-right:10px;
     border-style:double;
     border-color:#e3cb19;
}
.btnorange{
    width:35px;
    height:35px;
    background-color:#ff9933;
    border-radius:100%;
    margin-right:10px;
     border-style:double;
     border-color:#c77e08;
    
}
.allbuttons{
position:absolute ;
     padding:20px;
     width:90%;
     height:80px;
     right:1%;
     bottom:20px;
     
     
     
}
.boxheader{
    background-color:white;
    width:100%;
    height:50px;
    box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
    
    
}

.save{
    position:absolute;
    background-color:transparent;
    border:none;
    color:#1278b8;
    top:20px;
    left:80%;
}

.cancel{
    position:absolute;
    background-color:transparent;
    border:none;
    color:#1278b8;
    top:20px;
    right:80%;
}

.inputarea{
    width:100%;
    height:50%;
    border:none;
    padding:10px;
    margin-top:5px;
    border:1px solid black;
    
}
.add{
     background-color:green;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    border-radius:100%;
    width:60px;
    height:60px;
    margin-left:270px;
    top:430px;
    position:fixed;
}

output color

.redbtnclon{
    width:35px;
    height:35px;
    background-color:#ff3300;    
    border-radius:100%;    
    border-color:#f06c6c;
}

.grnbtnclon{
     width:35px;
    height:35px;
    background-color:#66cc33;    
    border-radius:100%;    
}
</style>


</body>


</html>

Typescript – How to check if generic type is undefined

I have a class with a generic type:

export abstract class AClass<TType extends BClass | undefined = undefined> {
    protected prop: TType;

    public hasProp(): boolean {
        return typeof this.prop === 'undefined';
    }

    public isPropable(): boolean {
        // ?
    }
}

And I need to check if TType is undefined or BClass. Does anyone know how to do that? Is it even possible?

PS.: I do not need to check if props is undefined… I need to check if props was assigned a type from the sub class.

Is not-returned code and content available for public in the source code?

I am new to nextjs and webdev. I been following a couple of tutorials but I still have a doubt.
Lets say I have this page:
import Link from ‘next/link’
import Layout from ‘../../components/layout’
import { useRouter } from “next/router”;

// /pages/test/load.js

import Link from 'next/link'
import Layout from '../../components/layout'
import { useRouter } from "next/router";


export default function TestLoad() {
    const router = useRouter();
    const query = router.query;
    console.log(query.info)
    // I don't want to show any of this code here, or the return in case queri.info != true.
    if (query.info == 'true') {
        console.log('TRUE RETURN')
        return (
            <Layout>
                <h1>First Post</h1>
                <h2>
                    <Link href="/">
                        <a>Back to home</a>
                    </Link>
                </h2>
                <p>Some hidden content that I don't want to show to all the users.</p>
                <p>Blah</p>
                // Images and more stuff

            </Layout>
        )
    } else {
        return (
            <>
                <h1>Nothing to show</h1>
                    <Link href="/">
                        <a>Back to home</a>
                    </Link>
            </>
        )
      }

}

If I deploy this code with Vercel for example, and try access to http://<some-url>/test/load?info=false is the code/info for query.info == 'true' available?

Of course in this particular case anyone can just try to access to http://<some-url>/test/load?info=true and view the content.

My idea is then try to wrap up the true/false logic into getStaticProps.

My ultimate idea is to render a different html code depending on the props passed by getStaticProps.

Thanks!

How to reset jquery/javascript filter

I have a list of div items which I am filtering/sorting via JS.
Each item animates in to place – in this case, scales up to its final size.

When I filter the items via buttons, anything already on screen DOES NOT play this animation again.

How can I RESET the filter every time a new button is selected, so EVERY item ALWAYS animates in to place no matter what is being filtered and whether or not it is currently on screen?

WORKING CODEPEN HERE

<div class="filter-list">
  <button class="active btn" id="all">All</button>
  <button class="btn" id="oranges">Oranges</button>
  <button class="btn" id="apples">Apples</button>
  <button class="btn" id="bananas">Bananas</button>
</div>
<div class="grid">
  <div class="artist-img item oranges">oranges</div>
  <div class="artist-img item apples">apples</div>
  <div class="artist-img item bananas">oranges</div>
</div>

JS

 var $items = $(".item");
  var $btns = $(".btn").click(function () {
    if (this.id == "all") {
      $items.show();
    } else {
      var $el = $("." + this.id).show();
      $items.not($el).hide();
    }
    $btns.removeClass("active");
    $(this).addClass("active");
  });

CSS

      @keyframes entrance {
    0% {
      transform: scale(0.5);
    }
    100% {
      transform: scale(1);
    }
  }
  .grid > div {
    padding: 1rem;
    position: relative;
    animation-duration: 0.5s;
    animation-name: entrance;
  }