Project help: $ is not defined (JavaScript) (Replit IDE) [duplicate]

I am currently using the online version of the Replit IDE (I don’t know if being online is a problem). In my project, I have this block of code; however when I run it, it states that $ is not defined. I ask if this is a problem related to how I use run the different files, as all I do is declare ‘node public/main.js’ rather than several different files. If anyone has experience Replit, it would be appreciated if you could guide me through the IDE. Thank you in advance 🙂 (sorry if I reply slowly).

Here is the block of code I’m having trouble with:

// Page Elements
const $input = $('#city');
const $submit = $('#button');
const $destination = $('#destination');
const $container = $('.container');
const $venueDivs = [$("#venue1"), $("#venue2"), $("#venue3"), $("#venue4")];
const $weatherDiv = $("#weather1");

How to remove duplicates from an array object in javascript

I want to remove duplicates, and to left only unique items in a sub-object array.

function display_message() {
  let filteredSerivces = 
  [
    {
        "ServiceTypeId": 805,
        "ServiceTypeName": "Custom Services 1",
        "GroupedServices": [
            {
                "Id": 5247,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A2",
                "Name": "A1",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3683
            },
            {
                "Id": 5254,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A2",
                "Name": "A2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3683
            },
            {
                "Id": 5254,
                "ServiceTypeId": 805,
                "ServiceName": "Some service A6",
                "Name": "A2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 4,
                "EmployeeId": 3684
            }
        ],
        "Order": 4
    },
    {
        "ServiceTypeId": 804,
        "ServiceTypeName": "Custom Services 2",
        "GroupedServices": [
            {
                "Id": 5246,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B1",
                "Name": "B1",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3696
            },
            {
                "Id": 5248,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B2",
                "Name": "B2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3700
            },
        {
                "Id": 5248,
                "ServiceTypeId": 804,
                "ServiceName": "Some service B2",
                "Name": "B2",
                "Duration": 30,
                "DurationForClient": 30,
                "Order": 5,
                "EmployeeId": 3683
            }
        ],
        "Order": 5
    }
]


//TASK: The goal is to remove duplicate object (leave just one) from an array object GroupedServices
// the key for this distinction is "Id".
// example: 
//            {
//                "Id": 5254,
//                "ServiceTypeId": 805,
//                "ServiceName": "Some service A2",
//                "Name": "A2",
//                "Duration": 30,
//                "DurationForClient": 30,
//                "Order": 4,
//                "EmployeeId": 3683
//            },
//            {
//                "Id": 5254,
//                "ServiceTypeId": 805,
//                "ServiceName": "Some service A6",
//                "Name": "A2",
//                "Duration": 30,
//                "DurationForClient": 30,
//                "Order": 4,
//                "EmployeeId": 3684
//           }
//=> in this case we need to remove second object, because it has same Id with a first object (Id: 5254) 

//WHAT I HAVE BEEN TRIED:
var uniqueGroupedServices = Array.from(filteredSerivces.GroupedServices().reduce((map, obj) => map.set(obj.Id, obj), new Map()).values());



    
    
  console.log(uniqueGroupedServices);

}
<input type="button" onclick="display_message();" value="click"/>

But obviously my code doesn’t work. I guess I need to iterate for each in this main array to approach to GroupedServices but I don’t know how. Also, how can I remove second occasion of same object (same Id)?

Error package vscode extension with vsce: invalid relative path

  • npm: 8.1.0
  • vsce: 2.5.3

I have a npm package (colibri) in a local folder and a VSCode extension (vscode-teroshdl) in other folder. colibri is a dependency of vscode-teroshdl:

    "dependencies": {
        "colibri": "file:../colibri"
    },

When I try to package the VSCode extension:

cd colibri
npm install
cd ../vscode-terosHDL
npm install
vsce package

It fails with the error:

 ERROR  invalid relative path: extension/../colibri/node_modules/cli-progress/CHANGES.md

String parameter passed in javascript does not work

Just trying to understand whats going on here. Obviously a quirk of javascript, hoping someone can help explain.

HTML:

<input type="file" asp-for="TitleImageUrl" value="@_loc[Model.AddTitleImageButton]" onchange="preview('CardDynamicImage')" />

<img class="card-img-top embed-responsive-item" id="CardDynamicImage" src="@Model.CardTitleImage" onerror="this.src=''">

JAVASCRIPT THAT WORKS:

function preview(elementId) {
<!--The id of the element is hard coded directly. Ignore the value passed in.-->
            CardDynamicImage.src = URL.createObjectURL(event.target.files[0]);
    }
}

JAVASCRIPT THAT DOES NOT WORK: Why?

function preview(elementId) {
<!--Trying to pass in the id of the element does not work.-->
            elementId.src = URL.createObjectURL(event.target.files[0]);
}

