Preloading a large background image

I would like to make sure that my image preloads properly, as there’s an svg effect, that only looks good when the background is loaded.

function preloader() {
if (document.getElementById) {
    document.getElementById("preload-01").style.background = "url(https://i.imgur.com/a9DM6w8.jpg) no-repeat -9999px -9999px";
}
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(preloader);

https://codepen.io/bonobonobo/pen/WNdWbZq?editors=0100

I have tried this method, yet it seems ineffective.
The above is only a snippet, I have a few other scripts loading as well, and all in all it doesn’t do the job.

Is there a mistake in my code?

How to update boolean value in MongoDB database

I’m currently writing a Next.js, and I’m not sure how to update the isBookmarked boolean value in my code that will persist to the database from my component. Here’s what I have currently.

Item.js

<Item>
...
<div onClick={????????}>....</div> //Update value on database from here
...
</Item>

index.js

export async function getServerSideProps(context){
  const client = await clientPromise;

  const db = client.db("mediaData")
  let media = await db.collection("media").find({}).toArray();
  media = JSON.parse(JSON.stringify(media));
  

  return{
    props:{ media} 
  }
}
......
media.map((item) => (
            <Item
              key={item._id}
              mediaBookmarked={item.isBookmarked} // value recived from the database
              year={item.year}
              category={item.category}
              rating={item.rating}
              title={item.title}
              small={item.thumbnail.trending.small}
              large={item.thumbnail.trending.large}
            />
....

Will I need to define a schema? I manually imported the information that populates this database from a JSON file.

react native redux : actions.(~~~~) not defined how to use dispatch and import actions?

part of App.js

import { createStore } from 'redux';
import { Provider,useDispatch,useSelector } from 'react-redux';
import reducers from './reducers';
import * as actions from './actions';
const store = createStore(reducers);

const App = () => {
  return(
    <Provider store={store}>
        <MyComponent>
    </Provider>
  );
};

//———————-

part of my component

const dispatch = useDispatch()

dispatch(actions.addPost(text));

//——————

actions - index.js
export const addPost = (text) => ({
   type : 'ADD',
   text
});

//—————–
reducers – index.js

const initialState = {
   posts : [],
};

const posts = (state=initialState,action) => {
const {posts}= state;
switch(action.type){
   case 'ADD':
       return({
           posts: [
               {
               idx : Math.random(),
               userIdx: 'user123',
               text: actions.text
               },
               ...posts,
           ]
       });
};
};

export default posts;

//——————————

i declare addPost in index.js in actions folder and export it
but when i use it, error has been occurred and it said “TypeError: actions.addPost is not a function. (In ‘actions.addPost(text)’, ‘actions.addPost’ is undefined)”

Why my components can’t recognize actions?
Is there anything i should add?
this is my project folder structure.
enter image description here

How to remove static array after uncheck checkbox in jquery

I have two checkboxes, and I want whenever I click on any checkbox then their values (static array) should be inserted into “final” array (empty array). If I uncheck that checkbox then its value (static array) should be remove from “final array”.

Right now I am inserting/pushing “static” array into blank array (final array), but I want to know that how can I remove this “static” array after uncheck checkbox ?

var myarray = [];
var model = ["Height", "size", "bust"];
var Hostess = ["Height", "bust"];

$("input:checkbox.country").click(function() {
  var value = $(this).val();
  if (!$(this).is(":checked"))
    alert('you are unchecked ' + $(this).val());

  else
    myarray.push(model);
});
console.log('Final array is ', myarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
  <fieldset>
    <legend>Choose your interests</legend>
    <div>
      <input type="checkbox" id="model" class="country" name="interest" value="model">
      <label for="model">model</label>
    </div>
    <div>
      <input type="checkbox" id="Hostess" class="country" name="interest" value="Hostess">
      <label for="hostess">Hostess</label>
    </div>

    <div>
      <button type="submit">Submit form</button>
    </div>
  </fieldset>
</form>

Dinamic import to JSON file in react component

I am trying to read a json file with a react component. The idea is to be able to choose which file to read based on the default_lang variable. This is the file structure and how I am trying to read them.

./config.json

{
  "enable-lang":{
    "es": "spanish",
    "en": "spanish"
  },
  "default-lang": "en"
}

./dictionary/spanish.json

{
  "title": "Pagina en construccion",
  "description": "Esta página sigue en construcción"
}

./dictionary/english.json

{
  "title": "Page under construction",
  "description": "This page is still under construction"
}

./Language.js

import {Component} from "react";
import config from "./config.json";


export class Language extends Component
{
    static getUsedDictionary() {
        let used_lang = "es";
        let dictionary_path = `./dictionary/${ config["enable-lang"][used_lang] }.json`;
        return import(`${dictionary_path}`);
    }

    static getText (id) {
        let dictionary = this.getUsedDictionary();
        console.log("Dictionary value in getText:" + dictionary);
        console.log("Dictionary[id] value in getText:" + dictionary);
        if(dictionary[id] !== undefined) {
            return dictionary[id];
        } else {
            return dictionary['text-not-found'];
        }
    }
}

dictionary and dictionary[id] value in function getText
values

Access localStorage of a url opened in another tab using chrome extension

I have a chrome extension which is accessible from a particular website url. I need to get the local storage of an iframe available in this website which is cross-origin domain, which is not possible. So as a work around I want to open the iframe url as a new tab, unfocused and access the localStorage of that tab from the chrome extension. How can I get the localStorage of the new opened tab

How do i make a cumulative total keep adding to itself

So basically im trying to achieve a running total for each player in my game of war. Idk how to achieve this I have already tried creating a variable which holds a total but i just refreshes and sets it to a new total.

HTML CODE

           <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="utf-8" />
                <title>Card Game</title>
                <link href="styles/normalilze.css" s rel="stylesheet" />
                <link href="styles/my_style.css" rel="stylesheet" />
            </head>
            
            <body>
            <div id="main">
                <h1>Card Game</h1>
                <div id="left">
                    <div id="pHand">
                        <br />
                        <!-- Using JavaScript replace the word 'Player' with the name of
                          the person playing the game-->
                        <h2 id="pNames">Player</h2>
                    </div>
                    <div id="cHand">
                        <h2>Slick</h2>
                    </div>
                    <div id="but">
                        <button id="newPlayer">New player</button>
                        <button id="deal">Deal</button>
                        <button id="play">Play</button>
                    </div>
                </div>
            <section class="player">
                <div id="right">
                    <h2>Card Count:</h2>
                    <!-- Using JavaSCript enter the number of remaining cards in the 'Players' hand
                        in the p tag below-->
                    <p id="cardCount"></p>
                    <br />
                    <!-- Using JavaSCript replace the word 'Player' with the name of
                        the person playing the game-->
                    <h2 id="pName">Player</h2>
                    <h2 id="pName2">:</h2>
                    <!-- Using jQuery insert the current 'Player' score in the p tag
                         below -->
                    <p id="pScore"></p>
                    <br />
                    <h2 id="cName">Slick:</h2>
                    <!-- Using jQuery insert the current 'Slick' score in the p tag
                         below -->
                    <p id="cScore"></p>
            
                    <!-- add and style winning message in the
                         following div -->
                    <div id="win"></div>
                </div>
            </div>
            </section>
            
            <script src="scripts/jquary-3.2.1.min.js"></script>
            <script src="scripts/jQ-War.js"></script>
            </body>
            </html>

Here is the javascript code and I added the problem which i am facing.

JavaScript Code

    $(document).ready(function () {

    var i = 0;
    var running = false;

    $(function(){
        $("#deal").click(function(){
            if (!running){
                War();
                addTotals();
                running = true;
                setTimeout(()=>{running = false}, 2200);
            }
        });
    });

    function War(){
        if (i <= 26)
        {

            var carding = [Hearts, Spades, Diamonds, Clubs];
            var slickCards = carding[Math.floor(Math.random() * carding.length)];
            var playerCards = carding[Math.floor(Math.random() * carding.length)];

            $("<img>")
            .attr('src', playerCards [playerScore = (value = Math.floor(Math.random() * 12))].picture)
            .appendTo("#pHand").hide().fadeIn("slow").delay("1000").fadeOut("slow");

            $("<img>")
                .attr('src', slickCards [slickScore = (value = Math.floor(Math.random() * 12))].picture)
                .appendTo("#cHand").hide().fadeIn("slow").delay("1000").fadeOut("slow");

            i++;
        }
    }

function addTotals(){
    var totalPlayerScore = 0;
    totalPlayerScore = playerScore + totalPlayerScore;
    document.getElementById("pScore").innerText = totalPlayerScore;
}

    function card(name,suit,value, picture) {
        this.name = name;
        this.suit = suit;
        this.value = value;
        this.picture = picture;
    }

    var Hearts = [
        new card('Ace', 'Hearts',1, "./images/Hearts/Ace.jpg"),
        new card('Two', 'Hearts',2, "./images/Hearts/Two.jpg"),
        new card('Three', 'Hearts',3, "./images/Hearts/Three.jpg"),
        new card('Four', 'Hearts',4, "./images/Hearts/Four.jpg"),
        new card('Five', 'Hearts',5, "./images/Hearts/Five.jpg"),
        new card('Six', 'Hearts',6, "./images/Hearts/Six.jpg"),
        new card('Seven', 'Hearts',7, "./images/Hearts/Seven.jpg"),
        new card('Eight', 'Hearts',8, "./images/Hearts/Eight.jpg"),
        new card('Nine', 'Hearts',9, "./images/Hearts/Nine.jpg"),
        new card('Ten', 'Hearts',10, "./images/Hearts/Ten.jpg"),
        new card('Jack', 'Hearts',11, "./images/Hearts/Jack.jpg"),
        new card('Queen', 'Hearts',12, "./images/Hearts/Queen.jpg"),
        new card('King', 'Hearts',13, "./images/Hearts/King.jpg"),
    ];

    //Diamond Functions

    var Diamonds = [
        new card('Ace', 'Diamonds',1, "./images/Diamonds/Ace.jpg"),
        new card('Two', 'Diamonds',2, "./images/Diamonds/Two.jpg"),
        new card('Three', 'Diamonds',3, "./images/Diamonds/Three.jpg"),
        new card('Four', 'Diamonds',4, "./images/Diamonds/Four.jpg"),
        new card('Five', 'Diamonds',5, "./images/Diamonds/Five.jpg"),
        new card('Six', 'Diamonds',6, "./images/Diamonds/Six.jpg"),
        new card('Seven', 'Diamonds',7, "./images/Diamonds/Seven.jpg"),
        new card('Eight', 'Diamonds',8, "./images/Diamonds/Eight.jpg"),
        new card('Nine', 'Diamonds',9, "./images/Diamonds/Nine.jpg"),
        new card('Ten', 'Diamonds',10, "./images/Diamonds/Ten.jpg"),
        new card('Jack', 'Diamonds',11, "./images/Diamonds/Jack.jpg"),
        new card('Queen', 'Diamonds',12, "./images/Diamonds/Queen.jpg"),
        new card('King', 'Diamonds',13, "./images/Diamonds/King.jpg"),
    ];

    //Club Functions

    var Clubs = [
        new card('Ace', 'Clubs',1, "./images/Clubs/Ace.jpg"),
        new card('Two', 'Clubs',2, "./images/Clubs/Two.jpg"),
        new card('Three', 'Clubs',3, "./images/Clubs/Three.jpg"),
        new card('Four', 'Clubs',4, "./images/Clubs/Four.jpg"),
        new card('Five', 'Clubs',5, "./images/Clubs/Five.jpg"),
        new card('Six', 'Clubs',6, "./images/Clubs/Six.jpg"),
        new card('Seven', 'Clubs',7, "./images/Clubs/Seven.jpg"),
        new card('Eight', 'Clubs',8, "./images/Clubs/Eight.jpg"),
        new card('Nine', 'Clubs',9, "./images/Clubs/Nine.jpg"),
        new card('Ten', 'Clubs',10, "./images/Clubs/Ten.jpg"),
        new card('Jack', 'Clubs',11, "./images/Clubs/Jack.jpg"),
        new card('Queen', 'Clubs',12, "./images/Clubs/Queen.jpg"),
        new card('King', 'Clubs',13, "./images/Clubs/King.jpg"),
    ];
        //Spades Functions

        var Spades = [
            new card('Ace', 'Spades',1, "./images/Spades/One.jpg"),
            new card('Two', 'Spades',2, "./images/Spades/Two.jpg"),
            new card('Three', 'Spades',3, "./images/Spades/Three.jpg"),
            new card('Four', 'Spades',4, "./images/Spades/Four.jpg"),
            new card('Five', 'Spades',5, "./images/Spades/Five.jpg"),
            new card('Six', 'Spades',6, "./images/Spades/Six.jpg"),
            new card('Seven', 'Spades',7, "./images/Spades/Seven.jpg"),
            new card('Eight', 'Spades',8, "./images/Spades/Eight.jpg"),
            new card('Nine', 'Spades',9, "./images/Spades/Nine.jpg"),
            new card('Ten', 'Spades',10, "./images/Spades/Ten.jpg"),
            new card('Jack', 'Spades',11, "./images/Spades/Jack.jpg"),
            new card('Queen', 'Spades',12, "./images/Spades/Queen.jpg"),
            new card('King', 'Spades',13, "./images/Spades/King.jpg"),
            //new card('Checkmark', 'Spades',14, "../check_sm.png")
        ];
});

How Do i add a running total here to the pScore!

function addTotals(){
    var totalPlayerScore = 0;
    totalPlayerScore = playerScore + totalPlayerScore;
    document.getElementById("pScore").innerText = totalPlayerScore;
}

UI retain last used text input

The Photoshop UI script has a checkbox group, radio button group, and text field group.
The script remembers the last used settings for the checkbox and radio buttons.
But does not remember the last used text filed string.

I have an idea of what needs to happen for the script to remember the text field string but don’t know how to implement the functionality into the script.

The text field string needs to be converted to a numerical value and then reconverted to a string for the script to retain the last used text field input.

Can someone please help me set up the string to number and number to string conversion?

enter image description here

Saple UI


   enter code here

#target photoshop;
app.bringToFront();

cTID = function(s) { return cTID[s] || (cTID[s] = app.charIDToTypeID(s)); };
sTID = function(s) { return app.stringIDToTypeID(s); }; 


function showDialog() {

  // DIALOG
  // ======
  var dialog = new Window("dialog"); 
      dialog.text = "Test UI"; 
      dialog.orientation = "row"; 
      dialog.alignChildren = ["left","top"]; 
      dialog.spacing = 10; 
      dialog.margins = 16; 

  // GROUP1
  // ======
  var group1 = dialog.add("group", undefined, {name: "group1"}); 
      group1.preferredSize.width = 150; 
      group1.orientation = "column"; 
      group1.alignChildren = ["fill","top"]; 
      group1.spacing = 10; 
      group1.margins = 0; 
      group1.alignment = ["left","fill"]; 

  // PANEL1
  // ======
  var panel1 = group1.add("panel", undefined, undefined, {name: "panel1"}); 
      panel1.text = "Checkbox Group"; 
      panel1.orientation = "column"; 
      panel1.alignChildren = ["left","top"]; 
      panel1.spacing = 10; 
      panel1.margins = 10; 
      panel1.alignment = ["fill","top"]; 

      dialog.checkbox1 = panel1.add("checkbox", undefined, undefined, {name: "checkbox1"}); 
      dialog.checkbox1.text = "item 1"; 
      dialog.checkbox1.alignment = ["fill","top"];
      dialog.checkbox1.value = checkbox1; 

      dialog.checkbox2 = panel1.add("checkbox", undefined, undefined, {name: "checkbox2"}); 
      dialog.checkbox2.text = "item 2"; 
      dialog.checkbox2.alignment = ["fill","top"];
      dialog.checkbox2.value = checkbox2; 

  // PANEL2
  // ======
  var panel2 = group1.add("panel", undefined, undefined, {name: "panel2"}); 
      panel2.text = "Radio Button Group"; 
      panel2.orientation = "column"; 
      panel2.alignChildren = ["left","top"]; 
      panel2.spacing = 10; 
      panel2.margins = 10; 
      panel2.alignment = ["fill","top"]; 

      dialog.radiobutton1 = panel2.add("radiobutton", undefined, undefined, {name: "radiobutton1"}); 
      dialog.radiobutton1.text = "Item 1"; 
      dialog.radiobutton1.alignment = ["fill","top"];
      dialog.radiobutton1.value = radiobutton1;  

      dialog.radiobutton2 = panel2.add("radiobutton", undefined, undefined, {name: "radiobutton2"}); 
      dialog.radiobutton2.text = "Item 2"; 
      dialog.radiobutton2.alignment = ["fill","top"];
      dialog.radiobutton2.value = radiobutton2;

  // PANEL3
  // ======
  var panel3 = group1.add("panel", undefined, undefined, {name: "panel3"}); 
      panel3.text = "Edit Text Groiup"; 
      panel3.orientation = "column"; 
      panel3.alignChildren = ["left","top"]; 
      panel3.spacing = 10; 
      panel3.margins = 10; 
      panel3.alignment = ["fill","top"]; 

      dialog.statictext1 = panel3.add("statictext", undefined, undefined, {name: "statictext1"}); 
      dialog.statictext1.text = "Tittle 1"; 
      dialog.statictext1.alignment = ["fill","top"]; 

      dialog.edittext1 = panel3.add('edittext {properties: {name: "edittext1"}}'); 
      dialog.edittext1.text = "Some text 1 "; 
      dialog.edittext1.alignment = ["fill","top"];
      dialog.edittext1.value = edittext1; 

      dialog.statictext2 = panel3.add("statictext", undefined, undefined, {name: "statictext2"}); 
      dialog.statictext2.text = "Title 2"; 
      dialog.statictext2.alignment = ["fill","top"]; 

      dialog.edittext2 = panel3.add('edittext {properties: {name: "edittext2"}}'); 
      dialog.edittext2.text = "Some text 2"; 
      dialog.edittext2.alignment = ["fill","top"];
      dialog.edittext2.value = edittext2; 
  

// GROUP2
// ======
var group2 = dialog.add("group", undefined, {name: "group2"}); 
    group2.orientation = "column"; 
    group2.alignChildren = ["fill","top"]; 
    group2.spacing = 10; 
    group2.margins = 0; 

var ok = group2.add("button", undefined, undefined, {name: "ok"}); 
    ok.text = "OK"; 

var cancel = group2.add("button", undefined, undefined, {name: "cancel"}); 
    cancel.text = "Cancel"; 

      //update the params and save them off on close
      function updateParams() {
        checkbox1 = dialog.checkbox1.value;
        checkbox2 = dialog.checkbox2.value;
        radiobutton1 = dialog.radiobutton1.value;
        radiobutton2 = dialog.radiobutton2.value;
        edittext1 = dialog.edittext1.text;
        edittext2 = dialog.edittext2.text;
    };


    ok.onClick = function () {
      updateParams();
      saveSettings();
      dialog.close(1);
    };

    dialog.center();
    return dialog.show();

}


  // Settings.
  var checkbox1 = false;
  var checkbox2 = false;
  var radiobutton1 = false;
  var radiobutton2 = false;
  var edittext1
  var edittext2

  //IDs for custom option saving / loading
  const settingsID = "exportOptions";

  const checkbox1ID = stringIDToTypeID("checkbox1");
  const checkbox2ID = stringIDToTypeID("checkbox2");
  const radiobutton1ID = stringIDToTypeID("radiobutton1");
  const radiobutton2ID = stringIDToTypeID("radiobutton2");
  const edittext1ID = stringIDToTypeID("edittext1");
  const edittext2ID = stringIDToTypeID("edittext2");

  var exportSettings;

  try {
    exportSettings = app.getCustomOptions(settingsID);
  } catch (e) {
    saveSettings();
  }

  if(typeof exportSettings == "undefined") {
    saveSettings();
  }

  function loadSettings() {
    //alert('step 1b')
    // check for previously saved dialog options
    // exclude layer group name and feather value
    exportSettings = app.getCustomOptions(settingsID);
    
    if(exportSettings.hasKey (checkbox1ID))
    checkbox1 = exportSettings.getBoolean (checkbox1ID);
  
    if(exportSettings.hasKey (checkbox2ID))
    checkbox2 = exportSettings.getBoolean (checkbox2ID);
    
    if(exportSettings.hasKey (radiobutton1ID))
    radiobutton1 = exportSettings.getBoolean (radiobutton1ID);
  
    if(exportSettings.hasKey (radiobutton2ID))
    radiobutton2 = exportSettings.getBoolean (radiobutton2ID);

    if(exportSettings.hasKey (edittext1ID))
    edittext1 = exportSettings.getString (edittext1ID);

    if(exportSettings.hasKey (edittext2ID))
    edittext1 = exportSettings.getString (edittext2ID);

  }
  
  function saveSettings() {
    //save defaults
    var newExportSettings = new ActionDescriptor();

    newExportSettings.putBoolean (checkbox1ID, checkbox1);
    newExportSettings.putBoolean (checkbox2ID, checkbox2);
    newExportSettings.putBoolean (radiobutton1ID, radiobutton1);
    newExportSettings.putBoolean (radiobutton2ID, radiobutton2);
    newExportSettings.putString (edittext1ID, edittext1);
    newExportSettings.putString (edittext2ID, edittext2);

    app.putCustomOptions(settingsID,newExportSettings,true);
  }

main()

function main(){

  try {
                
    //UI parameters
    loadSettings();
    var result = showDialog();

      if(result != 2) {

        if(checkbox1){
          alert('The checkbox 1 value is '+checkbox1);
        }
        if(checkbox2) {
          alert('The checkbox 2 value is '+checkbox2);
        }
        if(radiobutton1) {
          alert('The radio button 1 value is '+radiobutton1);
        }
        if(radiobutton2) {
          alert('The radio button 2 value is '+radiobutton2);
        }
        if(edittext1) {
          alert('The edit text 1 value is '+edittext1);
        }
        if(edittext2) {
          alert('The edit text 2 value is '+edittext2);
        }

      }
        
    }
    catch (e) {
      alert(e + ' ' + e.line);  
    }
      
}






Javascript – Refactoring and performance of a long method with some nested functions

Introduction

I have implemented a custom React hook (which consumes other custom hooks that use native React hooks), that returns a function for creating a post and, if necessary, open a rewarded ad.

The logic looks simple, but talking about code splitting, good practices, etc… I think I have made a more tedious code than it should be.

Code

Here is my code:

/**
 * Hook for creating a post with its respective information, preparing it for
 * the upload to the database and displaying a rewarded ad if were necessary.
 *
 * @memberof module:Hooks/Content
 * @function useShowRewardedAdOrCreatePost
 * @returns {import("../content.d").showRewardedAdOrCreatePostCallback}
 *   A method for creating the post, displaying a rewarded ad if neccessary.
 * @requires module:Hooks/i18n.useLanguage
 * @requires module:Hooks/AdMob.useAdMob
 * @requires module:Hooks/ConfirmationDialog.useConfirmationDialog
 * @requires module:Hooks/Content.useSendPostToProfile
 * @requires module:Hooks/Content/Helpers.preparePostForUpload
 * @requires module:Content/Constants.MAX_AVAILABLE_POST_CREATIONS
 * @requires module:AsyncStorage
 */
export default function useShowRewardedAdOrCreatePost() {
  const { t } = useLanguage();

  const { isAdMobAvailableInDevice, openRewarded } = useAdMob();

  const { getConfirmation } = useConfirmationDialog();

  const sendPostToProfile = useSendPostToProfile();

  /**
   * Creates the post, displaying a rewarded ad if neccessary.
   *
   * @async
   * @param {import("../../../utils/camera/camera.d").Photo} [photo]
   *   The photo of the post.
   * @param {import("../../../utils/camera/camera.d").Photo[]} [album]
   *   The album of the post.
   * @param {string} description - The post's description.
   * @param {import("../../../utils/map/map.d").MapPreciseLocation} [location]
   *   The location where the post is uploaded.
   * @returns {Promise<void>} An empty promise.
   */
  return async (
    photo = undefined,
    album = undefined,
    description,
    location = undefined
  ) => {
    const totalAvailablePostCreations =
      await AsyncStorage.getData("totalAvailablePostCreations") ??
      MAX_AVAILABLE_POST_CREATIONS;

    //
    // The user can create the publication directly, without the need to
    // display ads...
    //
    if (totalAvailablePostCreations > 0) {
      decreaseTotalAvailablePostCreations();
      createPost();
    }

    //
    // If `AdMob` is available, then show a confirmation dialog for opening
    // a rewarded ad.
    //
    else if (isAdMobAvailableInDevice) {
      getConfirmation(
        t("content.posts.creator.confirmationDialog.title"),
        t("content.posts.creator.confirmationDialog.message"),
        handleOnConfirmationDialogConfirm
      );
    }

    //
    // If `AdMob` is not available on the user's device, we need to make sure
    // to reset the total number of available post creations, in order to avoid
    // leaving the user locked.
    //
    else {
      resetTotalAvailablePostCreations();
    }

    /**
     * Handles the press events on the confirmation dialog's confirm button.
     *
     * @ignore
     * @inner
     * @private
     * @returns {void} Nothing.
     */
    function handleOnConfirmationDialogConfirm() {
      openRewarded({
        onEarnReward: handleOnEarnPostCreationsReward,
      });
    }

    /**
     * Handles the rewarded ad earnings.
     *
     * @ignore
     * @inner
     * @private
     * @returns {void} Nothing.
     */
    function handleOnEarnPostCreationsReward() {
      resetTotalAvailablePostCreations();
      createPost();
    }

    /**
     * Prepares the post for the uploading with its corresponding information
     * and sends it as param to the `Profile` screen.
     *
     * --Note: **We delegate the upload functionality to the `Profile` screen,
     * as it has to have the `UploadTask` for the progress bar.**
     *
     * @ignore
     * @inner
     * @private
     * @returns {void} Nothing.
     */
    function createPost() {
      console.log("Creating post!");

      const post = preparePostForUpload(photo, album, description, location);

      sendPostToProfile(post);
    }

    /**
     * Decreases the total number of available post creations in the
     * local disk.
     *
     * @ignore
     * @inner
     * @private
     * @returns {void} Nothing.
     */
    function decreaseTotalAvailablePostCreations() {
      AsyncStorage.storeData(
        "totalAvailablePostCreations",
        totalAvailablePostCreations - 1
      );
    }

    /**
     * Resets the total number of available post creations, to the initial
     * value, in the local disk.
     *
     * @ignore
     * @inner
     * @private
     * @returns {void} Nothing.
     */
    function resetTotalAvailablePostCreations() {
      AsyncStorage.storeData(
        "totalAvailablePostCreations",
        MAX_AVAILABLE_POST_CREATIONS
      );
    }
  };
}

QUESTIONS

As you can see, I have moved the logic of my code into “helper” methods, which I have left as inner functions of the method I return in the hook. Is it a bad practice to do something like this:

   function outer(some params) {
     const someVariable = 10;

     innerA();
     innerB();
     innerC();

     function innerA() {
       // use the outer's context (`some params`)
     }
    
     function innerB() {
       // complex logic which uses `someVariable`
     }
    
     function innerC() {
       //
       // just a long logic, which doesn't depends on the outer's arguments
       // and doesn't use the `someVariable`.
       //
     }
   }
  1. Is this considered an anti-pattern?

  2. Talking about performance, supposing I call this method only one time, what is considered to be better: moving the inner methods to other modules (passing the relative stuff as arguments) or leaving the helpers as inners?

  3. How could I refactor this function?

Filter by value in checkbox popup in Mapbox GL

I have changed my mind about how I want to use the Checkbox filter in Mapbox. I am using CSV2Geojson to map Google Sheets data in my map and then filter by values in one column. I know there is this https://labs.mapbox.com/education/impact-tools/finder-with-filters/ but i want to stick to my layout instead of using a config file to define options. My original spreadsheet had a function that looked at column headers and only returned cells with “Y” in them when checked. Now, I have 1 column that I need to look for 4 specific values. Below is the code and codepen for debugging. The code in question is at the bottom of the code block.

https://codepen.io/bearcats6001/project/editor/AjrPPP

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - project map 2</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>

<!-- partial:index.partial.html -->

<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src='https://npmcdn.com/csv2geojson@latest/csv2geojson.js'></script>
<script src='https://npmcdn.com/@turf/turf/turf.min.js'></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.min.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.css" type="text/css">-->

<div id="map">

  <div id="filterMenu">

    <h3>Programs</h3>

    <input type="checkbox" id="Nathan" name="srBox" value="SustainableRecreation">
    <label for="Nathan"> Nathan Shock Centers of Excellence in the Basic Biology of Aging</label><br>

    <input type="checkbox" id="Pepper" name="hlBox" value="HealthyLandscapes">
    <label for="Pepper"> Claude D. Pepper Older Americans Independence Centers</label><br>

    <input type="checkbox" id="Aging" name="ovBox" value="Overnight">
    <label for="Aging"> Centers on the Demography and Economics of Aging</label><br>
    <input type="checkbox" id="Minority" name="ovBox" value="Overnight">
    <label for="Minority"> Resource Centers for Minority Aging Research</label><br>

  </div>

</div>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>

var transformRequest = (url, resourceType) => {
  var isMapboxRequest =
    url.slice(8, 22) === "api.mapbox.com" ||
    url.slice(10, 26) === "tiles.mapbox.com";
  return {
    url: isMapboxRequest
      ? url.replace("?", "?pluginName=sheetMapper&")
      : url,
  };
};
 
mapboxgl.accessToken = 'pk.eyJ1IjoiYWZhcm9yZyIsImEiOiJjbDIwajV3YTUwMGc3M2xwNDdiYWJiMjUzIn0.Pjt9AndPk1Axv99wez-5TA';

const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    center: [-102.182698, 37.131563],
    zoom: 3,
   
    //left, bottom, right, top
});

var nav = new mapboxgl.NavigationControl({
        showCompass: true,
        showZoom: true,
        visualizePitch: true
      });

map.addControl(nav, "bottom-right");



$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: 'https://docs.google.com/spreadsheets/d/1umfhXq5WEPLEABV81-tZUayAw7WZrmqe/gviz/tq?tqx=out:csv&sheet=Sheet1',
    dataType: "text",
    success: function (csvData) { makeGeoJSON(csvData); }
  });



  function makeGeoJSON(csvData) {
    csv2geojson.csv2geojson(csvData, {
      latfield: 'Latitude',
      lonfield: 'Longitude',
      delimiter: ','
    }, function (err, data) {
      map.on('load', function () {

        map.addLayer({
          'id': 'rfovProjects',
          'type': 'circle',
          'source': {
            'type': 'geojson',
            'data': data
          },
          'paint': {
            'circle-radius': 7,
            'circle-color': "blue",
            'circle-opacity': 0.5,
          }
        });

      });

    });
  };
});

