How to add an email mask input ([email protected]) in javascript

I’m trying to add a mask to an email input ([email protected]). I tried some libraries before, the mask works but the libraries are not light (~200kb). I’m hoping, if possible, to find a simple code (with regexr maybe) that can help to add an email mask like this: [email protected]

P.S1: By “mask” I mean, controlling your input while the user is still typing, so he can’t type any invalid characters. It’s usually used with phone numbers. For instence, with phone numbers, we prevent the user from typing any non-digit characters (I do not mean validation).
P.S2: I’m using Jquery only,

Thank you

How to deselect HTML element with Javascript

I am implementing a game of set using javascript. I have a class to discern whether or not the card is being selected and I will add the class to this when this method is called, which is when the card is clicked as there is an eventListener for it. However, the issue I have is implementing a deselect eventListener to be able to click so the selected class is gone but be able to click again and the selected class is back and behaves as it would have earlier.
Here is the code for the function that runs when you select the card:

    function cardSelected() {
    let setCount = qs('#set-count');
    let board = qs('#board');
    this.classList.add('selected');
    let selected = qsa('#board .selected');
    let count = selected.length;
    if (count === 3 && isASet(selected)) {
      for (let i = 0; i < selected.length; i++) {
        let card = generateUniqueCard(true);
        board.replaceChild(card, selected[i]);
        selected[i].classList.remove('selected');
        let paragraph = createParagraph('SET!');
        let timer = setTimeout((i) => {
          card.classList.add('hide-imgs');
          card.appendChild(paragraph);
        }, 0);
        setTimeout(() => {
          clearTimeout(timer);
          card.classList.remove('hide-imgs');
          card.removeChild(paragraph);
        }, 1000);
      }
      setCount.textContent = parseFloat(setCount.textContent) + 1;
    } else if (count === 3 && !isASet(selected)) {
      for (let i = 0; i < selected.length; i++) {
        selected[i].classList.remove('selected');
        let paragraph = createParagraph('Not a Set');
        let card = generateUniqueCard(true);
        board.replaceChild(card, selected[i]);
        let timer = setTimeout((i) => {
          card.classList.add('hide-imgs');
          card.appendChild(paragraph);
        }, 0);
        setTimeout((i) => {
          clearTimeout(timer);
          card.classList.remove('hide-imgs');
          card.removeChild(paragraph);
        }, 1000);
      }
    }
  }

What am I doing wrong when filtering out data from a multi-level object?

Trying to understand and practice manipulation of passed in data I have created an array of objects:

const pizzaObj = [
  {
    id: 'mon',
    name: 'Monday',
    subMenu: [],
  },
  {
    id: 'tues',
    name: 'Tuesday',
    subMenu: [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ],
  },
  {
    id: 'wed',
    name: 'Wednesday',
    subMenu: [],
  },
]

that I’m trying to filter out medium and large from the subMenu so it will look like:

const pizzaObj = [
  {
    id: 'mon',
    name: 'Monday',
    subMenu: [],
  },
  {
    id: 'tues',
    name: 'Tuesday',
    subMenu: [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ],
  },
  {
    id: 'wed',
    name: 'Wednesday',
    subMenu: [],
  },
]

I can remove if just targeting the subMenu:

const listToDelete = ['medium', 'large']

const pizzaObj = [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ]

const result = pizzaObj.filter( el => (-1 == listToDelete.indexOf(el.id)) )

console.log(result)

But when I try filtering with the object using some the data isn’t removed:

const listToDelete = ['medium', 'large']

const pizzaObj = [
  {
    id: 'mon',
    name: 'Monday',
    subMenu: [],
  },
  {
    id: 'tues',
    name: 'Tuesday',
    subMenu: [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ],
  },
  {
    id: 'wed',
    name: 'Wednesday',
    subMenu: [],
  },
]

const result = pizzaObj.filter(m => {
  return Object.keys(m).some(key => {
    return key === 'subMenu'
      ? m[key].filter(item => -1 === listToDelete.indexOf(item.id))
      : m[key]
  })
})

console.log(result)

I’ve also tried with map:

const pizzaObj = [
  {
    id: 'mon',
    name: 'Monday',
    subMenu: [],
  },
  {
    id: 'tues',
    name: 'Tuesday',
    subMenu: [
      {
        id: 'small',
        name: 'Small',
      },
      {
        id: 'medium',
        name: 'Medium',
      },
      {
        id: 'large',
        name: 'Large',
      },
      {
        id: 'xlarge',
        name: 'X Large',
      },
    ],
  },
  {
    id: 'wed',
    name: 'Wednesday',
    subMenu: [],
  },
]

const testStrip = data => {
  const listToDelete = ['medium', 'large']
  
return data.filter(m => {
  return Object.keys(m).map(key => {
    return key === 'subMenu'
      ? m[key].filter(item => -1 === listToDelete.indexOf(item.id))
      : m[key]
  })
})
}

console.log(testStrip(pizzaObj))

Research:

What am I misunderstanding and how should I be filtering out medium and large?

Update/Reload specific tile in leaflet dynamicly

