Customize exit operation when closing tab or browser

Hi i’m trying to customize the operation made when a tab/browser is closed on my software.
I’ve found a script that stop the execution of the closing operation and display a popup that ask to confirm the exit intent:

<script type="text/javascript">
    window.addEventListener('beforeunload', function(e) {
        e.preventDefault();
        e.returnValue='';
    });
</script>

I want to make this script execute other operation like showing a confirm dialog, but cant figure out how to make it. I want something like

<script type="text/javascript">
    window.addEventListener('beforeunload', function(e) {
        e.stopClosing();
        //Show confirm dialog
    });
</script>

I’m using Primefaces and JSF. Thanks

Nuxt Dynamic routes returns 404 after static generation

guys. I have a shop page with two params: page and sort. like below:

example.com/shop/
example.com/shop/page/2/
example.com/shop/sort/newest/
example.com/shop/sort/oldest/page/2/

this is my route configs:

router: {
    extendRoutes(routes, resolve) {
      routes.push(
        {
          path: '/shop/sort/:sort/page/:page(\d+)',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-sort-page',
        },
        {
          path: '/shop/sort/:sort',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-sort',
        },
        {
          path: '/shop/page/:page(\d+)',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-page',
        },
      )
    }
},

Now, after i generate my website, Nuxt doesn’t generate sort pages. when i go to /sort/ or /sort/oldest/page/2/ it returns 404.

what do I need to do?
if I need to generate all these pages by myself, then what are these routes.push() used for?

I also want to add “name” and “filter” params. you see generating a dynamic route for all these parameters is impossible. what can I do?
thanks.

Trying to toggle a form using querySelector and it just isn’t budging

I was trying to toggle a modal for my register and login tabs on a website I’m working on, but the final part turning it from hidden to visible on the website I was using a little javascript to add an “active” class to the forms making it so they then appear and whatnot… help 馃檪

code:

CSS:

.login-form{
color: white;
text-align: center;
position: absolute;
top: 20%;
left: 37.5%;
transform: transform(-50%,-50%);
background: black;
border-radius: 15px;
box-shadow: 3px 3px 10px 1px rgba(0, 0, 0, 2);
visibility: hidden;
transform: .2s;

}

.login-form.active{
top: 50%;
transition: .2s;
visibility: visible;

}

.container-fluid.active{
filter: blur(20px);
transition: .2s;
pointer-events: none;

}

HTML:
Form –

<div class="login-form">
    <div class="form">
        <div class="closeBTN" onclick="loginToggle()">&times;</div>
        <div class="title">
            <h1>Login</h1>
        </div>
        <form action="loginConfig.php">
            <input type="email" placeholder="Email" required>
            <input type="password" placeholder="Password" required>
            <input type="submit" value="Login">
        </form>
    </div>
</div>

Navbar portion:

<div class="login">
                <ul>
                    <li onclick="registerToggle()">Registar-se</li>
                    <li onclick="loginToggle()">Login</li>
                </ul>
            </div>

JS:

  function loginToggle() {
        var container = document.querySelector('.container-fluid');
        container.classlist.add('active');
        var popup = document.querySelector('.login-form');
        popup.classlist.add('active');
    }

In order to be iterable, non-array objects must have a [Symbol.iterator]() method

I don’t find where is the error… I think the problem is on the useState declaration.
The first objective is be able to show an alert on the screen asking for tracking permissions in the App.

