How to use a separte js file in Laravel Blade Html?

How to use a js file outside Laravel Blade html?

Besides my layouts file, I have a single file welcome.blade.php for the html and it requires a fair amount of scripts. To improve neatness, I wanted to move the <scripts> from the bottom of welcome.blade.php into a separated .js file.

See below for current code, mainly a test to get things working.

welcome.blade.php

@extends('layouts')

@section('content')
  <div>
    Body Content
  </div>
@endsection

// Script added to the bottom of welcome.blade
// How to move into a separated file, like in resources/js/welcome.js 
// <script src='/js/welcome.js'></script> doesn't work
<script>
  alert('js works');
</script>

Even when I create a new welcome.js script inside the resources/js folder, linking via src or assets doesn’t work.

I don’t want to put it in the app.js (default laravel install folder structure), because then it’ll load in for EVERY page, instead of just welcome.js.

I’ve tried using stack, but the file doesn’t exist when using asset. However, it does work when writing the script itself into the push block. But then that’s not using a separate .js file anyway…

layouts.blade.php

<body>
...
@stack('scripts')
</body>
</html>

welcome.blade.php

...
@push('scripts')
  // Works when directly writing the script here
  // Trying to use `<script src="{{ asset('js/welcome.js' }}"></script>` fails
  // No js/welcome.js found. 
  <script>
    alert('js works');
  </script>
@endpush

How can I use a separate .js file inside a Laravel Blade HTML Template?

Edit

Did I actually need to make the welcome.js script public in webpack mix? It seems to work now after adding the additional .js line.

See answer.

Versions: Laravel 8

Javascript for-loop to populate a table

Can’t seem to wrap my head around the task given to me. I have a HTML file and an external JS file. The JS file has an array and needs a for-loop to populate a table with but I can’t seem to get the for-loop to to do anything. Best I can manage is getting the table headers to show.

What’s wrong with my for-loop and why won’t it populate the table?

I appreciate any help!