If my server tells the clients when and what tile to reload/update, how can reload/update the tile sent from the server? I’m using the L.CRS.Simple CRS. And I have no zoom levels on a custom game map.

Here is my code:

var map = L.map('map', {
    crs: L.CRS.Simple,
    attributionControl: false
}).setView([0, 0], 2)

L.tileLayer('/chunks/{x}.{y}.png', {
 maxNativeZoom: 1, 
 minNativeZoom: 1,
}).addTo(map)


function ReloadTile(x,y){
   // UPDATE TILE HERE Request for example /chunks/{1}.{1}.png depending on input
}

Play next audio if the current audio is finished playing using javascript

I am trying to play another audio if the current audio is finished but I am not getting any success results would be appreciated if any suggestions is given here is the below code :-

<audio class="pas" controls  loop autoplay>
               <source  src="https://www.mboxdrive.com/Drake_-_One_Dance_(Lyrics)_ft._Wizkid_&_Kyla(128k).m4a" type="audio/mp3">
               Your browser dose not Support the audio Tag
           </audio>
    <audio class="pas" controls  loop autoplay>
               <source src="https://www.mboxdrive.com/Coobie_-_Miss_You_(Official_Lyric_Video)(256k).mp3" type="audio/mp3">
               Your browser dose not Support the audio Tag
           </audio>

And below is the js I am currently using

document.addEventListener('DOMContentLoaded', () => {
   
    ms();
    
});
function ms() {
    var btns= document.getElementsByClassName("pas");
    for (var j = 0; j < btns.length; j++) {
        
        document.addEventListener('play', function(e){
                var songs = document.getElementsByClassName("pas");
     for(var i = 0;i<songs.length;i++){
         if(songs[i] != e.target){
            songs[i].pause();
        }
    }
    
}, true);


}

}

The above js is to allow only one audio to be played once. Anyway possible way to add any function to play another audio if the first one is finished?
You can try love demo here https://jsfiddle.net/mt1koznd/2/

how to use virtual scroll on table

Good morning
I implemented the “cdk-virtual-scroll-viewport” to improve the performance when loading data, but there was a break in the table where when using the virtual scroll another vertical scroll is automatically created, if anyone knows how to implement it properly I appreciate it. Thanks.

enter image description here

How to convert string to a number in a two-dimensional array?

So i did write a simple function to deal with my string declared in variable poly, as you can see I used a split() method and now i want to convert each of those string values to numerical values:

function toArray(polygon) {
  final = polygon.replace('POLYGON ', '').replace('((', '').replace('))', '').split(',');

  const arrOfNum = [];

  final.forEach(str => {
    arrOfNum.push(Number(str));
  });
  return arrOfNum
}

poly = 'POLYGON ((21.0446582 52.2367037, 21.0544858 52.2264265, 21.0702358 52.2307111, 21.0755573 52.2333133, 21.0771022 52.2349428, 21.0759006 52.2375447, 21.0716091 52.2421962, 21.0532413 52.238412, 21.0472331 52.2371242, 21.0446582 52.2367037))';

console.log(toArray(poly))

I’m trying to convert strings to a numerical values but I’m getting this result:

    [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]

Later on i want to get to this exact point:

    [[20.7218472,52.2294069],
    [20.9436337,52.0756329],
    [21.0651699,52.2134223],
    [20.7767788,52.2537934],
    [20.7218472,52.2294069]]

The main goal of those operations is that i want to use this data to find out if a Point is within a Polygon. To do this I’m using this function:

function ray_casting(point, polygon){
    var n=polygon.length,
        is_in=false,
        x=point[0],
        y=point[1],
        x1,x2,y1,y2;

    for(var i=0; i < n-1; ++i){
        x1=polygon[i][0];
        x2=polygon[i+1][0];
        y1=polygon[i][1];
        y2=polygon[i+1][1];

        if(y < y1 != y < y2 && x < (x2-x1) * (y-y1) / (y2-y1) + x1){
            is_in=!is_in;
        }
    }

    return is_in;
}

Thx everyone for the help!

JsPDF bold, normal and justify in same line

I am using JsPdf to create my pdf from the API response. I have also implemented the bold and normal word in same line. This logic is copied from below link. Now I want to make the text “justify”. How can I do that. Below is the snapshot for the reference,

[https://codepen.io/AndreKelling/pen/BaoLWao][1]

The below highlighted having bold word in between, so I am not able apply the justify on the text. But other paragraph which do not have any bold word is correctly justify.
https://i.stack.imgur.com/n4Nm8.png

How Can I use both bold and normal text mix along with text style justify and custom font. I am
using jspdf for this? Any help would be highly appreciated.

Password validation in a modal javascript

I am trying to check if two passwords (password1 and password2) in the input fields are the same. If I click the button there is automatically a text which is not in the corresponding condition of the button. I am trying to fix to display a text when – 1) Checking of empty password field. 2) minimum password length validation. 3) maximum length of password validation.
https://jsfiddle.net/chrismontage/onh51g93/4/