import { Text, StyleSheet, View, Alert } from 'react-native';
// import { requestTrackingPermissionsAsync } from 'expo-tracking-transparency';
import {
  getTrackingStatus,
  requestTrackingPermission,
  TrackingStatus,
} from 'react-native-tracking-transparency';
import Cosa from './cosa';
const App = ()=> {
  
  const [trackingStatus, setTrackingStatus] = useState<TrackingStatus | '(loading)'>('(loading)');
  useEffect(() => {
    getTrackingStatus()
      .then((status) => {
        setTrackingStatus(status);
      })
      .catch((e) => Alert.alert('Error', e?.toString?.() ?? e));
  }, []);

  return (
    <View style={styles.container}>
      <Cosa />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App;

Vue JS: API call request on app.vue in single page application

in my project i’m suffering from delay in API requests and that’s because i have huge amount of data in API, so i added a cache but it still appears white page when page creates, so i was thinking of adding API call on app.vue so request will be faster… is there a way to do it?
now i’m making API request on each page in my project
code below:

import BuildingsService from "../../../services/ApiService"
export default {

    data() {
        return {
  
buildings:[],
   
        };
    },

//API call, reponse saved in this.buildings
           BuildingsService.getBuildings().then((response) => {
            this.buildings = response.data.response;
 
        });
    }
}
<template>
<b-card no-body class="bg-default shadow">
    <h2>({{Building.building_number}}) B info</h2>
    <b-table-simple responsive>

        <b-thead>
            <b-tr>
                <b-th sticky-column class="table-title">floors </b-th>

            </b-tr>
        </b-thead>
        <b-tbody>
            <b-tr v-for="(floor, floor_index) in Building.floors" :key="floor_index">
                <b-th sticky-column>{{floor.floor_number}}</b-th>

                <b-th v-for="(flat, index) in Building.flats" :key="index" v-show="floor._id == flat.floor">
       
                    {{flat.flat_number}}
       

                    <b-icon v-if=" roles === 'User' && flat.status === '賲鬲丕丨'" icon="pencil-square" aria-hidden="true" @click="GotoFlatDetail(flat._id)"></b-icon>

                    <b-icon v-if="roles === 'Admin'" icon="pencil-square" aria-hidden="true" @click="GotoFlatDetail(flat._id)"></b-icon>
<b-row>
 <span class="size-text">{{flat.directions}} </span>
</b-row>
<b-row>
 <span class="size-text">{{flat.size}} {{flat.size_unit}}</span>
</b-row>
          
             <b-row>
                         
                  
                           <p  :class="{ 'text-green': flat.status=='available', 'text-red': flat.status=='sold', 'text-yellow': flat.status=='booked' }"> {{ flat.status }}</p>
                                      <a   v-show="flat.status=='sold' || flat.status=='booked'"><i class="fa fa-info-circle" aria-hidden="true" @click="showModal(flat._id)"></i></a>
                 </b-row>
             
                </b-th>

            </b-tr>
        </b-tbody>
    </b-table-simple>


</b-card>
</template>

app.vue:

<template>
  
<router-view :number="count" @send="getNewCount"   @reset="onReset">

<sidebar :number="count" @reset="onReset"/>

</router-view>
</template>
<script>

export default {
components: {
    sidebar,

  },
    data() {
        return {
      };
        
    },
    mounted(){ 
    // i wanted to add API call here and use it in other pages
   
    }
}
</script>

can i add saved API request array in app.vue and use it on other pages? and is it gonna improve my API call?

thanks in advance

How to use local variable as global [duplicate]

I have been working with some coordinates.Now I need to use x and y out of this function.
This is code from w3schools but I have something like this.

<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
}
</style>

<div onmousemove="myFunction(event)"></div>

<p id="demo"></p>

<script>
function myFunction(e) {
  var x = e.clientX;
  var y = e.clientY;
  var coor = "Coordinates: (" + x + "," + y + ")";
  document.getElementById("demo").innerHTML = coor;
}

Interactive Video Program Lagging

it’s my first question here and I really need your help about an interactive video.
I put a tag in the HTML, and depending on which button I click, the source of the video changes to play the next one. The problem is that at some point an almost infinite loop is created and the buttons take longer and longer to appear. I have to show this video to my brother-in-law for his birthday which is Saturday, and I really need help fixing this problem.

Here is the whole code, the sentences are in French, but you should still understand what is going on.

https://github.com/DonGiuliani/Video-Interactive

I am trying to make a responsive nav bar

I have the idea of having the anchor tags show up when they’re set to active and I have tried using JavaScript to access them and make them active when clicking on a div/button (I tried with button but it didn’t work out.).

The problem is that nothing happens. I ran through my code and didn’t find where I can be wrong.

Index.html:

<!DOCTYPE html>
<html>
<head>
<title>袧邪褔邪谢芯</title>
<link rel="shortcut icon" type="image/png" href="favicon.jpg">
<link rel="stylesheet" href="IndexStyle.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="ResponsiveMenu.js" defer></script>
<script src="https://kit.fontawesome.com/d2896764d5.js" crossorigin="anonymous"></script>
<script src="ResponsiveMenu.js" ></script>
</head>
<body>
<center>
<nav class="nav">
        <div class="dot_a" style="pointer-events: none;">
        <span class="dot" style="background-color: transparent; width: 5px; height: 5px;"></span>
        <span class="dot" style="background-color: #ff4757;"></span>
        <span class="dot" style="background-color: #ffa502"></span>
        <span class="dot" style="background-color: #2ed573;"></span>
        </div>
        <a class="anchors" href="Index.html"><i class="fas fa-house-damage"></i>&nbsp;&nbsp;袧袗效袗袥袨</a>
        <a class="anchors" href="HtmlPage.html"><i class="fas fa-code"></i>&nbsp;&nbsp;HTML&CSS</a>
        <a class="anchors" href="#"><i class="fas fa-tools"></i>&nbsp;&nbsp;袠袧小孝袪校袦袝袧孝袠</a>
        <a class="anchors" href="#"><i class="fas fa-thumbtack"></i>&nbsp;&nbsp;袟袗袛袗效袠</a>
        <a class="anchors" href="#""><i class="far fa-address-card"></i>&nbsp;&nbsp;袟袗 袧袗小</a>  
    </nav>
