javascript event.target.match or event.target.closest does not work

In my project, I have a cart icon that when mouse clicks on the icon needs to unfold a dropdown list with two link options. When the mouse is clicking on somewhere else or in a blank space the dropdown list needs to dissapear.

Here is a snippet of my html template which shows upon clicking on the element with id shoppingCartIcon the javascript function cartIconClicked() is called.

<div class="container-fluid sticky-top" id="takeawayHeaderCartContainer">
    <div class="row">
        <div class="col-11" id="cartIconContent">
            <i class="fa dropbtn" id="shoppingCartIcon" onclick="cartIconClicked()">&#xf07a;</i> <!--this code codes for the shopping cart icon-->
            <span class='badge badge-warning' id='lblCartCount'> 
                {% if sessionValidity %}
                    {{totalCartItems}}
                {% else %}
                0 
                {% endif %}
            </span>
            <div id="myDropdown" class="dropdown-content">
                <a href="#">Option 1</a>
                <a href="#">Option 2</a>
            </div>
        </div>        
    </div>
</div>

In my css file I have this snippet.

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

#takeawayHeaderCartContainer {
  justify-content: flex-end;
}

#shoppingCartIcon {
  font-size: 2rem;
  float: right;
  color: blue;
}

#lblCartCount {
    font-size: 16px;
    background: #ff0000;
    color: #fff;
    padding: 0 5px;
    vertical-align: top;
    float: right;
}

