How to Android WebView video fullscreen lock orientation

Screen orientation lock (screen.orientation.lock()) is not working in android webview.

function lockLandScape() {
    console.log(JSON.stringify(screen.orientation.lock))
    if (screen.orientation && screen.orientation.lock) {
      screen.orientation.lock('landscape');
    }
}
function unlockLandScape() {
    if (screen.orientation && screen.orientation.unlock) {
        screen.orientation.unlock()
    }
}   
function videoFullScreen(elem){
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { 
      elem.msRequestFullscreen();
    }
    elem.classList.add("fullscreen");
    lockLandScape()
}

Where elem is video element in webview.

JavaScript: How to move through my question array

I am really stuck! As a newbie, I am trying to build a guessing game for Flags of the World.
I have an array of objects which I want to shuffle. I then want to select the correct country that matches the image and add that to three answer buttons. Currently I am doing this by creating variables using a fixed index from the shuffled array for the currentFlagIndex (correct) and wrongFlagIndex (wrong) and anotherWrongIndex (also wrong).
I then want to check for a ‘correct’ or ‘wrong’ answer and then for the user to click ‘next’ which would load the next ‘correct’ country and image and two ‘incorrect’ countries from my array of objects.
I can make this all work once, as per the code below, but I am completely stuck on how to move to the ‘next’ question.
I am running this all against a 60 second timer. I have the timer counting down, but have not attempted to put a check in to ensure this is not at zero (I will do that once I know how to move my questions on).

Flags Array extract:

