Why does JavaScript go into never ending loop and not just error out on input send

I know that it DOES to it. But everywhere I go gives you instructions on how to send a form properly. That’s not what I am looking for.

I am wondering that why when you make the mistake of trying to (I realize I am using jQuery here, but there is no difference in this, or getElementByID)

$.post("/scripts/intake.php", {
        full_name: $('#full_name'),
        ...

Why does JavaScript even allow a “raw element” to be “sent”? But my real question is, what actually causes the problem? Is it looping infinitely through the DOM Object (which is what I am suspecting)? Can someone explain what happens specifically that JS freaks out over sending a DOM Object VS sending a parameter of said Object:

full_name: $('#full_name').val()

I understand that Object would be useless to the page posted to .. But what happens here to make JavaScript error out in an overflow vs just implementing an internal “try – catch” to prevent the nuance of waiting for it to time out, only to realize you have bad syntax?

Why insertMany does not create ObjectIds in mongoose?

Currently I’m developing an APP using Node.JS and MongoDB. I’m trying to insert multiple documents with predefined _id s and some ObjectId arrays.
When I use insertMany all documents _id fields are strings instead of ObjectId. However when I use create and pass an array it works fine but instead of one query it performs separate query for each item of the array.

As it is obvious as the array grows it would be critical problem.

How can I use insertMany with the fields of type ObjectId instead of string?

enter image description here

How can I make the Event listener ‘mousemove’ activate upon hover?

I’m working on creating a draggable slider and so i’m trying to work with a ‘mousemove’ event listener which should be activated when my mouse is hovering over the element, but it is not being activated. The event listener only registers when I click down with my mouse.

Here’s the code:

let slider = document.querySelector('.slider1');

slider.addEventListener('mousemove', () => {
  console.log('mouse is hovering');

})
<div class="slider1">
  <div class="f-images">
    <img src="images/image1" alt="Image1" class="image1">
    <img src="images/image2" alt="Image2" class="image2">
    <img src="images/image3" alt="Image3" class="image3">
    <img src="images/image4" alt="Image4" class="image4">
    <img src="images/image5" alt="Image5" class="image5">
    <img src="images/image6" alt="Image6" class="image6">
  </div>
</div>

I’m expecting it to spam the console log with ‘mouse is hovering’ when I go over the slider, but it doesn’t. It only pops up when i click down with the mouse. (I know that for a draggable slider I need to add an if statement that means it only proceeds if the mouse is pressed down, but i’m just trying to workout how mousemove works for now)

Reduce duplication of images using javascript

I was told it can be done via javascript but I wasn’t able to figure it out.

How would I do that here with this code? https://jsfiddle.net/czqa3Lds/

Something like this I was thinking. https://jsfiddle.net/5bj72hd1/

I tried different things and wasn’t able to do it.

That is all I am trying to do here, reduce duplication of the images.

<div class="container">
  <div class="panel-left">
    <div class="inner">
      <div class="container2" id="container2-left">
        <!-- Images will be inserted here by JavaScript -->
      </div>
    </div>
  </div>

  <div class="panel-right">
    <div class="inner">
      <div class="container2" id="container2-right">
        <!-- Images will be inserted here by JavaScript -->
      </div>
    </div>
  </div>
</div>

html,
body {
  margin: 0;
  padding: 0;
}

body {
  background: #121212;
  padding: 50px 8px;
}

.panel-left,
.panel-right {
  position: fixed;
  height: 100%;
  width: 50%;
  top: 0%;
  overflow: hidden;
  z-index: 0;
  transform: translateX(0);
  transition: transform 7s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition-delay: 1s;
}

.panel-left {
  left: 0;
}

.panel-right {
  right: 0;
}

.panel-left::before,
.panel-right::before {
  content: "";
  position: fixed;

  height: 100%;
  width: 200%;
  top: 0;
  left: 0;
}

.panel-right::before {
  left: -100%;
}

.container:hover .panel-left {
  transform: translateX(-100%);
}

.container:hover .panel-right {
  transform: translateX(100%);
}

.inner {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 200%;
  position: absolute;
  left: 0;
  z-index: 2;
}
.panel-right .inner {
  left: -100%;
}

.container2 {
  max-width: 360px;
  border: 1px solid #ccc;
}

.container2 div {
  display: flex;
  justify-content: center;
}

.container2 img {
  display: block;
  margin: auto;
  width: 33.33%;
  height: auto;
}
<div class="container">
  <div class="panel-left">
    <div class="inner">
      <div class="container2">
        <img src="https://i.imgur.com/z5MMJnv.png" alt="Image 1">
        <div>
          <img src="https://i.imgur.com/5u16syR.png" alt="Image 2">
          <img src="https://i.imgur.com/ygTtvme.png" alt="Image 3">
          <img src="https://i.imgur.com/QziKNDW.png" alt="Image 4">
        </div>
        <img src="https://i.imgur.com/8Jf8LLc.png" alt="Image 5">
      </div>
    </div>
  </div>

  <div class="panel-right">
    <div class="inner">
      <div class="container2">
        <img src="https://i.imgur.com/z5MMJnv.png" alt="Image 1">
        <div>
          <img src="https://i.imgur.com/5u16syR.png" alt="Image 2">
          <img src="https://i.imgur.com/ygTtvme.png" alt="Image 3">
          <img src="https://i.imgur.com/QziKNDW.png" alt="Image 4">
        </div>
        <img src="https://i.imgur.com/8Jf8LLc.png" alt="Image 5">
      </div>
    </div>
  </div>
</div>

Repeated error in logs: MaxListenersExceededWarning

I am having issues figuring out why I keep getting the following error:

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added to [Connection]. Use emitter.setMaxListeners() to increase limit

Below is my code:

export const Mychatapp = () => {

  var connnections = {}

  const WebSocket = require('ws');

  const webSocketServer = new WebSocket.Server({ port: 8443 });

  console.log("Websocket listening on 8443")

  webSocketServer.on('connection', (webSocket) => {

    webSocket.on('message', (message) => {

      var newdata = JSON.parse(message)

      switch (newdata.command) {

        case "connect":

          connnections[newdata.data.id] = webSocket;

          break;

        case "message":
         
          let msgsent = chatService.sendmsg(newdata.data);

          if (connnections[newdata.data.to_id]) {

            connnections[newdata.data.to_id].send(message);

            if (msgsent.success) {
              connnections[newdata.data.toid].send(message);
            }

            chatService.pushsend(newdata.data);

          } else {

            chatService.pushsend(newdata.data);

     
          }
          break;
        default:

      }
    });

  });

}

I am not sure what to do. Please assist.

Tried using once instead of .on. Very stuck as to what to try.

Can’t find a span element in a Web Component template document fragment

I am trying to add an onclick event across two slots in a Web Component template. I have tried surrounding it with a span and then running a .querySelector to get that span but it’s not finding the #label-wrapper element- I am rather confused.

HTML:

<template><span id="label-wrapper"><slot></slot>: <slot name="number"></slot></span></template>

Javascript

constructor(tab) {
    super();
    let template = document.getElementById("example-template");
    let templateContent = template.content;

    const containerNode = (templateContent.cloneNode(true));

    this.tab = tab;
    let slotNode = containerNode.querySelector("slot")
    slotNode.append("Example label");

    let labelWrapper = containerNode.querySelector("#label-wrapper");
    labelWrapper.onclick = () => {
        // Do something
    }

    this.append(containerNode);

JavaScript – matching and pushing certain items from two arrays

So I have data from https://restcountries.com/v3.1/all that gives me 250 countries.

Inside a country, France for example, it lists out all the countries that border it.

borders:(8) ['AND', 'BEL', 'DEU', 'ITA', 'LUX', 'MCO', 'ESP', 'CHE']

Those three character names appear as cca3. So for France its cca3 is ‘FRA’. Every country has a cca3 so when I loop through data, I get all 250 unique cca3 names.

I have

let borders = [];

for (let j = 0; j < data[i].borders.length; j++) {
    borders.push(data[i].borders[j]);
}

Which creates an array for all of those countries that border the selected country (again, France here).

console.log(borders, "borders");

returns

 (8) ['AND', 'BEL', 'DEU', 'ITA', 'LUX', 'MCO', 'ESP', 'CHE'] 'borders'

I have for (let i = 0; i < data.length; i++) as the main loop. It loops through all 250 countries and prints out info I’m using for the page.

When I loop through borders to find any cca3 names that match between borders[k] and data[i] it pushes the matching cca3 into a new array, matches

So far so good.

Here’s the code that loops and matches

for (let k = 0; k < borders.length; k++) {
    if (borders[k] == data[i].cca3) {
        matches.push(data[i].name.common);
    }
}

The very weird problem is that only five of those eight border countries are pushed into the matches array.

console.log(matches, "matches");

returns

(5) ['Luxembourg', 'Belgium', 'Switzerland', 'Germany', 'Spain']
 'matches'

Screen shot of the console

I thought that maybe some specific cca3’s were broken or something, but for example, Laos will show “China” in it’s matches array, but other countries that have borders with China will not show it.

I have absolutely no idea why some of these aren’t matching. China has 15 out of 16 matching, but Russia only has 2 out of 14 matching.

Sweden and Norway will both show Finland as matching, but Russia does not.

const api_url = new URL("https://restcountries.com/v3.1/all");
let data = "";
//Short name of countries bordering selected country
let borders = [];
let matches = [];

async function getData() {
    // Make request and get response
    const response = await fetch(api_url);

    // JSON
    data = await response.json();

    // Loop through data
    for (let i = 0; i < data.length; i++) {
        if (data[i].name.common.toLowerCase() == country) {
            const lang = Object.keys(data[i].languages)[0];

            console.log(data[i], "data");
            console.log(data[i].cca3, "cca3");

            flagImg.src = data[i].flags.png;
            countryName.textContent = data[i].name.common;
            nativeName.textContent = data[i].name.nativeName[lang].common;
            population.textContent = data[i].population.toLocaleString("en", {
                useGrouping: true,
            });
            region.textContent = data[i].continents;
            subRegion.textContent = data[i].subregion;
            capital.textContent = data[i].capital;
            domain.textContent = data[i].tld;
            currency.textContent = Object.values(data[i].currencies)[0].name;
            language.textContent = Object.values(data[i].languages);

            borders = [...data[i].borders];
        }

        // Loop through the data and if any short names match with the bordering country short names, add to matches array

        for (let k = 0; k < borders.length; k++) {
            if (borders[k] == data[i].cca3) {
                matches.push(data[i].cca3);
            }
        }
    }
    console.log(borders, "borders");
    console.log(matches, "matches");

What’s wrong with my JavaScript if else statement? [duplicate]

The browser console just output ‘Jason: Failed’ but I am expecting ‘Jason: A’, here is my code below:

function gradesResult(person) {
    let grades = {
        Jason: 97,
        Tommy: 64,
        Tina: 81,
        Steve: 73,
        Wilson: 91,
        Roy: 68,
        Teddy: 74,
        Sam: 82,
        Leila: 58,
        Leslie: 77
    };
    
    let result = grades.person;
    if (result >= 90) {
        return person + ': A'
    } 
    else if (result >= 80 && result < 90) {
        return person + ': B'
    } 
    else if (result >= 70 && result < 80) {
        return person + ': C'
    } 
    else if (result >= 60 && result < 70) {
        return person + ': Passed'
    } 
    else {
        return person + ': Failed'
    }
}

console.log(gradesResult('Jason'));

In-App Messaging Firebase click listener in React Native

I’m integrate In-App Messaging Firebase into my app, which is built with React Native and Expo, and I need to access the custom data specified in the Firebase console when I create the message (custom data in Firebase console).

I looked through the documentation and didn’t find a function (like a button click listener) that can help me with that.

I’m trying to use a Linking listener, but it doesn’t work.

Linking.addEventListener('url', (event) => {
    console.log("Linking event:", event.url);
    setUri(event.url);
});

I want to retrieve the custom data in the In-App message and perform whatever logic the client needs. Does anyone have an idea how I can achieve this?

How to send a form from a file index.html to a file success.html

please tell me if there is a problem with sending the name and phone number form. There is an index.html file in which there are fields for entering the name and phone number, there is also a file send.php which sends the data to my email, after clicking the “Place an order” button on the index.html page, it transfers to send.php , and send.php it ‘s already on the page success.html . I would like to make it so that on the page succes.html the data of the name and phone number entered on the page were displayed index.html to verify the correctness of the entered data by customers, while not losing the ability to receive notifications about requests by mail that the file sends send.php

And how to make the name and phone data appear in a certain place in the file success.html

I tried to do it through jQuery:

/*! FormChimp v1.2.1 | Fabio Quarantini – http://www.fabioquarantini.com */
!function(a,b,c,d){a.fn.formchimp=function(b){var d=a(this),e=a(“body”),f=d.attr(“action”).replace(“/post?”,”/post-json?”).concat(“&c=?”),g=d.find(‘[type=”submit”]’),h={appendElement:d,buttonSelector:g,buttonText:””,debug:!1,errorMessage:””,onMailChimpSuccess:function(){},onMailChimpError:function(){},responseClass:”mc-response”,successMessage:””,url:f},i=h.buttonSelector.text();a.extend(h,b),a(d).on(“submit”,function(b){b.preventDefault(),e.removeClass(“mc-success mc-error”).addClass(“mc-loading”),0===a(“.”+h.responseClass).length?$responseContainer=a(“”).addClass(h.responseClass).appendTo(h.appendElement):$responseContainer.html(“”),a.ajax({url:h.url,data:d.serialize(),dataType:”jsonp”}).done(function(b){h.debug&&console.log(JSON.stringify(b));var d=b.msg;isNaN(d.charAt(0))||”-“!==d.charAt(2)||(d=d.substring(3)),e.addClass(“mc-“+b.result).removeClass(“mc-loading”),”success”===b.result?(“”!==h.successMessage&&(d=h.successMessage),””!==h.buttonText&&h.buttonSelector.text(h.buttonText),a(c).trigger(“mailChimpSuccess”),h.onMailChimpSuccess.call()):(“”!==h.errorMessage&&(d=h.errorMessage),””!==h.buttonText&&h.buttonSelector.text(i),a(c).trigger(“mailChimpError”),h.onMailChimpError.call()),$responseContainer.html(d)})})}}(jQuery,window,document);

Highcharts Pie with Drilldown: How to change the color of each sub category

I need to create a pie chart with drill down, but color each subgroup in the drill down pie chart a different color. Right now, I get the default colors assigned to the data sets. The parent pie chart will have total count of active alerts for each environment i.e. DEV,DR, PROD, NPRD and when you drill down to each environment, display another pie chart that has 3 groupings ‘Critical’,’Warning’,’Info.’ Critical colored red, warning colored orange, info colored yellow.

Here is my code which works perfectly except the coloring of the subgroups of the drilldown pie chart.

Highcharts.chart('container_alerts_environment', {
    chart: {
        type: 'pie'
    },
    title: {
        text: 'Alerts Grouped By Environment',
        align: 'center'
    },
    subtitle: {
        text: 'Click the slices to view alerts. Source: <a href="http://vi-operations.bbtnet.com/Data/Active Nutanix Alarms.html" target="_blank">Alerts Data</a>',
        align: 'center'
    },

    accessibility: {
        announceNewData: {
            enabled: true
        },
        point: {
            valueSuffix: ''
        }
    },

    plotOptions: {
        series: {
            borderRadius: 5,
            dataLabels: [{
                enabled: true,
                distance: 15,
                format: '{point.name}'
            }, {
                enabled: true,
                distance: '-30%',
                filter: {
                    property: 'percentage',
                    operator: '>',
                    value: 0
                },
                format: '{point.y}',
                style: {
                    fontSize: '0.9em',
                    textOutline: 'none'
                }
            }]
        }
    },

    tooltip: {
        headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
        pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
        },

    series: [
        {
            name: 'Alert Count',
            colorByPoint: true,
            data: [
                {
                    name: 'DEV',
                    y: 19,
                    drilldown: 'DEV'
                },
                {
                    name: 'NPRD',
                    y: 8,
                    drilldown: 'NPRD'
                },
                {
                    name: 'DR',
                    y: 11,
                    drilldown: 'DR'
                },
                {
                    name: 'PROD',
                    y: 23,
                    drilldown: 'PROD'
                }
            ]
        }
    ],
    drilldown: {
        series: [
            {
                name: 'DEV',
                id: 'DEV',
                data: [
                    [
                        'Critical',
                        10
                    ],
                    [
                        'Warning',
                        7
                    ],
                    [
                        'Info',
                        2
                    ]
                ]
            },
            {
                name: 'NPRD',
                id: 'NPRD',
                data: [
                    [
                        'Critical',
                        3
                    ],
                    [
                        'Warning',
                        4
                    ],
                    [
                        'Info',
                        1
                    ]
                ]
            },
            {
                name: 'DR',
                id: 'DR',
                data: [
                    [
                        'Critical',
                        1
                    ],
                    [
                        'Warning',
                        4
                    ],
                    [
                        'Info',
                        6
                    ]
                ]
            },
            {
                name: 'PROD',
                id: 'PROD',
                data: [
                    [
                        'Critical',
                        12
                    ],
                    [
                        'Warning',
                        8
                    ],
                    [
                        'Info',
                        3
                    ]
                ]
            }
        ]
    }
});

Adding the color attribute inside each dataset does not work, I get an error of unexpected token. Can someone help?

Google Static Maps API Polyline with repeating icon (dashed line)

I have successfully used Google Maps icon technique to create dashed poly lines but now I want to apply this to a Google Maps Static Maps API image.

How do I apply a repeating icon along a path in a static Map similar to how it is done in Google Maps API?

Is it simply adding an icons to the path?
For example take a static Map URL that shows a solid path in NY

{"https://maps.googleapis.com/maps/api/staticmap?size=600x600&path=color:0xff0000ff|weight:5|40.737102,-73.990318|40.749825,-73.987963|40.752946,-73.987384|40.755823,-73.986397&zoom=19" + "&key=" + process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}

Would you just add in icons variable with associated arguments like (icon, offset and repeat) to dash this line?:

{"https://maps.googleapis.com/maps/api/staticmap?size=600x600&path=color:0xff0000ff|weight:5|icons&icon|path=M 0,-1 0,1|strokeopacity:0|scale:2|offset:0|repeat:20px|40.737102,-73.990318|40.749825,-73.987963|40.752946,-73.987384|40.755823,-73.986397&zoom=19" + "&key=" + process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}

This doesn’t work

Javascript canvas graphics optimazation

left candles look sharp, right candles are kind of blurry

Look at the image that I attached to this post. When I load the canvas it looks blurry. However, when I zoom out and then zoom back in the canvas looks very sharp. You may not be able to tell through the image but just try to compare the sharpness of individual candles.

How can I make sure candles are sharp as soon as they appear on the canvas?

Thanks

I tried some optimization but still, there is something that I’m missing.

Adobe Target: Unable to load all site elements in the editor

I’m in the process of migrating to Adobe Target for our A/B testing solution. I have Target successfully installed via Adobe Data Collection. However, not all the page elements load in the editor when I try to create test modifications. The missing components I’ve identified so far have been fonts, external CSS stylesheets, and forms with JavaScript functionality (a crucial component of our site for any sort of testing).

Here are some other relevant details:

  • Our site is not on Adobe Experience Manager
  • We use Firefox (have also tried in Chrome. Adobe recommends Firefox so we’re sticking with that, but have still been testing in both)
  • The form/JavaScript elements are hosted within the domain

I’m happy to provide other details anyone may deem relevant. Any assistance is greatly appreciated!

We expected to see and be able to edit all site elements in the Target editor, but it won’t load JavaScript and CSS components.

We originally thought the issue stemmed from a MIME type mismatch with our site’s header “X-Content-Type-Options” being set to “nosniff”:
nosniff error

However, when we changed the header value to “sniff,”
we started getting 404 errors within the Target editor for all our site’s JavaScript files:
404 error

What else we’ve tried:

  • We toggled the Target editor “Page Delivery” options (“render using JavaScript” and “enable Enhanced Composer), but this didn’t change anything
  • We tried to install an anti-flicker code snippet, but this didn’t change anything

How do I adjust the spacing to print chords from chordpro format to be aligned above the lyrics?

const fs = require('fs');

const fileName = 'songs/Sister Golden Hair.txt';

fs.readFile(fileName, 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  // Split the file into lines
  const lines = data.split('n');

  // Regular expression to match chords within square brackets
  const chordRegex = /[([^]]+)]/g;

  // Iterate through each line and extract chords and lyrics
  for (let line of lines) {
    // Extract chords
    const chords = [];
    let chordMatch;
    let lastIndex = 0;

    while ((chordMatch = chordRegex.exec(line)) !== null) {
      const chord = chordMatch[1];
      const index = chordMatch.index;

      // Calculate spacing
      const spacing = ' '.repeat(index - lastIndex);
      chords.push(spacing + chord);

      lastIndex = index + chord.length;
    }

    // Remove chords from the line
    const lyrics = line.replace(chordRegex, '').trim();

    // Display chords above lyrics
    console.log(chords.join(' ') + 'n' + lyrics);
  }

  console.log("DONE");
});

Current output

Intended output

Here is the chordpro file. I think the issue is that the code is not compensating for the length of the chord and adds to many spaces.

ChordPro example

Thanks!