</center>
<center>


</body>
</html>

IndexStyle.css:

body {
    background-image: url(1.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
    margin: 0;
}

.pro_column1{
  width: 15%;
}

.pro_column2{
  width: 85%;
}

.nav {
  overflow: hidden;
  background-color: white;
  /*opacity: 60%;*/
  margin: 10px;
  border-radius: 10px;
  width: 850px;
    /*background:#3c6382;
  /*box-shadow:0px 5px 20px rgba(0,0,0,0.1);*/
    /*border: solid black 2px;*/

}


.nav a {
  /*float: right;*/
  color: #747d8c;
    /*display: block;*/
  text-align: center;
    padding: 35px 10px;
  text-decoration: none;
  font-size: 17px;
    margin: 0;
  border-radius: 10px;
  transition: 1s;
  /*justify-content: center;*/
    /*position: fixed; /* or absolute */
}

.anchors {
   /*float: right;*/
  color: #747d8c;
    /*display: block;*/
  text-align: center;
    padding: 35px 10px;
  text-decoration: none;
  font-size: 17px;
    margin: 0;
  border-radius: 10px;
  transition: 1s;
  /*justify-content: center;*/
    /*position: fixed; /* or absolute */
}

.nav a:hover {
  background-color: #ddd;
  color: black;
  -webkit-animation: 1s ease-in forwards;

}

.dot_a{
  /*float: right;*/
  color: #747d8c;
    /*display: block;*/
  text-align: center;
    padding: 30px 10px;
  text-decoration: none;
  font-size: 17px;
    margin: 0;
  display: inline-block;
  border-radius: 10px;
  transition: 1s;
  /*justify-content: center;*/
    /*position: fixed; /* or absolute */
}

i {
    /*float: right;*/
  font-size: 20px;
  border: none;
  outline: none;
  color: #747d8c;
  padding: 32px 5px;
  font-family: inherit;
  margin: 0px;
  border-radius: 20px;
  transition: 1s;
}

.dot {
  height: 15px;
  width: 15px;
  border-radius: 50%;
  display: inline-block;
  margin: 0px;
}

.column {
  float: left;
  width: 33.33%;
  padding: 10px;
  height: 300px; 
}

.row:after {
  content: "";
  display: table;
  clear: both;
}


@media screen and (max-width: 870px) {
  .nav a{
    display: none;
    padding-top:5px;
    padding-bottom:5px;
  }

  div.dot_a{
    padding-top: 3px;
    padding-bottom: 0px;
  }

  .nav {
    width: 90%;
  }
  .dot{
    margin-top: 15px;
    margin-bottom: 15px;
  }

  .nav a:active {
    display: block ;
  }

}


ResponsiveMenu.js:

const toggleButton = document.querySelector('.dot_a');
const navbarLinks = document.querySelector('.邪nchors');

toggleButton.addEventListener('click', () => {
    navbarLinks.classList.toggle('active')
})

Remove items from an array in order until matching item is found

I have an array of items

const test = [
  {
    id: '1',
  },
  {
    id: 'a',
  },
  {
    id: '3',
  },
  {
    id: 'b',
  },
  {
    id: '5',
  },
  {
    id: 'c',
  },
  {
    id: '7',
  },
];

These objects are always going to be in the same order. I’d like to be able to remove all items in order from the start until a specific id is reached.

I thought I could do this by just looping through until one is found and then pushing the items coming after that to a separate array:

let skippedArray = []

let skipUntilIndex = undefined

test.forEach((item, i) => {
  if(item.id === 'b') {
    skipUntilIndex = i
  }
  if(skipUntilIndex && i >= skipUntilIndex) {
    skippedArray.push(item)
  }
})

// [
//   {
//     id: 'b',
//   },
//   {
//     id: '5',
//   },
//   {
//     id: 'c',
//   },
//   {
//     id: '7',
//   },
// ]
console.log(skippedArray)

But this seems pretty dirty. Is there a better way to achieve this? I don’t mind using lodash or similar libraries.

Uncaught TypeError: Cannot read properties of undefined (reading ‘rendered’)

im newbie in React and trying to make a headless worpdpress aplication.
when i fetch a post i get only the first value.

I fetch the post and save it in the state

componentDidMount() {
this.setState({ loading: true }, () => {
  axios.get('http://localhost/wpprojekte/ebike/wp-json/wp/v2/posts/426')
    .then(res => {
      this.setState({ loading: false, error: 'no error', post: res.data })
    }).catch(error => {
      console.log(error);
    });
});}

I have now the post in my state which looks like

constructor(props) {
super(props);
this.state = {
  loading: false,
  error: 'error',
  post: {},
}}

when i render the Component, i can get only the first value from the post.
for example this.state.post.date

when i try to get this.state.post.title.rendered

Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')

here is The render function

render() {
return (
  <div>
    {<div dangerouslySetInnerHTML={{ __html: this.state.post.title.rendered }} />}
  </div>
)}

I dont understand why it is getting only the first value.

How can calculate automatically without click any button to run function

I want to calculate days of a reservation for a booking website.
I want to calculate total price (days*$100) automatically without click any button to run function but update auto with out refresh page.

function daysBetween(startDate, endDate) {
  var millisecondsPerDay = 1000 * 60 * 60 * 24;
  var startDateUTC = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
  var endDateUTC = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());

  return Math.floor((endDateUTC - startDateUTC) / millisecondsPerDay);
}

