How to I re-enqueue WordPress plugins using JS?

This is a bit of an odd question, I have implemented Barba.js (a PJAX plugin for handling seamless page transitions) on a WordPress site. Use of the plugin requires re-initialisation of scripts between pages. I have this working correctly except for when a WordPress plugin is concerned.

When a page loads in directly (i.e via explicit URL or hard refresh, the plugin renders content correctly, however if I navigate away and back to the page via the menu inside Barba the plugin doesn’t re-initialise. Please see the below explanation:

example.com/page1 (contains plugin generated content which loads correctly)

navigate to new page via website menu inside Barba container

example.com/page2 (loads seamlessly and other custom animations work as expected)

navigate back to the first page via website menu inside Barba container

When I arrive at example.com/page1 again the plugin content does not render at all. I believe this is because scripts are not being re-initialised.

I’ve read that WordPress uses WP_ENQUEUE_SCRIPT and WP_ENQUEUE_STYLE to initialise plugin scipts and styles, but this is PHP, which is not my forte and as far as I know I can’t hook into this?

Ideally, I need to be able to reinit the plugin(s) like this so that it remains in context to other custom jS animations:

function reinitWPPlugin() {
   //do re-initialisation here
}

Can anyone point me in the right direction to reinit WordPress plugins?

Removing a Content Security Policy in React is still active?

I have a React Router app, and I need to have a content security policy just for one of the routes. So, for that route I have this inside a component:

  useEffect(() => {
    const csp = document.createElement('meta');
    csp.httpEquiv = "Content-Security-Policy";
    csp.content = "default-src 'none'; style-src embed.typeform.com; script-src 'self' embed.typeform.com; frame-src form.typeform.com";
    document.head.append(csp);
    return () => {
      document.head.removeChild(csp);
    }
  }, []);

My problem is that even though the code works, and the meta element is added and deleted as intended, Chrome doesn’t remove the policy internally and it is always present once I have attached it once. So i get a lot of default-src 'none' errors on the other routes.

Any idea what is wrong?

tippy.js with title attribute not work on dynamic content

I use Tippy for all title tags on my site with the following call.

tippy('input[title],a[title],img[title]:not(.cke_hand),small[title],table[title],div[title],span[title],i[title],li[title],p[title]', {
        arrow    : true,
        animateFill: false,
        placement: 'bottom',
        delay    : 5,
        distance : 15,
        maxWidth : 350,
        followCursor    : false,
        dynamicTitle    : true,
        allowHTML       : true,
        theme           : 'custom',
        zIndex          : 999999,
        ignoreAttributes: true,
        content(reference) {
            const title = reference.getAttribute('title');
            reference.removeAttribute('title');
            return title;
        },
    });

But when I dynamically add a div to the body with content that also has a title attribute, the tooltip doesn’t work there.

I have already put the typing call into a function and called it again in the callback of the div generation but it still doesn’t work.

I hope you can help me

How do I render a list on API response in vue 3?

I am new to vue and trying to render a list of items from an API response

<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import ServiceCard from './components/ServiceCard.vue'
import { parse, stringify } from 'yaml'
import { onMounted, onUpdated } from 'vue'
import Vue from 'vue'

interface ServiceAPIResponse { host: string, protocol: string, services: [{ subdomain: string, apikey: string }] };

let yaml: ServiceAPIResponse;

onMounted(() => {
  fetch('https://api.my.domain/').then((resp) => {
    resp.json().then((data: ServiceAPIResponse) => {
      yaml = data;
      console.log(yaml);
    });
  });
});

onUpdated(() => {
  console.log('onupdated');
});

</script>

<template>
  <div>
    <img alt="Vue logo" src="./assets/logo.png" />
    <ul v-if="yaml">
      <li v-for="service in yaml.services" :key="service.subdomain">
        <ServiceCard :name="service.subdomain" :host="yaml.host" :subdomain="service.subdomain" />
      </li>
    </ul>
  </div>
</template>

Coming from react, I would expect a re-render to occur when I update the value of yaml. I have tried wrapping it with reactive() but I don’t understand vue well enough.
I don’t understand why my v-if remains falsy after I set yaml‘s value.

Is v-if even the right way to handle this?

Discordjs v12 | cannot find module ../undefined/help.js

My bot has a command located in /commands/developer/reload.js and it’s purpose is to unload a command then load it again. But when trying to find the commands folder it throws an error saying Cannot find module '../undefined/help.js' but the path is ../misc/help.js

Code:

const fs = require('fs');

module.exports = {
    name: 'reload',
    description: 'Reloads a command',
    args: true,
    usage: '<command_name>',
    cooldown: 1,
    aliases: ['rl', 'restart'],
    execute(message, args) {
        const commandName = args[0].toLowerCase();
        const command = message.client.commands.get(commandName) || message.client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

        if(!command) {
            return message.channel.send(`There is no command called '${commandName}'`);
        }

        const commandFolders = fs.readdirSync('./commands');
        const folderName = commandFolders.find(folder => {
            fs.readdirSync(`./commands/${folder}`).includes(`${command.name}.js`);
        })

        delete require.cache[require.resolve(`../${folderName}/${command.name}.js`)];

        try {
            const newCommand = require(`../${folderName}/${command.name}.js`);
            message.client.commands.set(newCommand.name, newCommand);
            message.channel.send(`Command '${newCommand.name}' was reload successfully`)
        } catch (err) {
            console.error(err);
            message.channel.send(`There was an error while reloading a Command.`)
        }
    }

}

Get item from js object with partially known key

Let’s say you dont know the number before the letter here.

var obj = {'1234 x': 1, '32145 y': 2}

How would you retrieve the value 1 from this object.

The normal way of doing this would be:

obj['1234 x'] // 1

But what if you only knew part of the key: 'x' (what comes after the first space)

var key = '1234 x',
    known_key = key.split(' ')[0] // 'x'

How would you be able to retrieve this value?

obj['% ' + known_key]
// % represents all possible strings

Npm run dev on nuxt.js project isn’t working on Mac M1

I don’t know if it has something to do with the mac but on my other windows computer everything is fine the display is good but when I switch to my mac and run an npm run dev there are a few pages that don’t work not display.

I show you with the screenshots:

Here is on Mac M1 :

enter image description here
Nothing works on the navigation bar, even when I type in the url to access a page it doesn’t work

Here is on Windows pc :

enter image description here

I wanted to know if this has ever happened to anyone because I don’t understand the problem. The version of node.js on the mac is 16.13.0 and on my windows computer it’s a version 15 but I think below 16 it’s not compatible on mac M1. Thanks

Uncaught (in promise) SyntaxError: Unexpected end of input Node.js

I am making a component that should transfer the data in file controllers/hello.js(backend) to App.js(frontend in React.js app) which is imported from the router/collector components/hello.js

My components/hello.js looks like this:

import { React } from 'react'
import { useEffect, useState } from 'react';


export const Hello = ()=>{
    const[initialState, setInitialState] = useState([], )

    useEffect(()=> {
        fetch('http://localhost:3001/api/', {mode: "no-cors"})
            .then(response => response.json()).then(data => console.log(JSON.parse(data)))
    //         if (res.ok){
    //             return res.json()
    //     }
    //     }).then(jsonResponse => console.log(jsonResponse))
    },[])

    // console.log(initialState)
    console.log("should work ")
    return (<div>Hello</div>)
}

And I get this error:

        
       Uncaught (in promise) SyntaxError: Unexpected end of input
    at hello.js:9:1

when I check the API the only response I get is this
enter image description here
but it should be matching what’s in localhost:3001/api/ or what’s in controllers/hello.js which is
enter image description here

Do you have any idea how I can solve this? Any help is appreciated.

Trying to dynamically change values of html slider with jquery?

I’m trying to create three sliders with R, G, B values and that gives in result the values you’re sliding and a div with the resulting color.

I’m having a really hard time and I don’t get why. Please keep in mind I’m really new to jQuery, so there might (and probably there are) some really stupid errors in the syntax.

$(document).ready(function() {
  $(".slider").addEventListener("input", function() {
    let red = $("#red").value;
    let green = $("#green").value;
    let blue = $("#blue").value;
    $("#colorbox").css("background-color", "rgb(" + red + "," + green + "," + blue + ")");
    $("#rgboutput").text = "RGB(" + red + "," + green + "," + blue + ")";
    $("#hexoutput").text = "HEX(#" + rgbtohex(red) + rgbtohex(green) + rgbtohex(blue) + ")";
  }, false)

  function rgbtohex(color) {
    var hex = parseInt(color).toString(16);
    return hex.length == 1 ? "0" + hex : hex;
  }
})
body {
  background-color: #0075FF;
}

.container {
  background-color: #ffffff;
  margin: auto;
  width: 30%;
  padding: 20px 0;
  box-shadow: 20px 20px 30px rgba(0, 0, 0, 0.2);
  font-family: 'Work Sans', sans-serif;
  font-size: 20px;
  font-weight: 500;
  color: #142b37;
  border-radius: 5px;
}

.center {
  display: grid;
  justify-items: center;
}

.wrapper {
  width: 100%;
  text-align: center;
}

input[type="range"] {
  display: inline-block;
  width: 60%;
  margin-left: 10px;
  margin-top: 25px;
}

.output {
  display: inline-block;
  text-align: center;
  margin: 20px 0;
  background-color: blue;
  color: #ffffff;
  padding: 10px 30px;
  font-size: 18px;
  letter-spacing: 0.5px;
  border-radius: 2px;
}

#colorbox {
  width: 3em;
  height: 3em;
  margin: 3% solid black;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<div class="container">
  <div class="center">
    <div class="wrapper">
      <p>R</p><input type="range" min="0" max="255" value="0" class="slider" id="red" autocomplete="off">
    </div>
    <div class="wrapper">
      <p>G</p><input type="range" min="0" max="255" value="0" class="slider" id="green" autocomplete="off">
    </div>
    <div class="wrapper">
      <p>B</p><input type="range" min="0" max="255" value="0" class="slider" id="blue" autocomplete="off">
    </div>
    <div class="output" id="rgboutput">
      <p>RGB(0, 0, 0)</p>
    </div>
    <div class="output" id="hexoutput">
      <p>HEX(#000000)</p>
    </div>
    <div id="colorbox"></div> <br>
  </div>
</div>

Execute search query based on input field value with quotes or without quotes

I have an input field which value must be checked if it contains words with quotes or not and based on that I will need to execute an ajax call.

I tried this way but isn’t working as expected

        let siteUrl= window.location.protocol + "//" + window.location.host;

        let queryUrl;
        let queryUrl2;

        const searchTerm = document.getElementById("searchedWord").value.replace("'", "''");

        if (searchTerm[0] == ' " ' && searchTerm[searchTerm.length - 1] == ' " ') {
            queryUrl = siteUrl + "/api/search/query?querytext='" + searchTerm + "'&selectproperties='Path%Url'&sourceid='xxxx-xx-xxxx'";
        } else {
            queryUrl2 = siteUrl + "/api/search/query?querytext='" + searchTerm + "'&selectproperties='Path%Url'&sourceid='xxxx-xx-xxxx'";
        }

        $.ajax(
            {
                // call queryUrl based on what is found in input value
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: success,
                error: error
            }
        );

Hover is still active after action on the phone

I got this from somewhere but when I tap on it on the phone (on PC it’s ok) it stays with hover attributes = no BG and black colour:

HTML

<a id="back2Top" title="Top" href="#">&#10148;</a>

CSS

#back2Top {
    width: 40px;
    line-height: 40px;
    overflow: hidden;
    z-index: 999;
    display: none;
    cursor: pointer;
    transition: background-color 0.2s linear;
    -moz-transform: rotate(270deg);
    -webkit-transform: rotate(270deg);
    -o-transform: rotate(270deg);
    -ms-transform: rotate(270deg);
    transform: rotate(270deg);
    position: fixed;
    bottom: 39px;
    right: 0;
    background-color: #8db500;
    color: #fff;
    text-align: center;
    font-size: 30px;
    text-decoration: none;
}
#back2Top:hover {
    background-color: transparent;
    color: #000;
}
@media only screen and (max-width: 767px) {
#back2Top {
    bottom: 0px;
}}

And JS

$(window).scroll(function() {
    var height = $(window).scrollTop();
    if (height > 100) {
        $('#back2Top').fadeIn();
        $('.open').css('background', 'rgba(141, 181, 0, 0.5)'); //these 3 are for something different
        $('.closed').css('background', 'rgba(201, 0, 10, 0.5)');
        $('.warn').css('background', 'rgba(255, 113, 0, 0.5)');

    } else {
        $('#back2Top').fadeOut();
        $('.open').css('background', 'rgba(141, 181, 0, 1)'); //these 3 are for something different
        $('.closed').css('background', 'rgba(201, 0, 10, 1)');
        $('.warn').css('background', 'rgba(255, 113, 0, 1)');
    }
});
$(document).ready(function() {

    $("#back2Top").click(function(event) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });

});

What is wrong there? Or what did wrong?
×I don’t know what to add more here, it won’t let me post it because of mostly code.×
Thank you.

Localized npm package for antd

I want to create a localized package using umijs and father as build tool. When I try to import the package into my main application (created with antd) it seems that the defined locales are missing as the main projects ConfigProvider does not look them up in the node_modules folder.

Are there any suggestions or workarounds for this issue?