.badge {
  padding-left: 9px;
  padding-right: 9px;
  -webkit-border-radius: 9px;
  -moz-border-radius: 9px;
  border-radius: 9px;
}
.label-warning[href],
.badge-warning[href] {
  background-color: #c67605;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

I am not sure if I fully graps the last line .show {display:block;} in above css style because we do not have a show class in the html template to begin with. I therefore guess it is meant for the javascript – see below. I got this script from this tutorial. Can someone explain to me what this line in particular classList.toggle("show") does? I guess it switches the class “show” on and off for the dropdown list? My biggest problem is though, this line if (!event.target.closest('.fa dropbtn')). This line gets fired every time both when I click on the cart icon and somewhere else, which is NOT the intension. It should get fired if the user clicks somewhere else than the cart icon, in which case a check will be performed to see if the drop down list has the “show” on and if so it should be removed, leading to drop down list dissapearing – see the link tutorial for full description.

function cartIconClicked() {
    document.getElementById("myDropdown").classList.toggle("show");
  }
  
  // Close the dropdown menu if the user clicks outside of it
  window.onclick = function(event) {
      console.log(event.target);
      if (!event.target.closest('.fa dropbtn')) 
      {
        console.log("we are here");
    }
} 

Why is URL.creatObjectURL(blob) giving a cross-origin frame error in NodeJS/React application

I have never had this happen before and am not sure why it’s happening.
I have a component written to display PDF files in an iFrame as part of a larger application. I am retrieving a BLOB stream from the server and attempting to create a URL for it to display in the iFrame but it keeps giving me a cross-origin error, which I though would not be possible since it is creating the URL out of data.

Here is my entire component:

import React, { useState, useEffect } from 'react'
import IFrameComponent from '../Elements/IFrameComponent';

const PDFPages = (props) => {
    let [file, setFile] = useState(null)
    let [notFound, show404]=useState(false)
    useEffect(() => {
        let id=props.site?.componentFile;
        fetch(`${process.env.REACT_APP_HOST}/documents/GetPDF`,
            {
                method: 'POST'
                , headers: {
                    'Content-Type': 'application/json'
                }
                , credentials: 'include'
                , body: JSON.stringify({file:id})
            })
            
            .then(async response => {
                let blob;
                try{
                    blob=await response.blob(); // <--- this functions correctly
                }
                catch(ex){
                    let b64=await response.json()
                    blob=Buffer.from(b64.fileData,'base64')
                }
                //Create a Blob from the PDF Stream
                //Build a URL from the file
                const str=`data:application/pdf;base64,${b64.fileData}`
                const url=URL.createObjectURL(blob) //<---  ERROR IS THROWN HERE
                setFile(url);
            })
            .catch(error => {
                show404(true)
            });
    }, []);

    if(!notFound){
    return <IFrameComponent src={file} title=''>
        Please enable iFrames in your browser for this page to function correctly        
    </IFrameComponent>
    }
    else {
        return (
            <>
            <h3> File {file} could not be found on server</h3>
            </>
        )
    }
}

export default PDFPages;

For completeness here is the GetPDF function from the server which is sending the file.

router.post('/GetPDF', async (req, res, next) => {
    const props = req.body;
    let fileName = props.file;
    try {
        fileName = fileName.replace(/%20/g, " ");
        let options = {};
        if (props.base64) options.encoding = 'base64'
        let data = await dataQuery.loadFile(`./data/documentation/${fileName}`, options);
        if (!props.base64) {
            res.attachment = "filename=" + fileName
            res.contentType = 'application/pdf'
            res.send(data);
        }
        else{
            res.send({fileData:data, fileName: fileName});
        }
    }
    catch (ex) {
        res.send({ error: true })
    }
});

I have done very little work in node sending files but am positive my client code is good. Where am I going wrong here?

Emulating lisp list operations in js

What would be the proper way to define the cons, car, and cdr functions if we were to use javascript and functional programming? So far I have:

// CAR = λxy.x
// CDR = λxy.y
// CONS = λxy => ?
const car = a => b => a;
const cdr = a => b => b;
const cons = f => a => b;

let pair = cons(3)(4);
console.log(pair(car));
console.log(pair(cdr));

But my issue is pair(car) seems like an odd way to invoke the function. It seems like car(pair) seems like a better way but I’m not sure how to save the pair so it can be passed like that. How would that be done?

how the cube will stand on the floor in a parcur game

Can you help with the code?
I’m creating a parkour game and everything went well but I got stuck on it:
as the cube will stand on the floor.
Here is my js code:

      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      //Налаштування


      var width = canvas.width;
      var height = canvas.height;


      var gameOver = function () {
         clearInterval(intervalId);
         ctx.font = "60px Caurier";
         ctx.textAlign = "cener";
         ctx.textBaseline = "middle";
         ctxfillText("GAME OVER", width / 2, height / 2);
      };


      var cicle = function (x, y, radius, fillCircle) {
         ctx.beginPath();
         ctx.arc(x, y, radius, 0, Math.PI * 2, false);
         if (fillCircle) {
            ctx.fill();
         } else {
            ctx.stroke();
         }
      };


      //Людина
      //намалювати
      function Draw() {
         this.x = 10;
         this.y = 10;

      }
      Draw.prototype.draw = function () {
         ctx.beginPath();
         ctx.moveTo(this.x, this.y);
         ctx.lineTo(this.x + 50, this.y);
         ctx.lineTo(this.x + 50, this.y + 50);
         ctx.lineTo(this.x, this.y + 50);
         ctx.lineTo(this.x, this.y);
         ctx.fill();
      }
      Draw.prototype.move = function () {
         if (this.x < 0) {
            this.x = 0;
         } else if (this.x > 1250) {
            this.x = 1250;
         }
         if (this.y < 0) {
            this.y = 0;
         } else if (this.y > 450) {
            this.y = 450;
         }

         while (this.y < 450) {
            this.y++;
         }
      }
      Draw.prototype.setDirection = function (direction) {
         if (direction === "left") {
            this.x = this.x - 10;
         } else if (direction === "right") {
            this.x = this.x + 10;
         } else if (direction === "up") {
            this.y = this.y - 150;
         }
      }
      var person = new Draw;

      var keyActions = {
         37: "left",
         38: "up",
         39: "right"
      };
      $("body").keydown(function (event) {
         var direction = keyActions[event.keyCode];
         person.setDirection(direction);
      });

      setInterval(function () {
         ctx.clearRect(0, 0, 1300, 500);
         person.draw();
         person.move();
         //карта
         var floor = ctx.strokeStyle = "LimeGreen"; ctx.lineWidth = 4; ctx.strokeRect(0, 312, 1300, 362);
      }, 30);

I tried a lot but it didn’t work out.
For example, I tried this:
first the code checks whether the cube and the floor are in the same coordinates, if so it reflects, if not, then no.

JavaScript filter array of objects on multiple values dynamically

Hi Everyone i wanted to filter an array based on the array that I receive which contains column name condition and the value so let me just how the two array looks.
So this is what the array looks like from which I want to filter

[
            {
                "unique_id": 35264,
                "flash_candidate_id": 0,
                "first_name": "YAP  CHIN SIEN",
                "last_name": "",
                "email_id": "[email protected]",
                "tag_name": "Career Page ( sign up )",
                "position_name": "Fraud & Risk Specialist ",
                "campaign": "Airbnb Ireland (ABNB-MYS)",
                "location": "Malaysia",
                "job_req_id": 22017,
                "test_name": "Personality Test",
                "test_question": "AirBnB - Chinese Email Exam",
                "overall_score_average": null,
                "overall_score_percentage": "0%",
                "question": "",
                "answer": "",
                "question_score": 0,
                "question_score_percentage": "0%",
                "score": "",
                "grade": "",
                "test_comments": "",
                "presonality_result": "The Dynamic Thinker - ENTJ",
                "status": "Open",
                "remarks": "",
                "source": "",
                "medium": ""
            },
]

This is the second filter array which contains the column name, value, and should it contain or not

filterArray: [
    {
        "columnName": "first_name",
        "condition": "equal to",
        "value": "Some name"
    },
     {
        "columnName": "last_name",
        "condition": "equal to",
        "value": "Some last name"
     },
]

So I don’t understand how I can filter the original array based on the filter array that I receive
and the thing is the objects props will be dynamic so if one time first_name will be there if they are doing for selected data and the other time the original array will contain totally different values based on the selected data that’s why I am asking dynamically.

How can I make the website automatically run “node index.js” in the browser?

I have a javascript web scraping program for stock prices that I want to run automatically on netlify.

In order for it to run I have to type in “node index.js” in the command terminal.

But.. how can I make it do so AUTOMATICALLY after uploading it to netlify – without maually typing “node index.js”?
Web Scraping/API Practice

It’s my first web scraping project – so please be understanding – it’s probably a VERRY noobie question.

Here’s the index.js file

const request = require("request-promise");
const fs = require("fs");
const cheerio = require("cheerio");


async function tsla() {
    const html = await request.get(
        "https://finance.yahoo.com/quote/TSLA/"
        );

    const $ = await cheerio.load(html);

    const Price = $('[class="Fw(b) Fz(36px) Mb(-4px) D(ib)"]').text();
    const Symbol = $('[class="D(ib) Fz(18px)"]').text();
    const PercentChange = $('fin-streamer[class="Fw(500) Pstart(8px) Fz(24px)"][data-field="regularMarketChangePercent"]').find('span').text();
    fs.writeFileSync("./tslaSymbol.csv", Symbol);
    fs.writeFileSync("./tslaPrice.csv", Price);
    fs.writeFileSync("./tslaPercentChange.csv", PercentChange)
    
    console.log(Price);
    console.log(Symbol);
    console.log(PercentChange)

    setTimeout(tsla, 1000); //60 seconds == 1minute
}

tsla();

async function aapl() {
    const html = await request.get(
        "https://finance.yahoo.com/quote/AAPL/"
        );

    const $ = await cheerio.load(html);

    const Price = $('[class="Fw(b) Fz(36px) Mb(-4px) D(ib)"]').text();
    const Symbol = $('[class="D(ib) Fz(18px)"]').text();
    const PercentChange = $('fin-streamer[class="Fw(500) Pstart(8px) Fz(24px)"][data-field="regularMarketChangePercent"]').find('span').text();
    fs.writeFileSync("./aaplSymbol.csv", Symbol);
    fs.writeFileSync("./aaplPrice.csv", Price);
    fs.writeFileSync("./aaplPercentChange.csv", PercentChange)
    
    
    console.log(Price);
    console.log(Symbol);

    setTimeout(aapl, 1000); // 60,000 = 60 seconds == 1minute
}

aapl();


async function spy() {
    const html = await request.get(
        "https://finance.yahoo.com/quote/spy/"
        );

    const $ = await cheerio.load(html);

    const Price = $('[class="Fw(b) Fz(36px) Mb(-4px) D(ib)"]').text();
    const Symbol = $('[class="D(ib) Fz(18px)"]').text();
    const PercentChange = $('fin-streamer[class="Fw(500) Pstart(8px) Fz(24px)"][data-field="regularMarketChangePercent"]').find('span').text();
    fs.writeFileSync("./spySymbol.csv", Symbol);
    fs.writeFileSync("./spyPrice.csv", Price);
    fs.writeFileSync("./spyPercentChange.csv", PercentChange)
    
    console.log(Price);
    console.log(Symbol);
    console.log(PercentChange);

    setTimeout(spy, 1000); // 60,000 = 60 seconds == 1minute
}

spy();

async function nvda() {
    const html = await request.get(
        "https://finance.yahoo.com/quote/nvda/"
        );

    const $ = await cheerio.load(html);

    const Price = $('[class="Fw(b) Fz(36px) Mb(-4px) D(ib)"]').text();
    const Symbol = $('[class="D(ib) Fz(18px)"]').text();
    const PercentChange = $('fin-streamer[class="Fw(500) Pstart(8px) Fz(24px)"][data-field="regularMarketChangePercent"]').find('span').text();
    fs.writeFileSync("./nvdaSymbol.csv", Symbol);
    fs.writeFileSync("./nvdaPrice.csv", Price);
    fs.writeFileSync("./nvdaPercentChange.csv", PercentChange)
    
    console.log(Price);
    console.log(Symbol);
    console.log(PercentChange);

    setTimeout(nvda, 1000); // 60,000 = 60 seconds == 1minute
}

nvda();

Basically, the javascript scrapes that data and sends it to a CSV file which then is displayed into the page.

MongoError: BSON field ‘update.updates.u’ is the wrong type

I got this error when I trying to run this code with mongoose for MongoDB

'MongoError: BSON field 'update.updates.u' is the wrong type 'array', expected type 'object''

mongoose version: 5.13.14
mongo version: 5.0.3

    const docs = names.map(name => {
        return {
            updateOne: {
                filter: {
                    name
                },
                update: [{
                    $set: {
                       'data.someData': {
                            '$cond': {
                                if: {
                                    $eq: [
                                        '$data.someData',
                                        undefined
                                    ]
                                },
                                then: extraData.someData,
                                else: undefined
                            }
                        },
                    }
                    }],
                upsert: true,
            }
        }
    })
    await this.myCollection.bulkWrite(docs)

Best way to handle localization in NextJS with multiple regions

I am developing a website that will operate in multiple countries, but will offer slightly different features for each country. Additionally, the site for each country should support localization for the user’s desired language. For example, if a user is in France t but have english as their preferred language, they would be routed to the english version of the .fr site.

I have looked into domain based internalization on Next, but it seems like it routes based on language preference and not geolocation. So someone in Spain that prefers French would be routed to the .fr site as opposed to the French version of the .es site, which is not what I want.

At this point, I think the best solution is to keep independent repos for each country, deploy them separately and use sub path routing for each one. This also makes it easier to offer different features based on location. However, it would make it a lot harder to keep all websites synchronized, as I would have to manually update each repo separately.

I am not sure if I am missing another option. Any advice would be greatly appreciated. Thank you!

Add a currency comma in a PDF when format is already used to display an “event.value” in a text field

I’m a real novice when it comes to Javascript and the issue I’m having is a text field in a PDF form already has a custom format to add the text “Check Amount”, which disappears when typing in the text field. The struggle is having it add a comma(s) for currency and the number format won’t allow the displayed text at the same time. Below is the custom format javascript being used:

if (!event.value) { 
event.value = "Check Amount";
event.target.display = display.noPrint;
} else {
event.target.display = display.visible;
}

How do I add a currency format to it?

I’ve seen this javascript by KHKonsulting LLC, but the prefilled text of “Check Amount” disappears completely:

var f = this.getField("SomeField");
f.setAction("Format", "AFNumber_Format(2, 0, 0, 0, "", true);");
f.setAction("Keystroke", "AFNumber_Keystroke(2, 0, 0, 0, "", true);");

Operator overloading in js? [duplicate]

Is there anything that allows for overloading some of the more common operators in javascript? For example, taking an example from python to overload the >>:

class Perhaps:
    def __init__(self, value):
        self.value = value

    def __rshift__(self, other):
        ...

Is the anything similar to:

class Perhaps {
    constructor(value) {
        this.value = value
    }
    ?rshift?(other) {
        ...
    }
}

AJAX Call is not Sent NO ERRORS

I am using AJAX for making a custom plugin in WordPress. I have successful made some pages. But whatever I do, AJAX doesn’t even make a call in a particular page. I have checked the console, no request is made and syntax is valid.

My code:

function onSubmit(token) { 
     document.getElementById("result").innerHTML += "<p style="color: green;">Processing.........</p>";
     var form = document.forms["dt_login_form"];
var formData = new FormData(form);
     
                    $.ajax({
url: "/login/",
                       method: 'POST',
                       data: formData,
                       async: false,
                       cache: false,
                       contentType: false,
                       enctype: 'multipart/form-data',
                       processData: false,
                       success: function (data) {
                           if(data.status == 'success'){
                            document.getElementById("result").innerHTML = "<p style="color: green;">Successfully Logged In! Redirecting.....</p>";
                          } else if(data.status == 'fail'){
                            $('form').addClass('ahashakeheartache');
                            $('form').on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
                              $('form').delay(200).removeClass('ahashakeheartache');
                            });
                            document.getElementById("result").innerHTML = "<p style='color: red; float:center; text-align: center; font-size: 20px; '>Request Failed with Error:<br>" + data.message + "</p><br>";
                          }
                      },
                      error: function (err) {
                        console.log(err);
                          document.getElementById("result").innerHTML = "<p style='color: red;'>Request Failed with some Fatal Errors. Contact System Administrator or check Console for more details. </p><br><br>";
                      }
                    });
                   
   }