map.on('mouseenter', 'rfovProjects', function () {
  map.getCanvas().style.cursor = 'pointer';
});

map.on('mouseleave', 'rfovProjects', function () {
  map.getCanvas().style.cursor = '';
});


map.on('click', function(e) {

    if(!e.originalEvent.defaultPrevented) {
      e.originalEvent.preventDefault();
    }

    var features = map.queryRenderedFeatures(e.point, {
        layers: ['rfovProjects']
    });

    if (!features.length) {
        return;
    }

    var feature = features[0];

    var popupContent = '<h3 style="display:inline">' + feature.properties.Name + '</h3><br><p style="display:inline"><b>'
    /*popupContent += feature.properties.time ? '</b>, ' + feature.properties.time : '</b>'*/ 
    popupContent += '<br> <a href=" ' + feature.properties.Website + ' " target="_blank" rel="noopener noreferrer">Website Link</a> </p>'

    var popup = new mapboxgl.Popup({ offset: [0, 0] })
        .setLngLat(e.lngLat)
        .setHTML(popupContent)
        .addTo(map);
});


//basemap toggles
/*
var tRadio = document.getElementById('topoRadio');
tRadio.addEventListener('change', function() {
  if (this.checked) {
    map.setLayoutProperty('mapbox-satellite', 'visibility', 'none');
  }
});

var iRadio = document.getElementById('imageryRadio');
iRadio.addEventListener('change', function() {
  if (this.checked) {
    map.setLayoutProperty('mapbox-satellite', 'visibility', 'visible');
  }
});*/
//
map.doubleClickZoom.enable();
map.on('dblclick', function(e) {
map.getZoom() +10;
});
map.addControl(
  new MapboxGeocoder({
    accessToken: mapboxgl.accessToken,


    mapboxgl: mapboxgl,

    flyTo: {
      zoom: 12,
      easing: function(t) {
        return t;
      }
    },

    marker: false

  })
);