fixed side scrollbar for case study

This is my first post. I am new to code and am trying to code my case studies for my portfolio. I want to include a “scroll bar” to work as a sort of timeline on the left side that is “fixed” so as you scroll down the page it fills up. This website has a something close to what I am looking to accomplish. they have a small red “scroll bar” on the left side.

https://edesigninteractive.com/

Vanilla js class factory

I was trying to implement some kind of factory that create a class definition in the run time,I figure this work my code look like this


 function JsClassFactory() {
    this.X = class {

    };
    this.addMethod = (name, def) => {
        let Y = class extends this.X {
            constructor() {
                super()
                this[name] = def
            }
        }
        this.X = Y
        return this;
    }

    this.addAttribute = (name, def) => {
        this.addMethod(name, def)
    }

    this.getClass = function () {
        return this.X
    };
}


(function () {
    const cf = new JsClassFactory()
    cf.addAttribute('age', 35)
    cf.addAttribute('name', 'chehimi')

    cf.addMethod('myName', function () {
        console.log(' i am %s', this.name)
    })
    cf.addMethod('myAge', function () {
        console.log('my age is', this.age)
    })
    let z = new (cf.getClass())
    z.myName();
    z.myAge()
    cf.addAttribute('name', 'ali')
    cf.addAttribute('age', 15)
    let t = new (cf.getClass())
    t.myName();
    t.myAge()
})()

i am asking if there is a better a way to implement this feature?
or a better work arround,

handling contact form error animation – HTML/CSS/JS

I have the following code:

//Contact Form Redirection
var form = document.getElementById("my-form");

async function handleSubmit(event) {
  event.preventDefault();
  var data = new FormData(event.target);
  fetch(event.target.action, {
    method: form.method,
    body: data,
    headers: {
      'Accept': 'application/json'
    }
  }).finally(() => {
    window.location = "thankyou.html";
  });
}
myform.firstname.oninvalid = badEntrie
myform.lastname.oninvalid = badEntrie
myform.email.oninvalid = badEntrie
myform.subject.oninvalid = badEntrie

function badEntrie({
  target
}) {
  target.classList.add('shakingErr')
  setTimeout(() => {
    target.classList.remove('shakingErr')
  }, 820)
}
form.addEventListener("submit", handleSubmit)