<label for = "password">New Password</label>
<input type="password" class = "input" id = "password1" value="">
<label for = "cnfm-password">Confirm Pasword</label>
<input type="password" class = "input" id = "password2">
<input onclick = "verifyPassword()" type="submit" value = "Save Changes"class = "btn" id = "myBtn">
          
 <!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <img src="/images/logo.png" alt="SAMPLE" width="120" class = "mx-auto">
      <span class="close">&times;</span>
    </div>
    
    <div class="modal-body">
      <h4 class = "text-center"><span id = "message1"></span></h4>
    </div>
    <div class="modal-footer mx-auto">
      <button class = "btn" id = "confirm">Okay</button>

    </div>
  </div>
</div>
 function verifyPassword(){
    var pw1 = document.getElementById("password1").value;
    var pw2 = document.getElementById("password2").value;

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the button that opens the modal
    var btn1 = document.getElementById("myBtn");
    
    var confirm = document.getElementById("confirm");
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];


    btn1.onclick = function () {
        modal.style.display = "block";

        //check empty password field

        if(pw1 == "") {
            document.getElementById("message1").innerHTML = "*Please put your new password!";
            return false;
        }

        //minimum password length validation
        if(pw1.length < 8) {
            document.getElementById("message1").innerHTML = "**Password length must be atleast 8 characters";
            return false;
        }

        //maximum length of password validation
        if(pw1.length > 15) {
           document.getElementById("message1").innerHTML = "*Password length must not exceed 15 characters";
           return false;
        } else {
           if(pw1 == pw2){
               document.getElementById("message1").innerHTML=  "Passwords match!";
           }
        
           else {
               document.getElementById("message1").innerHTML=  "Passwords not match!";
           }
        }

    }
    
    confirm.onclick = function () {
        modal.style.display = "none";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
      }
  
      // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
          modal.style.display = "none";
    }
  }
    
} 

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  max-width: 40%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s
}

/* Add Animation */
@-webkit-keyframes animatetop {
  from {top:-300px; opacity:0} 
  to {top:0; opacity:1}
}

@keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

/* The Close Button */
.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: $color5;
  text-decoration: none;
  cursor: pointer;
}

.modal-header {
  
  background-color: $color1;
  color: white;
  text-align: center;
}

.modal-header h2 {
    color: $color1;
    text-align: center;
}

.modal-body {
    padding: 2px 16px;
  }

  .modal-body h4 {
      font-family: $font1;
      font-weight: normal;
      color: $color4;
      font-size: 20px;
  }

.modal-footer {
  padding: 2px 16px;
  color: white;
}

.modal-footer .btn {
    background-color: $color1;
    font-family: $font1;
    font-weight: normal;
    color: $color3;
}

.modal-footer .btn:hover{
    color: $color5;
}

xmlHttpRequest CORS from dev server [duplicate]

I have this get request to a server. This site is hosted on a dev server, but I want to point this get request to a production server.

var requestList = new XMLHttpRequest();  

requestList.onreadystatechange = function() {  
    if (requestList.readyState==4&&requestList.status==200) {  
        display(JSON.parse(requestList.responseText));  
    }  
};  
requestList.open('GET','<link/to/php/server>',true);  
requestList.withCredentials = true;  

I’m getting a cors error. But, I can run this request from something like PowerShell and it works with the following code:

$url = "<link/to/php/server>"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$response = $wc.DownloadString($url)
$df = ConvertFrom-Json $([String]::new($response))

The PowerShell code just uses windows credentials. Since the PowerShell code works, I know I should be able to query the production server. But how to do it with JavaScript XMLHttpRequest?

How to remove left join in function Knex.JS?

How to remove left join integration?

await knex.select().from("dishes")
            .leftJoin("companies", function () {
                if (companyId) {
                    this.on("dishes.companyId", "=", "companies.id")
                } else {
                    // I want to remove left join if companyId is false
                    return false;
                }
            })

node.js request returning only promise pending [duplicate]

I’m making a request from my front-end to an endpoint of node.js, and this service should make a request and return the result of this request to the frontend, but I’m getting as return the pending promises. When I use await with async, I’M getting the proxy time out, when I’M using .then I’m getting the pending promise. How I can solve this, any tips, please?

Node request:

const nodeRequest = async () => {

    const headers =  {
          'Content-Type': 'application/json',
          Accept: 'application/vnd.vtex.ds.v10+json',
          "REST-Range": "resources=0-100",
          'X-VTEX-API-AppKey': APP_KEY,
          'X-VTEX-API-AppToken': APP_TOKEN
        };
      
      try {
          const res = (await axios.get(`endpointxyz`, {
              headers: headers
          })).data;
          return res;
      }catch (e) {
          throw e;
      }
}

node func that return a answer to front-end request:

 routes: {
    hcheck: (ctx: ServiceContext<IOClients, State, ParamsContext>) => {
      
      
     
      setCacheContext(ctx)
      ctx.set('Cache-Control', 'no-cache')
      ctx.status = 200
      ctx.body = "OK"
      let res = nodeRequest().then(res => res) // return only Promise { <pending> } at the service terminal;
        ctx.response.body = res;
   
     
    },
  },
})

any tips on how I can solve this?