map.addControl(new mapboxgl.NavigationControl());
var filters = {};

function updateFilters() {
  var compositeFilter = ['all'];
  for (let filterValue in filters) {
    if (filters[filterValue]) {
      compositeFilter.push(['==', ['get', filterValue], 'Y']);
    }
  }
  if (compositeFilter.length > 1)
    map.setFilter('rfovProjects', compositeFilter);
  else {
    map.setFilter('rfovProjects', null);
  }
}

var checkbox = document.getElementById('Nathan');
checkbox.addEventListener('change', function() {
  filters['Program'] = this.checked;
  updateFilters();
});

var checkbox = document.getElementById('Pepper');
checkbox.addEventListener('change', function() {
  filters['Program'] = this.checked;
  updateFilters();
});

var checkbox = document.getElementById('Aging');
checkbox.addEventListener('change', function() {
  filters['Program'] = this.checked;
  updateFilters();
});
var checkbox = document.getElementById('Minority');
checkbox.addEventListener('change', function() {
  filters['Program'] = this.checked;
  updateFilters();
});

Unlink Prevents AJAX Code From Working..?

I have something like this:
enter image description here

Where, if I click on the delete button, I want the post directory as well as the post from the table to be deleted.

Right now, the file for creating post would use PHP to write an entirely new file in a folder as well as store the link of the post to the database. Then, on the index page, each anchor div would have a link that would go to that file (the post) that was stored.