function buildCitiesList() {
  const cityListJSON = {
    cities: [
      {
        name: "Adelaide",
        state: "SA",
        text: "Lovely city on the Torrens River",
        avgrainfall: 547,
        sunnydays: 224,
      },
      {
        name: "Brisbane",
        state: "QLD",
        text: "Capital city of Queensland",
        avgrainfall: 1080,
        sunnydays: 261,
      },
      {
        name: "Canberra",
        state: "ACT",
        text: "Where the federal politicians are!",
        avgrainfall: 602,
        sunnydays: 246,
      },
      {
        name: "Darwin",
        state: "NT",
        text: "Crazy and funny folks, up north!",
        avgrainfall: 1812,
        sunnydays: 239,
      },
      {
        name: "Hobart",
        state: "TAS",
        text: "Beautiful but very chilly winters...",
        avgrainfall: 569,
        sunnydays: 193,
      },
      {
        name: "Melbourne",
        state: "VIC",
        text: "City with four seasons in one day",
        avgrainfall: 518,
        sunnydays: 185,
      },
      {
        name: "Perth",
        state: "WA",
        text: "A long drive but worth it!",
        avgrainfall: 734,
        sunnydays: 265,
      },
      {
        name: "Sydney",
        state: "NSW",
        text: "Prettiest harbour in the world!",
        avgrainfall: 1042,
        sunnydays: 236,
      },
    ],
  };

  mytable =
    "<table class='table'>" +
    "<tr><th>#</th><th>City</th><th>State</th><th>Comment</th><th>Avg Rainfall</th><th>Sunny Days</th><th>Best Activity</th></tr>";

  for (i = 0; i < 8; i++) {
    mytable +=
      "<tr><td>" +
      i +
      "</td><td>" +
      cities[i].name +
      "</td><td>" +
      cities[i].state +
      "</td><td>" +
      cities[i].text +
      "</td><td>" +
      cities[i].avgrainfall +
      "</td><td>" +
      cities[i].sunnydays +
      "</td></tr>";
  }
  mytable += "</table>";
  document.getElementById("table").outerHTML = mytable;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Task 6.3C</title>
    <meta name="author" content="" />
    <meta name="description" content="Conditions and Functions" />
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <!-- Latest compiled and minified CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
      integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
      crossorigin="anonymous"
    />
    <script src="citiesJSON.js"></script>
  </head>

  <body>
    <div class="container-fluid">

      <h1>Australian Capital Cities & Information</h1>
      <p>
        Click the button below to build and display a list of Australian Cities
        along with some interesting information.
      </p>
<main>
  <!--TO UPDATE-->
  <div id="table"></div>
  
      <input
        class="btn btn-primary"
        type="button"
        onclick="buildCitiesList()"
        value="Display Capital Cities"
      />
      </div>


</main>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
      integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

Tailwind CSS Grid Spacing Messed Up

I am trying to make a blog website with two columns for the posts. The first column displays one large-format post while the second displays 3 small-format posts (pictured below). However, when i do this to small-format posts seem to respect the spacing of the large-format post, even though they are in different columns. Here is a picture:

enter image description here

As you can see, I want the posts on the right side to be spaced evenly, but the second post starts at the end of the large-format post on the first column.

Here is my code:

import React, { useEffect, useState } from 'react'
import client from '../client'
import BlockContent from '@sanity/block-content-to-react'
import { Link } from 'react-router-dom'

function Main() {
    const [posts, setPosts] = useState([])

    useEffect(() => {
        client.fetch(
            `*[_type == "post"] {
                title,
                slug,
                body,
                author,
                mainImage {
                    asset -> {
                        _id,
                        url
                    },
                    alt
                },
                publishedAt
            }`
        ).then((data) => setPosts(data))
         .catch(console.error)
    }, [])

    return (
        <div className='grid lg:grid-cols-3 md:grid-cols-2 gap-8 m-4 '>
            {posts.slice(0, 1).map((p, i) => (
                <Link to = {`/blog/${p.slug.current}`} className=''>
                    <article key = {p.slug.current} className=''>
                        <img src = {p.mainImage.asset.url} alt = {p.title} className='' />
                        <div>
                            <p className='font-bold text-xl text-secondary'>{p.title}</p>
                            <p className='text-sm'>By Brandon Pyle | {new Date(p.publishedAt).toLocaleDateString()}</p>
                        </div>
                    </article>
                </Link>
            ))}
            {posts.slice(1, 4).map((p, i) => (
                <Link to = {`/blog/${p.slug.current}`} className='col-start-2 h-16'>
                    <article key = {p.slug.current} className='flex'>
                        <img src = {p.mainImage.asset.url} alt = {p.title} className='w-auto h-auto max-h-[80px]' />
                        <div>
                            <p className='font-bold text-xl text-secondary'>{p.title}</p>
                            <p className='text-sm'>By Brandon Pyle | {new Date(p.publishedAt).toLocaleDateString()}</p>
                        </div>
                    </article>
                </Link>
            ))}
        </div>
    )
}

export default Main

Please let me know if you have any ideas on how to fix this issue! Thanks.

SlateJS apply bold to regex match

I am trying to apply bold to **text** in slatejs editor and so far my attempts have been unsuccessful.
I came across this answer which seems to be a possible solution to the problem.

However, after modifying that answer it still refused to apply bold.

I tried adding match: n => Text.isText(n) and that made the whole paragraph bold.

Expected result:
**text** => **text**

Actual result:
**text** => **text**

How may I modify this to work as expected?

const withMarkdown = editor => {
    const { normalizeNode } = editor;

    editor.normalizeNode = entry => {
        const [node, path] = entry;

        if (!Text.isText(node)) {
            return normalizeNode([node, path]);
        }

        const boldMatch = node.text.match(/([*]{2})(.+?)([*]{2})/);
        if (!boldMatch) {
            return normalizeNode([node, path]);
        }

        let [searchMatch, asteriskMatch] = boldMatch;
        const { index: startIndex } = boldMatch;
        const endIndex = startIndex + searchMatch.length;

        /* does not apply bold */
        Transforms.setNodes(editor, { bold: true }, {
            at: {
                anchor: { path, offset: startIndex },
                focus: { path, offset: endIndex },
            }
        })

        normalizeNode([node, path]);
    }

    return editor;
}

THREE.JS fbx is recognized as a localhost link

I’ve been trying to write this Three.js project for a while now, and I seem to be running into a problem. When I try to use an FBX path-name as my custom 3d model then it just returns a 404 error. This is obviously because it is attaching the pathname to localhost:8080 but I have no idea how to fix it and cannot even fathom where to start looking to even get that information.

Here is the necessary information to determine the solution to my stupid problem

script.js

// const loader = new OBJLoader()
// import { OBJLoader, MTLLoader } from 'https://cdn.skypack.dev/@hbis/three-obj-mtl-loader'
// import objMtlLoader from 'https://cdn.skypack.dev/obj-mtl-loader';
import {FBXLoader} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/FBXLoader.js'
import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';

const path = new THREE.Path();


const loader = new FBXLoader();
loader.setPath('./models/')
loader.load('guard.fbx', (fbx) => {
    // this._target = fbx
    // this._target.scale.setScalar(0.035);
    // this._params.scene.add(this._target);
    scene.add(fbx)
});

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000)
const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xffffff)

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