I have tried removing other parameters, still it isn’t working. Whereas in other page, almost same code, it works.

DOM Select. How to hide the list elements until an selectIndex is selected

I am writing a DOM select element program that creates a radio button that reveals a list of States in the USA.

This is how a part of the program looks:

The result of the program should create a button with the United States label attached to it. When I click on the button, a short list of the different American States should appear.
One problem is that the select list already shows after the program is executed. It’s supposed to be hidden at the beginning and the list should only appear when I click on the United States button.
enter image description here

I’m wondering how I can fix this.
Also, in an example that I looked at, it’s suggested to apply the global variable – var selectShowing = false; to the function to prevent the list of states from appearing immediately when the program is run.
Thanks in at advance and I appreciate your suggestions.

var states = new Array(2); 
states[0] = new Array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Idaho", "Illinois"); 
states[1] = new Array("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "ID", "IL");
    
function createSelect(divId, statesArray) {
    var mySelect = document.createElement("SELECT"); 
    mySelect.setAttribute("name", "states"); 
    mySelect.setAttribute("id", "states"); 
    var newOption;
    var newTextNode; 
    for (i = 0; i < statesArray[0].length; i++) {
        //create the new option
        newOption = document.createElement("OPTION"); 
        //set the value of the new option. values are for states[1]
        newOption.setAttribute("value", statesArray[1][i]); 
        //make a new text node - that's the text that appears between the opening and closing option tags
        //it is what you see in the pulldown menu list
        //text node items are in states[0]
        newTextNode = document.createTextNode(statesArray[0][i]);
        //append the text node to the option
        newOption.appendChild(newTextNode); 
        //append the option to the select
        mySelect.appendChild(newOption); 
    }
    document.getElementById(divId).appendChild(mySelect);
}
<div id="selectDiv"></div>
    <p><label><input type="radio" value="createSelect('selectDiv', states);" onclick="createSelect('selectDiv', states);" />United States</label></p>
  
<select name="state" id="state">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="AR">Arkansas</option>
    <option value="CA">California</option>
    <option value="CO">Colorado</option>
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="ID">Idaho</option>
    <option value="IL">Illinois</option>
</select>   

JEST unit test for Vue computed

How to write a JEST unit test for this:

  computed: {
    ...mapState('account', ['communicationPreferences']),
    communicationPreferenceTypeEmail() {
      return this.communicationPreferences.filter((e) => e.type === 'EMAIL')
    },
    communicationPreferenceTypeNotEmail() {
      return this.communicationPreferences.filter((e) => e.type !== 'EMAIL')
    },
  },

My test spec:

  it('should filter communication preferences by TYPE', () => {})

Change CSS display property with javascript if recaptcha not checked in form?

I’m trying to write a javascript function that confirms a user has checked a Google recaptcha V2 box (using django-recaptcha). If they haven’t checked the recaptcha box I’d like to display a piece of text reminding them to check before submitting the form. Here’s what I’ve already tried but the button either submits and refreshes the page, or the hidden div just will not display.

Javascript

function checkForm(){
      
  if(!document.getElementById("g-recaptcha-response").value){
    $('.validate').show();
      return false;
  }else{
    document.getElementById("buttoncontact").type = "submit";                
      return true;
        }
      }

HTML

<div>
  {{form.captcha}}
</div>
<div class="captcha">
  This site is protected by reCAPTCHA and the Google
  <a href="https://policies.google.com/privacy">Privacy Policy</a> and
  <a href="https://policies.google.com/terms">Terms of Service</a> apply.
</div>
<div class="validate" style="display: none;">
  Please validate the captcha field before submitting.
</div>
<div>
  <button id="buttoncontact" type="submit" onclick="return checkForm();">Submit</button>
</div>

I’ve gotten this code to work with the alert function show below, however for user experience I’d much rather not have an alert window to pop up:

function checkForm(){
      
  if(!document.getElementById("g-recaptcha-response").value){
    alert("Please validate the captcha field before submitting.");
      return false;
  }else{
    document.getElementById("buttoncontact").type = "submit";                
      return true;
        }
      }

How to find all unique values for specific key in array of objects in Javascript?

I have an array of javascript objects and I am trying to get an array of all unique values for a specific property in each object. I tried to do this using reduce(), my example code is below, but it results in an error that it “Cannot read properties of undefined (reading ‘includes’)” even though I provided an initial value of an empty array. The intended result is an array with

['New York', 'San Francisco', 'Chicago', 'Los Angeles']

The end goal is to create a bar graph with the cities on the X-axis and the calculated average wage for each city on the Y-axis, so I need the unique list of cities. Is there a way to avoid this error, or a better way to do this altogether?

const employees= [
 {id: 0, city: 'New York', wagePerHour: '15'}, 
 {id: 1, city: 'San Francisco', wagePerHour: '18'}, 
 {id: 2, city: 'New York', wagePerHour: '16'}, 
 {id: 3, city: 'Chicago', wagePerHour: '14'}, 
 {id: 4, city: 'Chicago', wagePerHour: '12'}, 
 {id: 5, city: 'San Francisco', wagePerHour: '15'}, 
 {id: 6, city: 'New York', wagePerHour: '18'}, 
 {id: 7, city: 'Los Angeles', wagePerHour: '10'}
];
const cities = employees.reduce((foundValues, nextEmployee) => {
 if(! foundValues.includes(nextEmployee.city)) {
  foundValues.push(nextEmployee.city);
 }
}, []);