//Contact Form Error Animation 
document.querySelector('form').addEventListener('submit', function(e) {
  var isValid = true;
  this.querySelectorAll('input, textarea').forEach(function(f) {
    if (!f.checkValidity()) {
      isValid = false;
      f.style.borderColor = "red";
      f.style.animation = "shake 0.82s forwards";
      setTimeout(function() {
        f.style.animation = "unset";
      }, 820);
    } else {
      f.style.borderColor = "initial";
    }
  })
  if (!isValid) {
    e.preventDefault();
  }
})
/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type=submit]:hover {
  opacity: 0.9;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

.shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="https://formspree.io/f/xdobkgny" id="my-form" method="POST">
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>
            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

There’s only a slight problem I’m facing. Basically, when you click the submit button without entering anything in the form, you will see that there is both a shake animation and a message that is being displayed.

I would like the message to be removed and only have the shake animation on all the input fields.

Also, the shake animation is not working on lastname field for some reason. Any suggestions on how I can fix this?

Add column to dynamically generated table? Or have content dynamically generated from second column of row?

I am trying to create a dynamic “availability” schedular. I show one week at a time, defaults to the current week, with buttons to move back and forth, while the first column will show resources (names, rooms etc). I am new-ish to Javascript. I was able to populate the calendar dates starting with the current week, and now have the Previous/Next buttons working. But I can’t quite figure out how to add a column.
Here is what I currently have:
Dynamically generated row, shows one week at a time

Here’s kind of what I’m aiming for:
Dynamically add column of names

A link to the current code is here: https://jsfiddle.net/surista/h0uvsdpz/1/

I’ve tried to dynamically add a column to this, but can’t seem to get it. I then tried to add the column in the HTML and then have the dates auto-populate from the -second- column, but this hasn’t worked either.

This is my current Javascript code:

function showDays(startDay){
  let start = moment(startDay);
  window.SelectedSunday = start; // save it for future use

  let table = document.getElementById("calendar");
  tbl_body = document.getElementById("calendar-body"); // body of the calendar

  // display month and year in table header
  let monthAndYear = document.getElementById("monthAndYear");
  monthAndYear.innerHTML = start.format('MMM YYYY');

  // always only show one row
  if (table.rows.length == 2) {
    table.deleteRow(1);
  }

  let row = table.insertRow(1);

  day = start.format('DD'); // Get day
  let cell = row.insertCell(0);
  cell.innerHTML = day;

  for(let i = 1; i < 7; i++){
    // iterate through days of week
    start.add(1, 'days');
    day = start.format('DD'); // Get day
    let cell = row.insertCell(i);
    cell.innerHTML = day;
  }
}

function nextWeek() {
  window.SelectedSunday.add(1, 'days');
  showDays(window.SelectedSunday);
}

function previousWeek() {
  window.SelectedSunday.add(-13, 'days');
  showDays(window.SelectedSunday);
}

window.SelectedSunday = null;
let currentSunday = moment().startOf('week');

showDays(currentSunday);

Eloquent Javascript Chapter 14 Exercise 2 – Elements by Tag Name – Why Isn’t Recursion Working?

In Chapter 14 of Eloquent Javascript (3rd Edition), the second exercise is to create a function byTagName that works like document.getElementsByTagName. The function should take a node and return all child elements with a given tag name.

My function should take a node and a tag name, then put each of the node’s children in a holding array if the child matches the tag name. Then the function tries to concatenate the holding array with the result of calling itself recursively on each of the node’s children. Finally, it returns the holding array.

My function isn’t recursing correctly. Can anyone tell me why?

<h1>Heading with a <span>span</span> element.</h1>
<p>A paragraph with <span>one</span>, <span>two</span>
  spans.</p>

<script>

//THE FUNCTION THAT ISN'T WORKING:

function byTagName (node, tagName) {
    let elements = [];
    let tag = tagName.toUpperCase();
    for (let child of node.children) {
        if ( tag == child.nodeName ) {
            elements.push(child);
        }
        elements.concat(byTagName(child,tagName));
        //^This part isn't working. 
        //I think the recursive call to byTagName is returning nothing no matter what.
    }
    return elements;
}


  console.log(byTagName(document.body, "h1").length);
  // → Correctly logs "1"
  console.log(byTagName(document.body, "span").length);
  // → Should log 3, but logs "0"
  let para = document.querySelector("p");
  console.log(byTagName(para, "span").length);
  // → Correctly logs "2"
</script>

How to unmounting a component properly in React Canvas? Its working but gives me a ton of errors

The code is working how I want. The balls appear and then the seeds appear after disappearing the balls. Yet, if you check the console, there is like 1000 errors, when the disappearance of the ball happens.

I have tried to solve it two ways. Both have failed

  const ballsSetter = () =>{
    setBalls(true)
  }

  const seedsSetter = () =>{
    setBalls(false)
    setSeeds(true)
  }

  const timingOfLevel2 = () => {
    setTimeout(ballsSetter, 5000);
    setTimeout(seedsSetter, 15000);
    setTimeout(() => {console.log("the end")},20000);
  }

useEffect(()=>{
  timingOfLevel2()
},[])
  

const ifAttempt = () =>{
  if(balls){
    return  <>
    <EnemiesBallsReturn 
    enemyBall1Ref = {enemyBall1Ref}
    />
    </>
  } else if (seeds){
    return <>
     <EnemiesSeedsReturn 
    enemySeed1Ref = {enemySeed1Ref}
   /> 
    </>
  } 
}

and returning the ifAttempt function in the return

or

>  {balls?   <EnemiesBallsReturn enemyBall1Ref = {enemyBall1Ref}/>:null}
   {seeds? <EnemiesSeedsReturn enemySeed1Ref = {enemySeed1Ref}/>:null}

either way when the state of balls or seeds is false, it is returning null. and I’m not seeing anything but when it switches to seed it throws this error.
basically stating it cant draw an undefined
I understand that but it shouldn’t be checking for anything bc its unmounted/null? I’m confused any help or direction would be greatly appreciated

how can i make url shortener api in express.js?

I’m doing a link shortener. The link shortener works very well but now I’m trying to do API for it. The problem is that if I pass the URL argument in the get URL it’s not working. I tried a lot of things but it’s not working. When I do like http://localhost:3500/api/create/google.com it works but when I do http://localhost:3500/api/create/https://google.com it’s not working because of the https://. These are the last 3 inputs via my API that failed: http://https:google.com, google.com, http://
I’m using express and mongoose. Here’s my code:

app.get('/api/create/:shortUrl(*)', async (req, res, next) => {
if (req.params.shortUrl.includes("https://") || req.params.shortUrl.includes("http://") || req.params.shortUrl.includes("/")) {
    req.params.shortUrl = req.params.shortUrl.replace("https://", "").replace("http://", "").replace("/", "")
}
if (req.params.shortUrl == "") {
    res.send("invalid URL")
}
    await shorturl.create({full: `http://${req.params.shortUrl}`})
    const shortUrls = await shorturl.find().sort({_id: -1}).limit(-1)
    const latest = shortUrls[0]
    res.send("https://p33t.link/" + latest.short)

});