How to match a string from array of strings using javascript and regex?

Hi below is an array of strings,

const arr = [
    "list-domain/1/",
    "list-domain/1/list/1",
    "some-group/2/",
    "some-group/2/list/2",
    "list/3/",
    "list/3/item/1"
];

i want to return true if the string matches "list/1/" or "list-domain/2/list/2/" or "some-group/3/list/4" so basically should return true if string starts with "list/1/" or has some string in front and ends with "/list/1/" 

note:here the number after slash can be any number.

so for the above array expected output is true.

 const arr1 = [
    "list-domain/1/",
    "list-domain/1/list/1",
    "some-group/2/",
    "some-group/2/list/2",
];

for arr1 expected output true

 const arr2 = [
    "list-domain/1/",
    "list-domain/1/list/1/item/2",
    "some-group/2/",
];

for arr2 expected output is false.

i have tried something like below,

const foundMatch = arr.some(a=> new RegExp(/(/list/[0-9]+)?/$/g).test(a));

but this does return true also for strings not expected.

could someone help me with this. thanks.

Report the values of the table parameters in an external div for calling an html file with those parameters

I need your help. I have a dynamic content table with values.

I need these values to be reported in a div to then pass them to the function, as shown in the code below.

.
.
.
Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
<td>${item.id}</td>
<td><${item.n_a}</td>`;
  table.appendChild(child);
  document.querySelector('#my-table').appendChild(child);
})
<div class="split left">
  <div class="centered">
    <table id="my-table" width="90%">
      <tr>
        <th>Number</th>
        <th>Type</th>
      </tr>
    </table>

    <br>
    <br>

    <div class="buttons">
      <form action="save.html">
        <input type="submit" value="Add article part" />
      </form>

    </div>
  </div>
</div>

<div class="split right">
  <div class="centered">
    <br>
    <object data="editframe.html?id=${item.id}&n_a=${item.n_a}" width="700" height="500"> </object>
             </div>
         </div>

I tried as done in the code below but nothing is shown.

Is it possible to do this? If so, how can this be done?

How to print array data using map method in React JS?

Hello Community I am stuck at some point I am new at React JS. I want to call image file using map function. Only images not appear on the webpage.

Here is my Array.jsx file

const PhotoData = [
   
        {
            imgsrc: gallery_1
        },
        {
            imgsrc: gallery_4
        },
        {
            imgsrc: gallery_7
        },
        {
            imgsrc: gallery_10
        }
    ]

    const PhotoData1 = [
   
        {
            imgsrc: gallery_2
        },
        {
            imgsrc: gallery_6
        },
        {
            imgsrc: gallery_8
        },
        {
            imgsrc: gallery_12
        }
    ]

    const PhotoData2 = [
   
        {
            imgsrc: gallery_3
        },
        {
            imgsrc: gallery_5
        },
        {
            imgsrc: gallery_9
        },
        {
            imgsrc: gallery_11
        }
    ]

    export default [PhotoData,PhotoData1,PhotoData2];

also import the gallery images on above the code.

Here is my photos.jsx file where I write the code.

<div className='photo__header-grid'>
                <div className='grid-item'>
                    {
                        PhotoData.map((val,index)=>{
                            return(
                                <div className='gallery-item' key={index}>
                                    <img src={val.imgsrc} alt="gallery_1"/>
                                </div>
                            )
                        })
                    }
                </div>
            </div>

            <div className='photo__header-grid-1'>
                <div className='grid-item'>
                {
                        PhotoData1.map((val,index)=>{
                            return(
                                <div className='gallery-item' key={index}>
                                    <img src={val.imgsrc} alt="gallery_1"/>
                                </div>
                            )
                        })
                    }
                </div>
            </div>

            <div className='photo__header-grid-2'>
                <div className='grid-item'> 

                    {
                        PhotoData2.map((val,index)=>{
                            return(
                                <div className='gallery-item' key={index}>
                                    <img src={val.imgsrc} alt="gallery_1"/>
                                </div>
                                )
                            })
                    }
                </div>
            </div>

Images not appear on the web-page.
Thanks in advance.

Get working hours between dates while excluding weekends and holidays

I need to get working hours (8 hours) in date range excluding weekends and holidays, and my code below works fine with excluding weekends, but I can’t wrap my head around how to make it work with holidays as well.
This is quite brute force-ish approach and freezes the tab on execution, ideally I’d want to make the year dynamic or even just only check the month and the day ignoring the year.

Another thing I will have to consider after solving this issue is what to do if the weekend and the holiday are on the same day. Usually in our country if that is the case the government will “postpone” the holiday, for example:
Holidays are on sunday and saturday, then the next week’s monday and tuesday are going to be work free days.
Or sometimes if the holiday on wednesday, then it will be postponed to friday, so people can have 3 weekend days consecutively.

function workingHoursBetweenDates(startDate : Date, endDate : Date, dayStart : number, dayEnd : number, includeWeekends : boolean) {
// Store minutes worked
var minutesWorked = 0;
// Validate input
if (endDate < startDate) { return 0; }
// Loop from your Start to End dates (by hour)
var current = startDate;
// Define work range
var workHoursStart = dayStart;
var workHoursEnd = dayEnd;
// Loop while currentDate is less than end Date (by minutes)
var holidays = ['2021-01-01', '2021-01-02', '2021-03-08', '2021-03-21', '2021-03-22', '2021-03-23', 
            '2021-05-01', '2021-05-07', '2021-05-09', '2021-07-06', '2021-08-30', '2021-12-01', '2021-12-16', '2021-12-17']

while(current <= endDate) {
    // Store the current time (with minutes adjusted)
    var currentTime = current.getHours() + (current.getMinutes() / 60);
    // Is the current time within a work day (and if it
    // occurs on a weekend or not)
    for (var i = 0; i < holidays.length; i++) {
        var tempDate1 = new Date(current.setHours(0, 0, 0, 0));
        var tempDate = (new Date(holidays[i]));
        var tempDate2 = new Date(tempDate.setHours(0, 0, 0, 0));
        cd.console! += tempDate1.getTime() + 'n';
        cd.console! += tempDate2.getTime() + 'n';
        if (currentTime >= workHoursStart && currentTime < workHoursEnd 
                                        && (includeWeekends ? current.getDay() !== 0 
                                        && current.getDay() !== 6
                                        && tempDate1.getTime() === tempDate2.getTime() : true)) {
            minutesWorked++;
        }
        // Increment current time
    }                   
    current.setTime(current.getTime() + 1000 * 60);
}
// Return the number of hours
return (minutesWorked / 60).toFixed(2);     

}

I thought perhaps an abomination like this could work, putting this in an if statement:

(current.getMonth() !== 0 && current.getDate() !== 1) 
                        && (current.getMonth() !== 0 && current.getDate() !== 2)
                        /*Many many rows of the month and the day of the holiday*/
                        && (current.getMonth() !== 11 && current.getDate() !== 17)

That didn’t work as well.

Array content empty after taking input in text area

The inputs I am taking in the textarea are not reflecting in the console (Check code snippet)
:

Array(1)

content: “”

line: 0

Problem Statement – Table values -> Make JSON structure -> Pull/Push to db
Your app should read a JSON in the same structure, and populate values. And send a JSON in same structure to db.
For loading and saving

        $(document).ready(function(){
    var textarea = $('textarea').val();
    var linebreak = textarea.split('n');
    var length = linebreak.length;
    var data = [];
    console.log(length);
    for ( var i = 0 ; i<length ; i++){
          
        data.push({ 'line': i , 'content': linebreak[i] });
        console.log(data);
    }
});
  
<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="index.js" async></script>
<html>
    <head>
        <title>Basic Web Page</title>
    </head>
    <body>
        <textarea class="form-control ph" id="notes_inputbox" rows="5" placeholder=""></textarea>
        <textarea class="form-control ph" id="notes_inputbox" rows="5" placeholder=""></textarea>
        <textarea class="form-control ph" id="notes_inputbox" rows="5" placeholder=""></textarea>
        
    </body>
</html>

I made a responsive website and included a toggle menu, but it does not function

I’m trying to make a responsive website with a toggle menu, but it’s proving difficult. Because I’m a beginner at programming, I’ve included all of the code I’ve written thus far. This is my HTML header, which also includes other sections and divs, as well as the hamburger menu’s button:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website</title>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&family=Source+Code+Pro:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
        rel="stylesheet">
    <script src="https://kit.fontawesome.com/0b2eeb2fd2.js" crossorigin="anonymous"></script>
    <!-- <link rel="script" href="script.js"> -->
</head>

<body>
    <section class="header">
        <nav>
            <a href="index.html"><img src="./image/logo.png" alt="logo"></a>
            <div class="nav-links" id="navLinks">
                <i class="fas fa-bars" onclick="hideMenu()"></i>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">Service</a></li>
                    <li><a href="#">About us</a></li>
                    <li><a href="#">Contact us</a></li>
                </ul>
            </div>
            <i class="fas fa-bars" onclick="showMenu"></i>
        </nav>

        <div class="text-box">
            <h1>Lorem, ipsum dolor.</h1>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum explicabo ipsam quis, numquam voluptatem recusandae, repudiandae animi eligendi culpa provident soluta Repudiandae repellat adipisci ratione asperiores</p>
            <a href="#" class="hero-btn">similique rerum evenietodio?</a>
        </div>
    </section>

    <!-- Services -->
    <section class="services">
        <h1>Lorem, ipsum dolor.</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, dolorem.</p>

        <div class="row">
            <div class="img">
                <img src="https://images.unsplash.com/photo-1518614368389-5160c0b0de72?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NHx8a2lkcyUyMHBsYXlpbmclMjBiYXNrZXRiYWxsfGVufDB8fDB8fA%3D%3D&w=1000&q=80" alt="">
            </div>
            <div class="text">
                <small>Build a foundation</small>
                <h3>Remedial Education</h3>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorem reprehenderit magni maiores aperiam, esse facere perspiciatis saepe alias, non laudantium qui earum cupiditate consequuntur! Natus quam vitae fugit? Eveniet, distinctio.</p><br>
                <div class="button">
                    <button class="sec1don">Donate₹</button>
                    <button class="sec1vol">Volunteer</button>
                </div>

</body>

</html>

Also, here’s the CSS I’m attempting to implement:

        * {
            margin: 0px;
            padding: 0px;
            font-family: 'Open Sans', sans-serif;
            font-family: 'Source Code Pro', monospace;
        }
        /* BANNER */
        
        .header {
            min-height: 100vh;
            width: 100%;
            background-image: linear-gradient(rgba(4, 9, 30, 0.7), rgba(4, 9, 30, 0.7)), url(./eduford_img/banner.png);
            background-position: center;
            background-size: cover;
        }
        /* NAVBAR */
        
        nav {
            display: flex;
            padding: 2% 6%;
            justify-content: space-between;
            align-items: center;
        }
        
        nav img {
            width: 150px;
        }
        
        .nav-links {
            flex: 1;
            text-align: right;
        }
        
        .nav-links ul li {
            list-style: none;
            display: inline-block;
            padding: 8px 12px;
            position: relative;
        }
        
        .nav-links ul li a {
            color: #fff;
            text-decoration: none;
            font-size: 15px;
        }
        
        .nav-links ul li::after {
            content: '';
            width: 0%;
            height: 2px;
            background: #f44336;
            display: block;
            margin: auto;
        }
        
        .nav-links ul li:hover::after {
            width: 100%;
            transition: 0.5s;
        }
        /* TEXTBOX DIV */
        
        .text-box {
            width: 90%;
            color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }
        
        .text-box h1 {
            font-family: 'Source Code Pro', monospace;
            font-size: 62px;
        }
        
        .text-box p {
            margin: 10px 0 40px;
        }
        
        .hero-btn {
            display: inline-block;
            text-decoration: none;
            color: #fff;
            border: 1px solid #fff;
            padding: 12px 34px;
            font-size: 13px;
            background: transparent;
            position: relative;
            cursor: pointer;
        }
        
        .hero-btn:hover {
            border: 1px solid #f44336;
            background: #f44336;
        }
        
        nav .fas {
            display: none;
        }
        /* Services section */
        
        .services {
            width: 80%;
            margin: auto;
            text-align: center;
            padding-top: 100px;
        }
        
        .services h1 {
            font-size: 48px;
            font-weight: 700;
            font-family: 'Source Code Pro', monospace;
        }
        
        .services p {
            color: #777;
            font-size: 18px;
            font-weight: 300;
            line-height: 22px;
        }
        /* service section div 1*/
        
        .row {
            margin-top: 5%;
            display: flex;
            justify-content: space-between;
        }
        
        img {
            width: 25rem;
        }
        
        .text {
            display: block;
            margin: auto;
            padding: 0 0 0 2rem;
            text-align: left;
        }
        
        .text small {
            font-size: 1.5rem;
            color: rgb(155, 155, 155);
            text-transform: capitalize;
        }
        
        .text h3 {
            font-size: 3rem;
            font-family: 'Source Code Pro', monospace;
        }
        
        .text p {
            font-family: 'Open Sans', sans-serif;
            letter-spacing: .5px;
        }
        
        .text .button {
            text-align: center;
        }
        
        .button button {
            font-size: 22px;
            color: #777;
            background-color: #fff;
            border: 1px solid #777;
            border-radius: 5px;
            padding: 5px;
        }
        
        .button button:hover {
            color: #fff;
            background-color: #777;
            border: 1px solid #fff;
        }
        
        hr {
            margin-left: -40px;
            margin-right: -40px;
        }
        /* media queries */
        
        @media(max-width: 700px) {
            .text-box h1 {
                font-family: Source Code Pro;
                font-size: 20px;
            }
            .text-box p {
                margin: 10px 0 40px;
                font-size: 10px;
            }
            /* navbar */
            .nav-links ul li {
                display: block;
            }
            .nav-links {
                position: absolute;
                background: rgb(255, 255, 255, 0.2);
                height: 100vh;
                width: 200px;
                top: 0px;
                right: -200px;
                text-align: left;
                z-index: 2;
                transition: 1s;
            }
            nav .fas {
                display: block;
                color: #fff;
                margin: 10px;
                font-size: 22px;
                cursor: pointer;
            }
            .nav-links ul {
                padding: 30px;
            }
        }

I tried the following JS function:

                    // javascript for toggle menubar

                    var navLinks = document.getElementById("navLinks");

                    function showMenu() {
                        navLinks.style.right = "0";
                    }

                    function hideMenu() {
                        navLinks.style.right = "-200px";
                    }

I’m not sure what the answer is; any assistance would be highly appreciated, and please assist me as a rookie programmer.

How to extend X axis datetime in Highchart

Hi I am new to HighChart, I was trying to extend the x-axis of my graph which is a datatime showing date and month.
enter image description here

The issue here is I am getting dates on intervals of 1 day because of tickInterval: 24 * 3600 * 1000. My last entry of data point plotted on the graph is of 3rd Feb but the tickInterval skipping the date how can Is this possible to display +1 day before the data?
In short how can I show 4th February here?

My second concern is about the tickInterval of one day which is 86400000 milliseconds. How can I show days without skipping or giving interval?
Like Showing 1Feb, 2Feb, 3Feb 4Feb without skipping any day?

Below is my code for the following chart.

Highcharts.chart('container', {
                chart: {
                    type: 'spline'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        minute: '%H:%M',
                        hour: '%H:%M',
                        day: '%e. %b',
                        week: '%e. %b',
                        month: '%b '%y',
                        year: '%Y'

                    },
                    tickInterval: 24 * 3600 * 1000,
                    title: {
                        text: 'By Date'
                    },
                    labels: {
                        style: {
                            color: 'black',
                            fontSize: '11px'
                        }
                    }
                },
}

jquery button only works for first button?

I have a table of records. each table row has a submit button – when the submit button is clicked it makes a ajax request to the server. The first button works and request is sent to server. The next buttons do not work and the page refreshes each time when it should not. Any reason why this is happening ? I believe it is because i have an id on the button which references all records, but i am not sure.

Here is snippet of code:

$("#submitBtn").on('click', function(event) {

event.preventDefault();

var registerNo = $('#registerNo').val();
var date = $('#date').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var refNo = $('#refNo').val();
var attendance = $("#AttendanceValue option:selected").val();

var obj = {
    attendance : attendance,
    refNo : refNo,
    registerNo : registerNo,
    date : date,
    startTime : startTime,
    endTime : endTime
}

/*

$.ajax({
    url: "process.asp",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(obj),
    success: function (response) {
        alert(JSON.stringify(response));
    },
    error: function(response) {
        alert('There was an error: ' + response.responseText);
    }       
});

*/
console.log(obj); 
});

Why am I getting error when using expo-facebook login in React Native?

I have a managed workflow expo project (SDK 44) and I tried to follow the documentation to implement the solution. These are the steps I took:

  • Register to Facebook Developer
  • Install expo-facebook
  • Fetch key hash for android app and add it on Facebook
  • Added “host.exp.Exponent” as Bundle ID on Facebook
  • Added the sample code from the docs

enter image description here

enter image description here

async function logIn() {
  try {
    await Facebook.initializeAsync({
      appId: '<APP_ID>',
    });
    const { type, token, expirationDate, permissions, declinedPermissions } =
      await Facebook.logInWithReadPermissionsAsync({
        permissions: ['public_profile'],
      });
    if (type === 'success') {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
      Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
    } else {
      // type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

When I press my Button I get the following result in my Console: ExponentPushToken[_FnNNxPOoKSPcfwJ-A5z2J]

Then it redirects me to my App’s Facebook page, where I can see my app details, and image.

After I add my Facebook credentials I get the following error:

Webpage not available The webpage at
fbconnect://cct.host.exp.exponent#granted_scopes=public_profile&denied_scopes=&signed_request=VhUPKkgri83xZuKbpsop5XFf4sLD72HeFHn5mgHKtTY.eyJ1c2VyX2lkIjoiNTA0MzMwNTUyMjM2MDIyNiIsImNvZGUiOiJBUUFuY2h5dTl4dWNKNEdQbWc5S0NGTXNwb1p3bVJURDRuX3NOaGt4ZHJUZGEyNGZOdDVQamFBbXNkQXN2R1E3YlBkN0lWZnlPUl9KYThnSFExcXU1ZDhkTWF1UnJiajRZenZtbDlIamRXYkY1b1I1VUtBUk92SzdPOGRQcWJtd1hkeTdPNVhQb2VOZ2QtZjdpYkwwWF9aYUNNbjhWWDk5VEtnQVZralI3MGVmNzFVTnBscW5EdERUWWdpR3llVkloOXM5eTN2SC1wdWNublRnYW9qaGRBeFktUEVrM1ZWUTZoRGNvZUhmbXRiRkdyMTFnN2ZDTmxIWkUtY3pDSW5MMTdhZ20xX2o0NS1CRExVek96ZkFBdVVUXzBkd0tydTJacEVETnVXMy1wN0FPcjFtcGdXNlBPWDhCZEI2MFZyRzhNOXJOcmpKWlBLNU13ZEtSQXF1SXJ5UEItZjBrV0VFVVVYU3Y2czFLY2d2SXFPZHNQZ2tsYmk0NXM2eHF4SklMVjdQc09ueF9hZFJ2aGZrbkI0RmJuOEoiLCJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTY0Mzk2NzY5MX0&graph_domain=facebook&access_token=EAAPYJXwv3ysBAN0gNls0mMoJ9NoZBbRvOQYMyaAqwlfHL7vcZA1ZAq4jPJsZBZCZCc5qG6sWSBY5w7Xc4ZArScfi6bvIA7brKz4S4AtWUDLyw71hfmnHYckdi1fLSqRLZBxfVfEGDPz9W5ZBFxHsScpoFXI4EzTwis11hiD58yLXubhnn5JZBm08Fje7FhI0DbTBZA0AZAFgObcLC0s75ZCTQ7SaZAPKLRT3W0kAiAAi2eolUntXy6gslYKEYY&data_access_expiration_time=1651743691&expires_in=5182128&state=%7B%220_auth_logger_id%22%3A%228315c2f8-8e7f-42c5-8496-5d45fd1f1f25%22%2C%223_method%22%3A%22custom_tab%22%2C%227_challenge%22%3A%22b4as3835lr367tdn0m0n%22%7D
could not be loaded because:

net::ERR_UNKNOWN_URL_SCHEME

enter image description here

What am I doing wrong? :/

Getting the values from a JSON

each entry in the JSON, looks like this:

{
  "ALBA": [
    {
      "name": "ABRUD",
      "zip": "515100",
      "lat": "46.274675",
      "long": "23.065029"
    },
    {
      "name": "ABRUD-SAT",
      "zip": "515101",
      "lat": "46.283967",
      "long": "23.061093"
    },
}

The first object is the county name, I have more of them, but I just gave an example, the nested objects are the cities. What I want is a way to display them in a select tag in HTML, but I can’t manage to do it.

I have the following code, until now:

const getCities = () => {
    JSON.parse(JSON.stringify(regions));
    // Object.keys(regions).map(function(key, index) {
    //   console.log(regions[key]);
    // })
    for (const region in regions) {
      console.log(region); //this returns exactly what i want
    //cities.push(region)
    }
  }
  getCities();

And in html:

<div>
            <select name="city">
              <option value={cities}>{cities}</option>
            </select>
</div>

How can I make this select tag return me exactly the counties and how to make another one to show me the cities name based on the selected county?

How to simulate eval() in JavaScript?

In a browser environment, I hope to know the execution result of a script for a testing purpose.

Suppose my script is 1+1; 2+2;. I can use eval() to get its execution result:

console.log(eval("1+1; 2+2;"));

The output is 4.

If I just use Chrome’s console and type in 1+1; 2+2;, the console also outputs 4.
enter image description here

May I ask is it possible to know the execution result without using eval?

console.log(1+1; 2+2;); // This line is only for illustration. It will throw a SyntaxError

Invalid hook call issue while calling a webpack

I got following error while running the react app with webpack
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

1.You might have mismatching versions of React and the renderer (such as React DOM)
2.You might be breaking the Rules of Hooks
3.You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.

I have resolved the issue by adding peerDependencies in package.json

"peerDependencies": {
    "react": ">=16.8.0",
    "react-dom": ">=16.8.0"
},

Also need to add the following to Webpack’s config

externals: {
  react: "commonjs react",
  "react-dom": "commonjs react-dom",
},

Hope this should resolve your issue, it works well for me.

Youtube iframe is not working on mobile browser

for run this code using local environment like vs-code etc.

this snippet working on a computer browser properly when I open the same page using IP on my mobile browser I got an error. I don’t know why but does anyone has a solution provided in the answer section.

//YouTube embed with YouTube Iframe API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTube embed player details
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "668nUCeBHyY",

    //Features
    playerVars: {
      controls: 0,
      rel: 0,
      disablekb: 1,
    },
  });
}

//functions
function playYT() {
  player.playVideo();
}

function pauseYT() {
  player.pauseVideo();
}
<div style="pointer-events:none" id="player"></div><br><br>
<button onclick="playYT()">Play</button>
<button onclick="pauseYT()">Pause</button>