document.getElementById("btn").addEventListener("click", function() {
  let startDate = new Date(document.getElementById("startdate").value);
  let endDate = new Date(document.getElementById("enddate").value);
  let output = document.getElementById("totalprice");

  // Get how much days is between these dates
  let days = daysBetween(startDate, endDate);

  if (days) {
    output.classList.remove("text-danger");
    output.innerHTML = `${days*100}鈧琡;
  } else {
    /* if no valid date is entered */
    output.classList.add("text-danger");
    output.innerHTML = `Select valid dates`;
  }

}, false);
<section class="sec5">Check in</section>
<section class="sec2"><input class="date" id="startdate" type="date" name="checkin" required=""></section>

<section class="sec5">Check out</section>
<section class="sec2"><input class="date" id="enddate" type="date" name="checkout" required=""></section>


<p>Total price
  <p>
    <section class="sec3" id="totalprice" name="totalprice">--</section>



    <div id="btn">CLICK ME!</div>

PHP, jQuery, AJAX: Can insert one type of data to database

I have simple jQuery AJAX which from HTML form through PHP gets some data and makes it in the background.

Also, I’m using phone numbers this library.

Both scripts work fine but when all data are inserted into the database the phone number is not inserted.

When I try to use the form without Javascript, only with PHP script all data also with phone number is inserted.

In my opinion, the problem will be in AJAX and I can’t find it.

Is there any solution how I can fix it?

My code is on this link

Intercept 401 error and prevent console error message

I’m using the following library axios-auth-refresh to automatically refresh the token.

When I make a call to the API it returns a 401 error and in this way the library is triggered in order to execute the refresh token and ensure that all requests are successfully completed.

I’m using axios to make API calls and I also use interceptors. I’ve already tried to check if I get the 401 error in the response interceptor but that doesn’t happen, I always get the code 200.

Is there any way to prevent the 401 error in the browser?

Interceptors

axios.interceptors.request.use(request => {
  request.headers['Authorization'] = `Bearer ${sessionStorage.getItem("access_token")}`;
  return request;
});

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

axios-auth-refresh

const refreshAuthLogic = (failedRequest) => {
   
    return axios.post(url,
    {
        client: "Test",
        grant_type: "refresh_token",
        refresh_token: sessionStorage.getItem('refresh_token')
    }).then(tokenRefreshResponse => {
        failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data.access_token;
        sessionStorage.setItem("access_token", tokenRefreshResponse.data.access_token);
        sessionStorage.setItem("refresh_token", tokenRefreshResponse.data.refresh_token);
        return Promise.resolve();
    }).catch(function (e) {
        console.log("error", e);
    });
}

createAuthRefreshInterceptor(axios, refreshAuthLogic);

simple get

private extractData(res) {
    return res.data;
  }

  private handleErrorPromisse(error: Response | any) {
    console.error(error.message || error);
    return Promise.reject(error.message || error);
  }

  GetSample(): Promise<any> {
    return axios.get(url, {
      headers: {
        Authorization: 'Bearer ' + sessionStorage.getItem("access_token")
      }
    })
      .then(this.extractData)
      .catch(this.handleErrorPromisse);
  }

problem

img