mysqli_query($con, "INSERT INTO posts VALUES('','$author','$title','$text','$date','no','$thisPostColor', '', '$postLink')");

// Creating New File and Writing to That File
$myfile = fopen("posts/".$postLink.".php", "w"); // Handler
$beginning = "<?php require('../includes/post_part/postparttop.php'); ?>";
$ending = "<?php require('../includes/post_part/postpartbottom.php'); ?>";
$textBody = mysqli_fetch_array(mysqli_query($con, "SELECT post_text FROM posts WHERE post_title = '$title'"));
$textBodyNew = "<p>".$textBody['post_text']."</p>";

fwrite($myfile, $beginning);
fwrite($myfile, $textBodyNew);
fwrite($myfile, $ending);
fclose($myfile);

That is a snippet from the actual project, where the $beginning is just like navbars and stuff, and $ending is just footers and stuff. Now, whenever I click on the trash icon in the image above, it uses Javascript and AJAX + PHP to delete the post from displaying on the side (where you can edit and delete other posts) as well as deleting the actual file directory.

<?php 
//More Code Up Here
//        ⋮
            
    echo "<div class = 'previous_post'>
    <div>
      <h2> $title </h2>
      <p> Date Written: $dateWritten </p>
    </div>
    <a href = '#'> <i class = 'fa fa-pen-to-square fa-lg'></i> </a>
    <a href = '#' onclick = 'deletePost($postid)'> <i class = 'fa fa-trash fa-lg' ></i> </a>
    </div>";
    }