const sphere_geometry = new THREE.SphereGeometry(1, 32, 16);
const sphere_material = new THREE.MeshBasicMaterial({color: 0x000000})
const sphere = new THREE.Mesh(sphere_geometry, sphere_material);
scene.add(sphere);

document.addEventListener("onkeydown", function(e){
    switch(e.KeyCode){
        case 37:
            console.log("Left")
            break
        case 38:
            console.log("top")
            break
        case 39:
            console.log("right")
            break
        case 40:
            console.log("bottom")
            break
    }
})

// loader.load("/Users/dmitri/Desktop/flame/models/fresh_fire_01 (1).obj", function(object){
//     scene.add(object)
// })

var run = function() {
    requestAnimationFrame(run);
    renderer.render(scene, camera)
}
run()

index.html

<html>
    <head>
        <style>
            body{
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
        <script src="/script.js" type="module"></script>
    </body>
</html>

File Structure

modules

–campfire.fbx

–fresh_fire_0 (1).obj

–guard.fbx

public

–index.html

–script.js

app.js


Pls help meh!

How to remove all parenthesis and their contents from a string using a regular expression or pure JavaScript and retain other text format

Currently I am entering text inside a text area and on clicking the submit button of my form, I am applying some changes to the text mainly using .replaceAll(); js methods and printing it out as a paragraph inside a div.

If I enter text that already has newlines as well as parenthesis into the text area, I want my script to strip/remove all parenthesis as well as the contents inside parenthesis AND keep all newlines as they are.

I have tried the following regex + js function with the sample text however there are some formatting issues that get introduced (some newlines are removed and text following parenthesis ends up on the same line as the text in the previous line where parenthesis was removed)

regex+js code:

updatedText = updatedText.replaceAll(/s*(.*?)s*/g, '');

Sample input:

06.abbaa(bbbbadf)
01.lijer      ttt
06.foo(sample)dddddddddd(garbage)
06.text(lksdhfljkld)20001(kkkkkksssss)
01.asdfg
13.fffffffff(fdsgggg/asdfasdf)
03.ggggggg(defg/abc)
18.abc     123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh(moreblah/blah)
15.2035number(test)(test0/2test)
12.testing morewords
03.random(blahhh)(blahahaha/morerandomstuff)
17.anotherrandomtextstring
11.string
testy(mctest)
isTestingStrings
11.string
11.string
11.string

the result outputted where lines are combined when they are not suppose to be is this:

06.abbaa01.lijer ttt
06.foodddddddddd06.text2000101.asdfg
13.fffffffff03.ggggggg18.abc 123abc
blahblah
qqqqqq
anon
06.barbarbar
10.foobar
18.fooistbar
12.blahhhh15.2035number12.testing morewords
03.random17.anotherrandomtextstring
11.string
testyisTestingStrings
11.string
11.string
11.string
  • for example “testy” and “isTestingStrings” should be on 2 separate lines.
  • each line could have any number of(0 or more) “(xxxx…)” parenthesis with content and in these cases should also retain the newlines.

Why does replacing the matched text with an empty string result in the newline character being removed from the string, and how can I resolve this issue in my script. Is there better regex to handle this or would this require writing a custom js parser?

Trying to randomize the padding of an element to create a small rain effect

I am trying to randomize the position of diagonal falling lines using padding. Whenever I try to use the below code the lines do not change. However, if I add style:padding-left:300px to the style of the rain and remove my JavaScript I can move the element to the right by 300px. I can theoretically do this and map out each line however I would like to know how to randomize the padding, preferably dynamically and not just onpageload

<script>
function randomnumber(min, max) {
  var rn = Math.random() * (max - min) + min;
  document.querySelector('#rain .line').style.padding = rn+'px';
}

</script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<style>   
body{
   background:#000000;
   margin: 100px; 
}

.line {
 height: 1px;
 width: 40px;
 background: white;
 transform: rotate(45deg);
}

.rainsize{
height:100%;
width:100%;
opacity:0%;
z-index:1000;
position:fixed;
width:100%;
top:0px;
left:0px;
}

.move{
position:relative; 
animation-name: moverain;
animation-duration: 3s;
animation-iteration-count: infinite;
}
@keyframes moverain {
0%{top:0px;left:0px;}
100%{top:1000px;left:1000px;}
}

</style>


<div onpageload="randomnumber('10','1000')"class="rainsize"></div>


<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>

<div id=rain class="move">
  <div class="line""></div> 
</div>









How to prevent Nav Menue toggle from changing y position

I’m very new to WordPress and I’m experiencing a bug where the y position of the page gets updated involuntarily.

I’m using a floating menu but each time I toggle the Nav menu it resets my view to the top of the page (not very useful for links that point to a specific position on the page that are stored within the nav menu).

The element in question

<button type="button" class="navbar-toggle">
    <span class="screen-reader-text"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Toggle sidebar &amp; navigation</font></font></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
</button>

After some research the closest I’ve been able to identify what is causing this issue is the line of code e(document.body).toggleClass("side-nav-open") in scripts.min.js?ver=1.6.0

function s() {
    e(document.body).toggleClass("side-nav-open").addClass("side-nav-transitioning"); <-----
    const t = e("#slider").data("flexslider");
    t && (e(document.body).hasClass("side-nav-open") ? (i = t.playing,
    t.playing && t.pause()) : i && t.play());
    let s = !1;
    e(".site").one("transitionend", function() {
        e(document.body).removeClass("side-nav-transitioning"),
        s = !0
    }),
    setTimeout(function() {
        s || e(document.body).removeClass("side-nav-transitioning"),
        n.trigger("resize")
    }, 230)
}
e(".navbar-toggle, .side-nav-overlay").on("click touchend", function() {
    e(document.body).hasClass("side-nav-transitioning") || (s(),
    e(document.body).hasClass("side-nav-open") ? n.width() <= 640 ? t.find(".side-nav__close-button > button").focus() : t.find("nav.mobile-menu-wrapper ul li:first-child").focus() : t.find(".header-navigation-wrapper button.navbar-toggle").focus(),
    e.fn.keepFocusInMobileSidebar())
}),

using break points I was able to stop at the line e(document.body).toggleClass("side-nav-open").addClass("side-nav-transitioning"); and executing e(document.body).toggleClass("side-nav-open") in the console I saw my page jump to the top.

I’m hoping someone could help me complete my research and identify why my page no longer stays put when the navigation menu is clicked. Since I very rarely work on WordPress I’m not sure what info would be pertinent and what information would be noise, please post in the comments the data that would be most beneficial to trouble shoot this issue.

The current active theme is Inspiro version 1.6 https://www.wpzoom.com/free-wordpress-themes/inspiro-lite/

How can I disable the save credit card info popup in the chrome on Android device?

I am try to run some automation scripts writing with WD.js on the lamda cloud server,but I can not handle this popup,any suggestions?Thanks so much!

Here is my capabilities setting,but it seems not work.

  exports.config = {
  seleniumHost: 'hub.lambdatest.com',
  seleniumPort: 80,
  test: '../tests/demo.js',
  capabilities: [{
        build: "test demo",
        name: "work flow",
        platform: "Android",
        deviceName: "Huawei P20 Pro",
        platformVersion: "9",
        acceptSslCerts: true,
        visual: "true",
        browserName: 'chrome',
        chromeOptions: {
          prefs: {
            credentials_enable_service: false,
            'profile.password_manager_enabled': false,
            'profile.default_content_setting_values.notifications': '2'
        },
         args: ['--ignore-certificate-errors',
           '--disable-features=Translate',
           '--disable-popup-blocking',
           '--disable-notifications',
           '-incognito']
    }
    }]
}

enter image description here

I want to get array of multiple emp for particular Manager

I have a data where each emp has manager, i’m trying to get an array with emp with perticular manager. for ex: Manager1 with array of all his emp and Manager2 with all his emp. i have pasted a sample out.how can i get that?

const response = [
    {
        "emp":{
            "firstName":"Abhi"
        },
        "manager":{
            "firstName":"Ashok"
        }
    },
    {
        "emp":{
            "firstName":"Lokesh"
        },
        "manager":{
            "firstName":"Ashok"
        }
    },
    {
        "emp":{
            "firstName":"Harish"
        },
        "manager":{
            "firstName":"Ashok"
        }
    },
    {
        "emp":{
            "firstName":"Kaushik"
        },
        "manager":{
            "firstName":"Sunil"
        }
    },
]
            
            

Sample output i need:

[
    {
        "manager":"Ashok",
        "emp":[
            {
                "firstName":"Abhi"
            },
            {
                "firstName":"Lokesh"
            },
            {
                "firstName":"Harish"
            }
        ]
    },
    {
        "manager":"Sunil",
        "emp":[
            {
                "firstName":"Kaushik"
            }
        ]
    }
]

How to run a request in a function in Nodejs?

I have the following code to run a request and return the result in NodeJS :

const https = require('https')

async function GetStatus(HostName, Path) {  
    const options = {hostname: HostName,port: 443,path: Path,method: 'GET'}                     
    const req = https.request(options, res => {     
        res.on('data', d => {
            var result = JSON.parse(d);
            console.log('A - the status is ' + result.status);
            return result.status;               
        })
    })
    
    req.on('error', error => {console.error(error)});
    req.end();  
}

async function T() {
    var x = await GetStatus('www.domain.com', '/path');     
    console.log('B - The status is ' + x);
}

T();

I’m trying to run the function GetStatus to get some results based on the https request.

When running this code, I’m getting A – The status is something while the output of the function is B – The status is undefined

Does anyone know how to solve that please ? such that the function returns the result as expected instead of undefined.

Thanks.
Regards,

How can I stop the browser from url-encoding for react js form for POST data values with password field value included with #

I wanted to stop URL encoding for reactjs form password filed, when I entered the ‘#” in password browser automatically converts it into URL encoding format like ‘%23’, want to stop that or any other solution for this issue.

form is like:

              labels={{
                        passwordInputLabel: 'Password',
                        passwordPlaceHolder: 'Enter password',
                        loginButtonMessage: 'Logging In'

All my requests to Firestore are classified as unverified because of AppCheck?

I enforced Firebase AppCheck for Firestore.

Now, when I try to access data, I get an error:

    firebase
      .firestore()
      .doc(firestoreRoot.configs.priceIds._pathUrl)
      .get()
      .then((v) => console.log(v.data()));

appcheck error

In Firebase, it says all my requests are unverified:

enter image description here

This only happens for firestore.

Is there something else I must do?

I enabled AppCheck in my app using:

  const appCheck = firebase.appCheck();
  appCheck.activate("MY_SITE_KEY", true);

I tried disabling AppCheck in the firebase console, and now all my requests are accepted.

Trying to get value from object using external url but

When i start bot console say:

Online with undefined/5

and when 10 secconds are passed give this error:

undefined:1
[object Promise]
^
SyntaxError: Unexpected token o in JSON at position 1

My Code:

let jogadores
client.on("ready", async () => {

async function players_online() {
    const response = fetch(`http://ip:port/dynamic.json`);
    const data = JSON.parse(response);
    jogadores = data.clients;


}

async function autoconnect() {

    if (jogadores === -1) {
        console.log('Offline');

    } else {
        console.log('Online with ' + jogadores + '/5')

    }
}
autoconnect()

setInterval(() => {
    client.user.setStatus('dnd');
    client.user.setActivity(`Online with ${jogadores} players.`, { type: 'PLAYING' })
    players_online()
}, 10000)

})

The script does not send the changed data

I encountered a problem that my script does not send the changed data to Discord.
All other functionality works well. What could be the problem?

Here’s the code:

var send = WebSocket.prototype.send;

WebSocket.prototype.send = function (data) {
    if (WebSocket.prototype.toString.call(data) === "[object ArrayBuffer]") {
        var array = new Uint8Array(data);
        var modules = DiscordNative.nativeModules.requireModule('discord_erlpack');
        var unpackeddata = modules.unpack(array);
        console.Log("(WS LOG) received wsdata -> " + JSON.stringify(unpackeddata));
        if (unpackeddata.op == 4) {
            unpackeddata.d.self_mute = true;
            unpackeddata.d.self_deaf = true;
            unpackeddata.d.self_video = true;
            console.log("WS Packet 4")
        } else if (unpackeddata.op == 12) {
            for (var stream of unpackeddata.d.streams) {
                stream.quality = 1;
                stream.max_bitrate = 8000;
                stream.max_framerate = 10;
                console.log("WS Packet 12")
            }
        } else if (unpackeddata.op == 24) {
            unpackeddata.d.type = 123;
            unpackeddata.d.limit = 123;
            unpackeddata.d.offset = 123;
            console.log("WS Packet 24");
        }
        var packed = modules.pack(unpackeddata);
        var buffer = packed.buffer;
        array = new Uint8Array(buffer);
        data = array;
    } else {
        console.log("(WS LOG) received wsdata -> " + data);
    }
    return send.apply(this, [data]);
}