How to play different audio based on which div is in view?

I’m trying to create a website that depending on which div is in view will play a different audio file.

The only thing closely related that I could find was different audio playing depending on specific height locations of the website, i.e. between start height = 1000px and end height = 1400px play X music. Example here: http://home.jejaju.com/play/smoothFade/tracks

The only issue with this approach is that my website is responsive, so depending if you’re on mobile or desktop will have different heights.

Any ideas or examples on how to approach this?

How to lazy load headless ui Dialog in React?

I’m trying to lazy load a headless ui Dialog component but I haven’t been able to do it while also keeping transitions.

Here’s as close as I’ve gone:

// Modal.js

const Modal = ({
  isOpen
}) => {
  return (
    <Transition show={isOpen}>
      <Dialog>
        ...
      </Dialog> 
    </Transition>
  );
};

export default Modal;

const Modal = lazy(() => import("~/components/Modal"));

<Suspense>
  {isOpen ? <Modal isOpen={isOpen} ... />
</Suspense>

This works for the most part but I lose the transition when the component is unmounted since isOpen is false then it gets unmounted immediately. But If I remove it then the component isn’t lazy loaded when I open it but instead it loads on page load.

Is there a way to lazy load it while keeping the Transitions?

my panning handler resets the offset state after the second time

Im trying to make a panning handler for my canvas element using a state for the offset and a state to hold the mouse start position. The first pan works as expected and the offset is set to the correct values. On the secont pan when clicked it worked as expected but then when i move it it resets the offset to 0 asif its the first pan. Im very new to react and will appreciate any help.

function handlePan(event) {
        switch (event.type) {
            case "mouseleave":
                setIsPanning(false);
                break;

            case "mousedown":
                setIsPanning(true);
                setPanStartX(event.clientX);
                setPanStartY(event.clientY);
                break;

            case "mouseup":
                setIsPanning(false);
                console.log("UP");
                break;

            case "mousemove":
                if (isPanning) {
                    // Calculate the panning offset based on the mouse position and the pan start position
                    const offsetX = event.clientX - panStartX;
                    const offsetY = event.clientY - panStartY;
                    setPanOffsetX(offsetX);
                    setPanOffsetY(offsetY);
                    console.log("PANNING");
                }
                break;

            default:
                break;
        }
    }

I tried making a second state to store values to be substracted with the offset as the transform of the canvas which i thought would fix it but it made the canvas’s offset stack when moved consecutively.

How do I move al my code under one array in Javascript?

I have two scripts in JavaScript that allows my to write data to a text file. I want to move all of my code into one function called myFunction. I want to do this with just code and not copy and paste because I don’t have access to the source code.

My code for both programs are:

`const fs = require(‘fs’)

      
    // Data which will write in a file.

    let data = “Learning how to write in a file.”

      
    // Write data in ‘Output.txt’ .

    fs.writeFile(‘Output.txt’, data, (err) => {

          
        // In case of a error throw err.

        if (err) throw err;`

Can someone help me? I want to put this in a function by code and not copy and paste or manually doing it.

Create an Index.php that opens several .php files, without having to reload the page

Good afternoon, I want to create an index.php and that at the same time open several .php files but without having to reload the page

A friend gave me this .js that he uses to make said function

`    let style = ["betados", "administradores", "ranking", "pug_history", "demo_history"];
var pag = 0;
var pagin = 0;
function ActualizarPag() {
    $('#content_right').load('include/web/content_right_bans.php?i='+ pag + '&c=1&pagina=' + pagin);
    return false;
}
function PaginadorClick(val) {
    pagin = val;
    $('#content_right').load('includes/right_content.php?i='+ pag + '&c=1&pagina=' + val);
    return false;
}
function DisplayRightContent(val) {
    pag = val;
    $('#titulo').load('includes/right_content.php?i=' + val + '&c=0');
    $('#content_right').load('includes/right_content.php?i=' + val + '&c=1');
    $('#menu').load('includes/right_content.php?i='+ val +'&c=2');
    return false;
}
function DisplayMatchContent(match_id) {
    pag = 3;
    $('#titulo').load('includes/right_content.php?i=' + 3 + '&c=0&m=' + match_id);
    $('#content_right').load('includes/right_content.php?i=' + 3 + '&c=1&m=' + match_id);
    $('#menu').load('includes/right_content.php?i='+ 3 +'&c=2&m=' + match_id);
    return false;
}
$('#titulo').load('includes/right_content.php?i=0&c=0');
$('#content_right').load('includes/right_content.php?i=0&c=1');
$('#menu').load('includes/right_content.php?i=0&c=2');    `

The truth is that I have not tried it myself since I do not know how to start, the idea is that from a single .php file open several at the same time but without reloading the page

This is the index.php where I want to do everything

`    <?php
    $pag = 0;
    include "include/web/steam.php";
    include "include/web/conexion.php";
    include "include/geoip.inc";
    date_default_timezone_set("America/Caracas");
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, user-scalable=1">
    <title id="titulo">Baneados | Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <link rel="stylesheet" href="css/default.css">
    <link rel="stylesheet" href="css/paginador.css">
    <link rel="stylesheet" href="css/betado_stats.css">
    <link rel="stylesheet" href="css/hover/hover.css" media="all">
    <link rel="stylesheet" href="css/icomoon/style.css">
    <link rel="icon" type="image/jpg" href="img/logo.png">
    <link rel="stylesheet" href="css/right_content/administradores.css">
    <link rel="stylesheet" href="css/right_content/betados.css">
    <link rel="stylesheet" href="css/right_content/demo_history.css">
    <link rel="stylesheet" href="css/right_content/pug_history.css">
    <link rel="stylesheet" href="css/right_content/ranking.css">
</head>
<body>
    <div id="style_right"></div>
    <div class="contenedor">
        <div class="animate__animated animate__backInDown">
            <div class="banner">
                <img src="img/banner3.png" alt>
            </div>
            <?php include "include/web/menu.php";?>
            <?php include "include/web/content_left.php";?>
            <?php include "include/web/content_right_bans.php";?>
        </div>
        <div class="footer">
            <p>
                Copyright © 2022 | 
                <a href="index.php">Test e-Sports</a>
            </p>
        </div>
    </div>
    <script src="js/right_content.js"></script>
    <script src="js/index.js"></script>
    <script src="js/right/betados.js"></script>
    <script src="js/right/administradores.js"></script>
    <script src="js/right/ranking.js"></script>
</body>
</html>    `

in this part

`    <?php include "include/web/menu.php";?>

<?php include "include/web/content_left.php";?>

<?php include "include/web/content_right_bans.php";?>    `

is where I want the functions to be performed.

I don’t know if it is allowed, if it is not, let me know to remove the link, on this page is what I am trying to recreate, in the menu section when you click and see another section, it shows the data without having to reload the page

Page

Encountered two children with the same key, `undefined`. Keys should be unique so that components maintain their identity across updates

I’m getting below error:
ERROR Warning: Encountered two children with the same key, undefined. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

I Beileve, I’m geeting this error in DropDownPicker. I have used new Set, I believe it gives unique value but still I’m getting above error. Please help me out.

Below is my code:

const CarList = () => {
    const [isLoading, setIsLoading] = useState(false);
    const [data, setData] = useState([]);
    const [error, setError] = useState(null);
    const [query, setQuery] = useState('');
    const [fullData, setFullData] = useState([]);
    const [selected, setSelected] = useState("");
    const [open, setOpen] = useState(false);
    const [childOpen, setChildOpen] = useState(false);
    const [filterOption, setfilteroption] = useState([
        
        {label: 'Model', value: 'Model'},
        {label: 'Year', value: 'Year'},
        {label: 'Color', value: 'Color'},
      ]);
      const [value, setValue] = useState(null);
      const [childvalue, setChildValue] = useState([]);
      const [childItem, setChilditem] = useState(null);

    
   
    useEffect(() => {
        setIsLoading(true);  
        fetch(`https://myfakeapi.com/api/cars/?seed=1&page=1&results=20`)
          .then(response => response.json())
          .then(response => {
            setData(response.cars);
            setFullData(response.cars);
      
            setIsLoading(false);
          })
          .catch(err => {
            setIsLoading(false);
            setError(err);
          });
      }, []);

      if (isLoading) {
        return (
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <ActivityIndicator size="large" color="#5500dc" />
          </View>
        );
      }
    
      if (error) {
        return (
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={{ fontSize: 18}}>
              Error fetching data... Check your network connection!
            </Text>
          </View>
        );
      }


    const handleSearch = (text) => {
        const formattedQuery = text.toLowerCase();
        const filteredData = filter(fullData, user => {
          return contains(user, formattedQuery);
        });
        setData(filteredData);
        setQuery(text);
      };
      
      const contains = ({ car, car_model,car_color }, query) => {

      
        if (car.toLowerCase().includes(query) || car_model.toLowerCase().includes(query) || car_color.toLowerCase().includes(query)) {
          return true;
        }
      
        return false;
      };

     

const changeSelectOptionHandler = (item) => {
  const color = [...new Set(data.map((val) => val.car_color))];
  const model = [...new Set(data.map((val) => val.car_model))];
  const year = [...new Set(data.map((val) => val.car_model_year))];

  console.log("hi", item.value)
   setSelected(item.value);
   if (selected === "Color") {
    
    setChildValue(color)
  } else if (selected === "Model") {
    setChildValue(model)
  } else if (selected === "Year") {
    setChildValue(year)
  }
 };

    
     
      
      
     
      function renderHeader() {
        return (
            
          <View
            style={{
              backgroundColor: '#fff',
              padding: 10,
              marginVertical: 10,
              borderRadius: 20
            }}
          >
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              clearButtonMode="always"
              value={query}
              onChangeText={(queryText) => handleSearch(queryText)}
              placeholder="Search"
              style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
            />
            
          
            <DropDownPicker onSelectItem={changeSelectOptionHandler}
     open={open}
     value={value}
     items={filterOption}
     setOpen={setOpen}
     setValue={setValue}
     setItems={setfilteroption}
     dropDownDirection="TOP"
  
     style={{
        padding: 5,
        margin: 5,
        width: 200,
        flexDirection: 'row'
       // borderRadius: 20
      }}
    /> 
               
   
             
               <DropDownPicker
       open={childOpen}
        items={childvalue}
    value = {childItem}
  setValue = {setChilditem}
        setOpen={setChildOpen}
        setItems={setChildValue}
        dropDownDirection="TOP"
      /> 
         
          </View>
          
        );
      }

 
  
    return (
     
      
        <View style={styles.container}>
      <Text style={styles.text}>Favorite Contacts</Text>
      <FlatList
      keyboardShouldPersistTaps="always"
       ListHeaderComponent={renderHeader}
        data={data}
        keyExtractor={({ id }) => id}
        renderItem={({ item }) => (
          <View style={styles.listItem}>
            <Image
                source={{
                    uri: 'https://picsum.photos/200',
                  }}
              style={styles.coverImage}
            />
            <View style={styles.metaInfo}>
              <Text style={styles.title}>{`${item.car} ${
                item.car_model
              }`}</Text>
               <Text>Color: {`${item.car_color}`}</Text>
               <Text>Price: {`${item.price}`}</Text>
            </View>
          </View>
        )}
      />
    </View>
      
    );

 
}

Google App Script Trigger Cannot Retain Data to Be Used For The Second Trigger

I created a Google Sheet that allows a user to enter a specific ID number from a cell. The script takes that information, makes an API call, and saves the information to a variable called “invoiceItems”. It will then displays it on the sheet for the user to confirm that the information is correct. The user also has the option to send out an email if the checkbox is checked.

// Set Global Variable
let invoiceItems = {};

function main (e) {
    let invoiceData = '';  // Data from POS
    const activeSheet = SpreadsheetApp.getActiveSheet ();
    const UI = SpreadsheetApp.getUi ();
    
    // Checks if there's a change in cell E2
    if (e.range.getRow () == 2 && e.range.getColumn () == 5) {
      try {
        invoiceData = getInvoice ();
        console.log (invoiceData);
        showCustomer (invoiceData);
      }
      catch (e) {
        if (e.message.indexOf ('404') != -1) {
          UI.alert ('Error', 'No invoice found.  Check the invoice number and try again.', UI.ButtonSet.OK);
        }
      }
    }
  
  /* // Checking for the checkbox value
  if (activeSheet.getRange ("E27").getValue ()) {
    sendInvoice ();
  }
  */
    if (e.range.getRow () == 27 && e.range.getColumn () == 5 && e.value == 'TRUE') {
      sendInvoice ();
    }
  }

// Sample invoiceItems data extracted from a full list of invoiceData
invoiceItems = {
  'firstName': 'John',
  'lastName':  'Doe',
  'address_1': '555 Nowhere Street',
  'address_2':  'Sunnycity, AA 13455',
  'phone': '555-555-555',
  'email': '[email protected]'
}

The script is able to fire the trigger once the cell “E2” value has changed. The script is also able to kick off the second trigger when the send email checkbox is checked. However, the invoiceItems information isn’t present for the script to run the sendInvoice () function. I created an if statement in the sendInvoice () function to raise an error if no email is detected. This tells me that the two triggers executed independently from each other; therefore, when the second trigger kicks off, “invoiceItems” is empty.

If I don’t limit the trigger to a specific cell on the spreadsheet, the trigger works but at the expense of making 2 API calls (one for detecting changes to cell “E2” and the other when the send email checkbox is checked). Doing so will cause the script to ask the user to send the email without first displaying the information on the spreadsheet or allowing the user to verify. I could make the script sleep before asking the user to confirm sending the email but it’s not an elegant solution. Not to mention, any edit to any cell will cause a trigger.

I also tried the following but the data inside invoiceItems has some weird javascript objects in it instead of a simple string as shown in the sample data above.

// Set a property value
PropertiesService.getUserProperties().setProperty('myProperty', 'Hello, World!');

// Get a property value
function myFunction() {
  var value = PropertiesService.getUserProperties().getProperty('myProperty');
  Logger.log(value);
}

Question: Is there a way to retain the information pulled from the first trigger to be used with the second trigger?

How to put for loop in Bootstrap-Popover in JavaScript?

Before typing this question up I spent a number of days looking for an example that was close enough to help to no avail and so I’m bringing my specific use case to SO

I have three cards of bootstrap 5.

cards

And I want to create Popovers for each card, but maybe the manager wants to make a hundred more. I want to create using a for loop. I don’t want to enter every single code. How is this possible?

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/bootstrap.rtl.min.css">
    <title>Document</title>
</head>
<body>
<div style="height:200px"></div>
<div class="container">
    <div class="row">
        <div class="col-lg-4 mb-3 servicePOP" data-aos="fade-up" tabindex="0" data-bs-toggle="popover" data-bs-placement="top" data-bs-trigger="focus" title="Title" data-bs-content="">
            <div class="card position-relative">
                <div class="d-block card-icon">
                    <img src="https://www.virtuozzo.com/company/blog/wp-content/uploads/2019/04/laravel-framework.png" class="card-img" alt="Title">
                </div>
                <div class="card-body">
                    <a href="#" class=" text-decoration-none text-dark ">
                        <h5 class="card-title ">Title 1</h5>
                    </a>
                    <p>A short description</p>
                    <a href="#" class="btn btn-primary">More Details</a>
                </div>
            </div>
        </div>
        <div class="col-lg-4 mb-3 servicePOP" data-aos="fade-up" tabindex="0" data-bs-toggle="popover" data-bs-placement="top" data-bs-trigger="focus" title="Title" data-bs-content="">
            <div class="card position-relative">
                <div class="d-block card-icon">
                    <img src="https://www.virtuozzo.com/company/blog/wp-content/uploads/2019/04/laravel-framework.png" class="card-img" alt="Title">
                </div>
                <div class="card-body">
                    <a href="#" class=" text-decoration-none text-dark ">
                        <h5 class="card-title ">Title 2</h5>
                    </a>
                    <p>A short description</p>
                    <a href="#" class="btn btn-primary">More Details</a>
                </div>
            </div>
        </div>
        <div class="col-lg-4 mb-3 servicePOP" data-aos="fade-up" tabindex="0" data-bs-toggle="popover" data-bs-placement="top" data-bs-trigger="focus" title="Title" data-bs-content="">
            <div class="card position-relative">
                <div class="d-block card-icon">
                    <img src="https://www.virtuozzo.com/company/blog/wp-content/uploads/2019/04/laravel-framework.png" class="card-img" alt="Title">
                </div>
                <div class="card-body">
                    <a href="#" class=" text-decoration-none text-dark ">
                        <h5 class="card-title ">Title 3</h5>
                    </a>
                    <p>A short description</p>
                    <a href="#" class="btn btn-primary">More Details</a>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="js/bootstrap.bundle.min.js"></script>
<script>
    const servicePOP = document.querySelector('.servicePOP')
    const popover = new bootstrap.Popover(servicePOP, {
        sanitize: false,
        html: true,
        content: '<button type="button" class="btn btn-primary">My Button</button>'
    });
</script>
</body>
</html>

I want to create using for a loop.

Why is each comment element mapping multiple items instead of only one at a time?

In my comment thread, which has a parent-child relationship (where the parent ID of a child comment is the ID of the root comment and the parent ID of the root comment is null), each object has a “replies” array that represents replies to that specific comment. However, when I try to map through and display these replies, each comment element is mapping 4 replies instead of just the replies that pertain to it. How can I fix this so that each comment element only displays the replies that are relevant to it.

I know this is verbose but this is my comments api data structure

[
{
    "avatar": "/Mrandompic_158.jpg",
    "comment": "2nd Child of Root comment 2 replying to 1st child",
    "commenterName": "Jerry Smith",
    "created": "2017-01-01T00:00:00.000Z",
    "currentUserId": "qrs",
    "draft": false,
    "draftContent": "qrs",
    "id": 6,
    "initials": "MR",
    "isEdit": false,
    "likesData": {
        "userLiked": true
    },
    "markAsResolved": "false",
    "parentId": 2,
    "showComments": true,
    "showDelete": true,
    "showEdit": true,
    "showLikes": true,
    "updated": "2017-01-01T00:00:00.000Z",
    "replies": [
        {
            "id": 1,
            "replierId": "qrs",
            "replierName": "Jerry Smith",
            "reply": "Reply to Jerry",
            "repliedToId": "nop",
            "repliedToName": "Karen Smith",
            "created": "2017-01-01T00
        }
        ]
},
{
  "avatar": "Mrandompic_158.jpg",
  "comment": "2nd Child of Root comment 2 replying to 1st child",
  "commenterName": "Karen Smith",
  "created": "2017-01-01T00:00:00.000Z",
  "currentUserId": "nop",
  "draft": false,
  "draftContent": "fjhjsgd",
  "id": 5,
  "initials": "MR",
  "isEdit": false,
  "likesData": {
    "userLiked": true
  },
  "markAsResolved": "false",
  "parentId": 2,
  "showComments": true,
  "showDelete": true,
  "showEdit": true,
  "showLikes": true,
  "updated": "2017-01-01T00:00:00.000Z",
  "replies": [
    {
      "id": 1,
      "replierId": "nop",
      "replierName": "Karen Smith",
      "reply": "Reply to Jerry",
      "repliedToId": "qrs",
      "repliedToName": "Jerry Smith",
      "created": "2017-01-01T00:00:00.000Z",
      "updated": "2017-01-01T00:00:00.000Z"
    }
  ]
},
]

{
  fullCommentSectionApiData?.commentsData.comments.map(_comment => {
    {/*@ts-expect-error */}
    if (_comment.replies.length > 0) {
      {/*@ts-expect-error */}
      return _comment.replies.map(reply => {

 
  //  user id matches.. does abc === abc ? then display
        if (reply.replierId === _comment.currentUserId) {
          return (
            <div key={reply.id}>
              {reply.replierName} replied to {reply.repliedToName}
            </div>
          );
        }
        return null;
      });
    }
  })
}

My Comment Thread

sidenote: number 2 James should not even have a replied to display.. its replies [] is empty, but it is also displaying for all of them no matter if the replies.length is 0.

What am i doing wrong?

I tried to map the replies array for each comment object and display the replierName and repliedToName in a list. However, the result was that each comment element was mapping 4 items instead of just one. I was expecting each comment element to only display one reply at a time, with the replierName and repliedToName for that specific reply.

React : Canvas doen’t get returned as NULL in draw function

I am currenty reading code of Excalidraw and trying to understand how app works. I started from first commit and see that code

const rootElement = document.getElementById("root");

function drawScene() {
  ReactDOM.render(<App />, rootElement);
  const canvas = document.getElementById("canvas");
  
  const context = canvas.getContext("2d");
  }
drawScene();

Everything works fine ,but when I do my version

const root = ReactDOM.createRoot(document.getElementById("root"));    

    const drawScene = () => {   

    root.render(<App />);  
    
    const canvas = document.getElementById("canvas"); 
  
    const context = canvas.getContext("2d"); 
 }; 

 drawScene();

Canvas is NULL, but it renders. I understand that I use different version of React,but can you tell me and give me the link why in the first case canvas is normal value , in mine is Null.

the project was initially created 3 years ago and that version of react was used, now I use the last version of it. I understand that to write code the way is quite messy, but I follow commits and want to go step by step.

How to get the event list of an HTML element

I need to get the event list of an html element.

To be clear I don’t mean the inline events that are mentioned in this thread.

I need to get the EventListeners that are added by function addEventListener().

It would also be very convenient to be able to understand how to remove an event present in the list without the need of the function used to create it, as required by removeEventListener() function.

How to push a form submission to the dataLayer in google tag manager (gtm)

More than a question, I want to give back to the community…

Here is a little snippet for a code that will help you guys push the submission of forms to the dataLayer in Google Tag Manager.

I noticed that there were explanations of how to push to the dataLayer, but there were no actual examples. So here it is. I’d recommend narrowing down the querySelector if you have more than 1 form on the same page, but even with that, it will help.

If anyone of you pros wanna suggest anything that’d work better so that people can see this thread just comment below 🙂

`

<script>
var inputs = [];
var inputs = document.querySelectorAll('input');
var dictionary = {};
  
var x = inputs.forEach(function(field) { 
  var key = field.getAttribute("name");
  var value = field.value;
  dictionary[key] = value;
});

window.dataLayer = window.dataLayer || []; 
  dataLayer.push({
  'event': 'formInfoPush',
  'ObjInfo': dictionary});
</script>

`

How can I loop through an array using a promise?

My use-case: using each SKU in my SQL database, I will compare its respective price with the current, realtime price retrieved using API. Later on, I will compare these prices and overwrite the price in my DB with the realtime price.

TL;DR:

  1. Query: run loop to pass each SKU from getAllBridalDB as {{dynamicSKU}} in getProducts API call.

  2. comparePrices: assign price from JSON retrieved in {{dynamicSKU}} API call as a dynamic variable

  3. (Later use case): compare price from getAllBridalDB to price from comparePrices.
    3a. Update DB price as needed.

Query

Goal: retrieve the first SKU from table getAllBridalDB and store it in dynamicSKU, pass it into getProducts (see below), and store the price retrieved from getProducts as a new variable (see comparePrices below). I will then compare the price from the SKU in the table with the price from getProducts. If there’s a change (+/-) from the price in my database, I will overwrite the price in my database (I haven’t made it this far yet – I’m still trying to get to the point of comparing prices).

This query hasn’t really been working. In fact, it crashes my app every time I run it. Everything else seems to be working so far. Question #1: how can I amend this loop to meet the above need?

const bridalArray = await getAllBridalDB.trigger({});
//console.log(bridalArray)
const bridalArraySKUs = bridalArray.Sku

const query = getProducts

const promises = bridalArraySKUs.map((Sku) => {
  return query.trigger({
    additionalScope: {
      dynamicSKU: Sku
    }
  });
});

return Promise.all(promises);

getAllBridalDB
Simply imports SQL database into table. Each row has a unique SKU (not pictured)

Example of SQL data in table:

https://ibb.co/BngDXzd

getProducts

https://ibb.co/HXKBqTn

comparePrices
I’m working with an array of nested objects. This script logs the price as a decimal. It should work for every SKU as the JSON structure doesn’t change.

If I simply type in a SKU in the value of getProducts, compareProducts logs the price successfully. I will need this to be dynamic in production (hence {{dynamicSKU}}).

Question #2: how can I dynamically store this decimal to later compare with my DB price? I’d probably run the comparison in real-time in this script.

//Passes thru every object thru price
let values = Object.values(getProducts.data.Products[0].Price)
//use values[0] because values [1] is the currency denomination as a string (which is not needed)
let currentPrice = values[0] //current price of given SKU as a decimal
console.log(currentPrice) //result: 1610.93

When using mapbox-gl js, popups of unclustered points appear on incorrect coordinates on touch screens

map.on(“click”, “unclustered-point”, (e) => {
e.originalEvent.stopPropagation();

      const coordinates = e.features[0].geometry.coordinates.slice();
      const title = e.features[0].properties.title;

      const innerHtmlContent = `<div class="w-100">
        <h4 class="h4Class">${title} </h4> </div>`;

      let lang = localStorage.getItem("language");
      let buttonText = "Nasıl gidilir?";
      

      const divElement = document.createElement("div");
      const assignBtn = document.createElement("div");
      assignBtn.innerHTML = `<button class='btn-primary w-100 d-flex flex-row justify-content-center' >${buttonText}</button>`;
      divElement.innerHTML = innerHtmlContent;
      divElement.appendChild(assignBtn);

      assignBtn.addEventListener("click", () => {
        this.searchStore(title);
        this.openDialog("search");
        this.$store.dispatch("showClusters", false);
      });

      while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
        coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
      }

      new mapboxgl.Popup({ offset: 20 })
        .setLngLat(coordinates)
        .setDOMContent(divElement)
        .addTo(map);
    });

I implement cluster and unclusters the same as the documentation of mapbox-gl js but when clicking the uncluster points on the touch screen, it triggers the wrong empty space (right below the marker).

Note : It’s working like a charm on desktop view 🙂

Can not disable scrolling on ios

I have a scrollable feed on my site for user posted content. There is a button that triggers a popup/overlay that should pause the scrolling. I found a way to pause on a pc browser, but I am unable to pause the scrolling on my iPhone causing a weird visual glitch that shows the content behind the popup/overlay still scrolling as if it were the content ontop.

<script>
            function NewPostPopup() {
                const noscroll = document.getElementById("newpostpopup").classList.toggle("active");
                if (noscroll) {
                    document.body.style.overflow = "hidden";
                } 
                else {
                    document.body.style.overflow = "auto";
                }
            }
        </script>