const flags = [
{ 
    image: 'assets/images/ad.webp',
    country: 'Andorra',
},
{ 
    image: 'assets/images/ae.webp',
    country: 'United Arab Emirates',
},
{ 
    image: 'assets/images/af.webp',
    country: 'Afghanistan',
},

Game JavaScript:

const startButton = document.getElementById('start-button');
const nextButton = document.getElementById('next-button');
const answerButtons = document.getElementById('answer-buttons');

nextButton.addEventListener('click', buildNextQuestionArray);
/**
 * Set 60 second countdown timer. Code modified from Grepper: https://www.codegrepper.com/code-examples/javascript/add+countdown+timer+to+javascript+quiz
 */
let count = 60;
let interval = setInterval(function () {
    document.getElementById('timer').innerHTML = count;
    count--;
    if (count === 0) {
        clearInterval(interval);
        document.getElementById('timer').innerHTML = 'GAME OVER'; // this is where I can add what to do once the timer ends - take to the GAME OVER score html page
    }
}, 1000);

/**
 * Function to randomly sort array modified from: https://www.codegrepper.com/code-examples/javascript/how+to+randomly+sort+an+array+javascript 
 */
function createNewFlags(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

let newFlags = createNewFlags(flags);
console.log(newFlags[0].country);

let currentFlagIndex = 0;
console.log(newFlags[currentFlagIndex]);

let wrongFlagIndex = 12;
console.log(newFlags[wrongFlagIndex]);

let anotherWrongFlagIndex = 21;
console.log(newFlags[anotherWrongFlagIndex]);

/** 
 * Create an array of the correct answer and two wrong answers
 **/
function buildFullAnswerArray() {
    let fullAnswerArray = []; {
        fullAnswerArray.push(newFlags[currentFlagIndex].country);
        fullAnswerArray.push(newFlags[wrongFlagIndex].country);
        fullAnswerArray.push(newFlags[anotherWrongFlagIndex].country);
    }
    return fullAnswerArray
}

let allAnswers = buildFullAnswerArray();
console.log(allAnswers);

/** 
 * Shuffle the allAnswers array so that the order of the countries in the answers will be randomised
 **/
function createShuffledAnswers(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

let finalAnswers = createShuffledAnswers(allAnswers);
console.log(finalAnswers);


    document.getElementById('flag').src = newFlags[currentFlagIndex].image;

    let answer1 = document.getElementById('answer-1');
    let answer2 = document.getElementById('answer-2');
    let answer3 = document.getElementById('answer-3');

    answer1.innerText = finalAnswers[0];
    answer2.innerText = finalAnswers[1];
    answer3.innerText = finalAnswers[2];

    answer1.addEventListener('click', checkAnswer);
    answer2.addEventListener('click', checkAnswer);
    answer3.addEventListener('click', checkAnswer);


/** 
 * Check button onclick whether correct answer or not - event listener
 * If correct - return 'CORRECT!' and change the body color to green
 * If incorrect - return 'WRONG!' and change the body color to red
 **/

function checkAnswer() {
    if (this.textContent === newFlags[currentFlagIndex].country) {
        let correct = true
        let correctAnswer = `CORRECT!`
        document.getElementById('result').innerHTML = correctAnswer;
        setStatusClass(document.body, correct);
        increaseScore();
    } else {
        let wrong = false
        let wrongAnswer = `WRONG!`
        document.getElementById('result').innerHTML = wrongAnswer;
        setStatusClass(document.body, wrong);
    }
    nextButton.classList.remove('hide');
    answerButtons.classList.add('hide');
}

/**
 * Gets the current score from the DOM and increments it by 1
 */
function increaseScore() {
    let currentScore = parseInt(document.getElementById('correct').innerText);
    document.getElementById('correct').innerText = ++currentScore;
}
/**
 * Adds a class to the body depending on whether the answer is correct or wrong. Allows the body color to be changed depending on correct or wrong answers.
 * Adapted from Web Dev Simplified YouTube Video: https://www.youtube.com/watch?v=riDzcEQbX6k
 */
function setStatusClass(element, correct) {
    clearStatusClass(element)
    if (correct) {
        element.classList.add('correct')
    } else {
        element.classList.add('wrong')
    }
}

/**
 * Resets class status on body. Used when setting the nextQuestion()
 * Adapted from Web Dev Simplified YouTube Video: https://www.youtube.com/watch?v=riDzcEQbX6k
 */
function clearStatusClass(element) {
    element.classList.remove('correct')
    element.classList.remove('wrong')
}

function resetState() {
    clearStatusClass(document.body);
    nextButton.classList.add('hide');
}

// function buildNextQuestionArray() {
//     currentFlagIndex = ++currentFlagIndex;
//     wrongFlagIndex = ++wrongFlagIndex;
//     anotherWrongFlagIndex = ++anotherWrongFlagIndex;
//     let nextQuestionArray = []; {
//         nextQuestionArray.push(newFlags[currentFlagIndex].country);
//         nextQuestionArray.push(newFlags[wrongFlagIndex].country);
//         nextQuestionArray.push(newFlags[anotherWrongFlagIndex].country);
//     }
//     return nextQuestionArray
// }

// let nextAnswers = buildNextQuestionArray();
// console.log(nextAnswers);

I have commented out the above code as it will generate a new array of three but it also causes the current correct answer to return wrong, so must be changing the variables.

I think I have a problem where I am inserting the answer text and image outside of a function, but I have tried many things here, which all return errors.

Game HTML:

 <!-- GAME AREA -->
    <div class="container">
        <div id="timer"></div>
        <div id="flag-container" class="flag"><img src="" id="flag"></div>
        <div id="answer-buttons" class="answer-box">
            <button class="btn" id="answer-1">Country 1</button>
            <button class="btn" id="answer-2">Country 2</button>
            <button class="btn" id="answer-3">Country 3</button>
        </div>
        <div id="result" class="result"></div>
        <!-- <div class="answer-box"><button class="start-btn" id="start-button">Start >></button></div> -->
        <div class="answer-box"><button class="next-btn hide" id="next-button">Next flag >></button></div>
        <div class="score">Score: <span id="correct" class="score">0</span></div>
    </div>

    <!-- SCRIPTS -->
    <script src="assets/js/flags.js"></script>
    <script src="assets/js/game.js"></script>

I have a solution where I can add two incorrect answers to my flags array, but that seems like a long-hand (there are 216 flags!) way to ‘solve’ this problem. I have all of the parts, I just need someone to help me move through the array to the next flag please!

The latest version of the full code is also deployed here: Git Hub

I am sure there is a lot wrong with my code, but any straightforward help to move me on would be much appreciated!

how to conditionally apply text to data variable based on props in VueJS

How can I conditionally apply value to the data variable based on props, the ternary operator is generating error, I would like to refer to this code:

<template>
  <div class="absolute left-3 top-1/2">
    <img
      :src="hamburgerUrl"
      style="width: 25px; cursor: pointer; transform: translateY(-50%)"
      alt="toggle menu button"
    />
  </div>
</template>

<script>
export default {
  name: "HamburgerMenu",
  props: ["white"],
  data: {
    hamburgerUrl: this.white
      ? "/gfx/hamburger-white.png"
      : "/gfx/hamburger-menu.png",
  },
};
</script>

and I get the error saying :

TypeError
Cannot read property 'white' of undefined

I have tried to validate the props and set it to not required like so:

  props: {
    white: {
      type: Boolean,
      required: false,
      default: false,
    },
  },

But it didn’t help, what am I doing wrong?
Thanks

Animate accordion plugin with auto height

I am using a very lightweight plugin which is great but I can’t get it to animate withut a fixed height.

I initally tried the usual transitions before realising they did not work with auto height

I tried modifying some JS I found but this did not work

var headers = document.querySelectorAll('.aab__accordion_head');

for (var i=0; i<headers.length; i++) {
  headers[i].addEventListener('click', toggleDisplay);
}

function toggleDisplay() {
  if (this.parentNode.classList.contains('aab__accordion_body--show')) {
    var currentlyDisplayed = document.querySelectorAll('.aab__accordion_body--show');
    for (var e=0; e<currentlyDisplayed.length; e++) {
      currentlyDisplayed[e].classList.remove('aab__accordion_body--show');
    } 
  } else {
    this.closest('.aab__accordion_body').classList.add('aab__accordion_body--show');
  }
}

I also tried a suggestion of using ScaleY like this

.wp-block-aab-accordion-block .aab__accordion_body {
    transform: scaleY(0);
    display: 
    transition: scale 300ms ease-in-out !important; 

}


.wp-block-aab-accordion-block .aab__accordion_body.aab__accordion_body--show {
    transform: scaleY(1);
    transition: scale 300ms ease-in-out !important; 
}

But this still reserves the space where it should be and doesn’t work.

I’ve tried this too but with no luck

.aab__accordion_container  {
    display: grid !important;
}

.aab__accordion_head:hover + .aab__accordion_body--show {
    display: flex !important;
    flex-direction: column !important;
}

.aab__accordion_container p {
    flex-basis: 0;
    overflow: hidden;
    transition: 1s;
}

I will actually have Gutenberg blocks in there too but I just thought i would test to see if I could get the

to show

The accordion panel is here

tinyurl.com/4afdnpkm

Any help would be appreciated

Thanks

How do I send data to HTML with Web Scraping technique?

I pulled a data from another site using the puppeteer command with JavaScript. When I run the code, the data comes to the terminal. However, I am building a website with HTML. And I cannot send this data to HTML. In fact, it gives me an error in the inspect section of the website I have made: “require(‘puppeteer’);” Uncaught ReferenceError: require is not defined.

const puppeteer = require('puppeteer');//The place that gives an error in the Inspect section.
async function scrapeProduct(url) {

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);

    const [ element ] = await page.$x('//*[@id="cur-moon-percent"]');

    const text = await element.getProperty('textContent');
    const textValue = await text.jsonValue();

    document.getElementById('test').innerHTML = textValue();//Where I am trying to post the code to HTML.
    //To see if the code works, delete line 13 and replace it with Console.log(textValue);

    browser.close();
};
scrapeProduct('https://www.timeanddate.com/moon/phases/turkey/istanbul');
<!DOCTYPE html>
<html lang="en">
<body>
  <div id = "test"></div> <!--A rendered HTML to see if the data is gone.-->
</body>
</html>

How to if elase function for following?

I need help to create function to enable option disable other remaining options. For suppose id product price is fall between 5000 to 10000 then it allows to choose only option that has 5000 to 10000 and remain will disable and Price in between 10000 to 20000 and it only allow respictive option to choose.
Please check below image for the options

option filed for user

What is the meteorJS Template Engine?

I’m working with meteor JS for a project.
And i have a question about this framework.

I can’t find the Template Engine of meteor, and the difference with Blaze.
Because when i’m looking the purpose of Blaze, i have Blaze is a powerful library for creating user interfaces by writing reactive HTML templates. Basically it’s a front end rendering system.

But if Blaze is just rendering templates, what is the Engine ?

Wait sometime before loading a widget onto a page

I’m new to programming and the following code I got through an open source project.

I’m loading a widget on a website. So instead of immediately loading the widget, I want it to take 10 secs before showing the widget.

I was wondering what is the right way to achieve it?

Entire code below…………

switch (methodName) {
            case 'init':

                const loadedObject = Object.assign(defaultConfig, item[1]);
           
                // the actual rendering of the widget
    
                const wrappingElement =
                    loadedObject.element ?? win.document.body;
                targetElement = wrappingElement.appendChild(
                    win.document.createElement('div')
                );
                targetElement.setAttribute('id', `widget-${instanceName}`);
                render(targetElement, loadedObject);

                // store indication that widget instance was initialized
                win[`loaded-${instanceName}`] = true;
                break;
    
            default:
                console.warn(`Unsupported method [${methodName}]`, item[1]);
        }

    }

How to add the values ​in an array of objects depending on the date value of each object

I have this array:

[{start_date: "2022-12-05T04:00:00Z" ,distance: 1000, time: 3600} 
,{start_date: "2022-02-07T04:00:00Z" ,distance: 1500, time: 6400},
{start_date: "2022-12-08T04:00:00Z" ,distance: 1000, time: 1300}]

I want to add the distance and time values ​​grouping them by the month indicated by the start_date value. For example, if two start_dates have the same month 2022-12-01 and 2022-12-08, how can I add the distance and time values ​​of those two months?

so i get a new array like this:

 [{month: 12 ,total distance: 2000, total time: 4900}, 
  {month: 02 , total distance: 1500, total time: 6400} ]

Close Modal with JavaScript

I’m trying to close my modal when add to cart button is clicked.

here is the code for the button to close:

<button class="btn btn-info btn-block addItemBtn" id="closemodal" >&nbsp;Add to cart</button>

here is the javascript code:

          $(document).ready(function() {

            // Send product details in the server
            $(".addItemBtn").click(function(e) {
              e.preventDefault();
              var $form = $(this).closest(".form-submit");
              var pid = $form.find(".pid").val();
              var pname = $form.find(".pname").val();
              var pdesc = $form.find(".pdesc").val();
              var pprice = $form.find(".pprice").val();
              var pcode = $form.find(".pcode").val();
              var pqty = $form.find(".pqty").val();

              $.ajax({
                url: 'action.php',
                method: 'post',
                data: {
                  pid: pid,
                  pname: pname,
                  pdesc: pdesc,
                  pprice: pprice,
                  pqty: pqty,
                  pcode: pcode
                },
                success: function(response) {
                  $("#message").html(response);
                  window.scrollTo(0, 0);
                  load_cart_item_number();
                }
              });
              $('#closemodal').click(function() {
                $('#modalwindow').modal('hide');
              });
            });
         });

When I clicked the add to cart button that I want is added to cart but the modal is still open. I want it to automatically closes when the button is clicked.

Issue with state variables of a class and dictionaries inside a constructor

I have to instantiate the class obj1, which returns a dict, and pass this object into another instantiation of a class like this:

const obj1 = new Class1() 
const obj2 = new Class2({ obj1, id: 8 })

This works fine, but the problem comes when i wrap this process into a class.

Class X () {
    constructor(newId) {
    this.obj1 = new Class1()
    this.obj2 = new Class2({this.obj1, id: newId})
    }
}

This time it throws Referenceerror: obj1 is not defined when i instantiate the class.

I think it’s because node tries to read this.obj1 as this:obj1 since we are in the context of a dict.

This might seem stupid but I’m stuck.
Any help ?

Get a value from an object inside an object

How do I get the id 43 from country ?

"hq_locations":[{"id":1886112,"address":"10 Rue Laurencin, 69002 Lyon, France","street":"Rue Laurencin","street_number":"10","zip":"69002","lat":45.7527311,"lon":4.8321804,"country":{"id":43,"name":"France","lat":46.227638,"lon":2.213749,"trade_register_office":"Info Greffe"}

I get an empty error when submitting multiple forms with file uploads with ajax in laravel

my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file.
File is empty error. I’ve been dealing with this for 2 days, there is no method I haven’t tried, please help me.
Apart from that, I added multipart to the form, but it still didn’t work, I’m sharing my codes with you.

Sorry for my bad english.

I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn’t succeed.
It sends it to Laravel server side as [Object File].
My Form

<form class="form" id="createProduct4" method="POST" action="">
<input type="file" class="upload-box-title" id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file" class="upload-box-title" id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>

My blade ajax:

function createProducts()
{
    var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
    let photo = document.getElementById("urun-dosyasi").files[0];
    let photo2 = document.getElementById("urun-fotografi").files[0];
    console.log(photo,photo2);

    $.ajax({
        url: "{{ route('user.product.create') }}",
        type: "POST",
        data: dataString+"&urun_dosyasi="+photo+"&urun_fotografi="+photo2,
        success: function( data ) {
            $('#submit').html('Submit');
            $("#submit"). attr("disabled", false);
            Swal.fire({
                title: "Bilgi mesajı!",
                html: data,
                showConfirmButton: true
            })
        },
        error: function(xhr)
        {
            console.log(xhr);
            var err = JSON.parse(xhr.responseText);
            Swal.fire({
                title: "Hata!",
                html: err.message,
                icon: 'error',
                showConfirmButton: true
            })
        }
    });
}

Server Function

 public function createProduct(Request $request)
{
    $file = $request->file('urun_dosyasi');
    $file2 = $request->file('urun_fotografi');
    $filename = $file->getClientOriginalName();
    $extension = $file->getClientOriginalExtension();
    $filename2 = $file2->getClientOriginalName();
    $extension2 = $file2->getClientOriginalExtension();

    echo $filename,$extension."2. doc: ".$filename2.$extension;
}

Javascript error:

Screenshot a error image