?>
                
<!-- Script for Delete Button to Use PHP To Delete Post First Alert -->
<script>
  // This Uses AJAX
  function deletePost(id){
    $.ajax({
      type: "GET",
      url: "includes/handlers/deletePost.php",
      data:{deleteId:id},   
      dataType: "html",                
      success: function(data){  // What to Do On Success
        location.reload(); // REFRESH PAGE SO IT LOOKS LIKE IT IS DELETED
        return false;
      }
    });
  };

But it does not work if I use PHP Unlink. The contents of deletePost.php are:

<?php
// We Got To Adjust PHP For This Specific File
include("../../config/config.php");

if(isset($_GET['deleteId'])){ // DeleteID Was What We Called It In Data Attribute in AJAX
    $id = $_GET['deleteId']; // DeleteID Was What We Called It In Data Attribute in AJAX
    delete_data($con, $id); // Past These to A Function Called Delete_Data
}

function delete_data($con, $id) {
    // Deleting File From Folder
    $linkquery = mysql_fetch_array(mysqli_query($con, "SELECT post_link FROM posts WHERE id = '$id'"));
    $link = $linkquery['post_link'];
    unlink("../../posts/".$link);
    
    // Deleting Post From Database
    $queryDelete = "DELETE FROM posts WHERE id = '$id'";
    $exec = mysqli_query($con, $queryDelete);
    
    // Refresh Page
    echo("<meta http-equiv='refresh' content='1'>");
}
?>

If I remove $linkquery, $link, and unlink(...), then it works fine. Also, I don’t understand why I have to do location.reload() and return false or echoing the meta tag for the delete function to take the div off the side. I thought AJAX does this automatically?

Been struggling for hours, help would be greatly appreciated.

Qualtrics programming question (using javascript to create a bipolar slider)

I need to use bipolar sliders for a series of questions in Qualtrics. I saw some code on the Qualtrics community website to help get a label on the right hand side (otherwise, this is not possible for slider type questions). I saw one that recommended not using javascript (instead using <float: right> in html), but I can’t get that to work regardless of if I turn mobile on or off. I have found a solution — using javascript like this:

jQuery(".statement-container div").eq(0).append("<span style='float: left'>LEFT1</span>");
jQuery(".statement-container div").eq(0).append("<span style='float: right'>RIGHT1</span>");
jQuery(".statement-container div").eq(1).append("<span style='float: left'>LEFT2</span>");
jQuery(".statement-container div").eq(1).append("<span style='float: right'>RIGHT2</span>");

However, now I need to make sure the different sliders are randomized between participants. I can’t figure out how to do this because the javascript is what is placing the labels in their respective locations.

Any help on how to randomize when using javascript to put the labels in would be really helpful.

Alternatively, if there are any suggestions for getting the simpler solution of using html to work, then the randomization problem will be fixed (meaning, I would be able to use question randomization built into qualtrics). As noted, I tried messing with mobile settings and that did not help, I also tried expanding the window size and that also did not help.

Is it possible to have cookies for different domain in a same session?

For example, I have two web projects(LocalProject and serverProject) and they were deployed at localhost and server.com respectively.

Now I login the LocalProject so I have the sessionid in cookies under domain locahost
enter image description here

I want to have another sessionid for serverProject in cookies under domain server.com and try to login via fetch

const respLogin = await browser.fetch('server.com/web/login',{
    method: 'POST',
    headers: { 'Content-Type': 'application/json'},
    body: loginData
});

The request is succeeded and the server sent the sessionid to me
enter image description here

But the problem is I cannot find this sessionId in the Application panel. Why and how can I fix this problem.