Rails 6.1 – JS stops working after clicking on any button

I have a few JS functions linked to application.html.erb through channels.

They all work fine when the page is loaded. However, if I click any button on my page (href=””), JS seems to stop working and none of my functions apply anymore.

Here’s the application.html.erb file:

<!DOCTYPE html> <html>   <head>
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload', defer: true %>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>   </head>

  <body>
    <%= render 'shared/navbar' %>
    <%= yield %>
    <%= render 'shared/footer' %>
    <%= render 'shared/modal' %>   </body> </html>

One of the functions:

var dropdownMenu = document.querySelector(".dropdown-menu");

function triggerDropdown() {

  dropdownMenu.addEventListener("click", (event) => {

    var dropdownReveal = document.querySelector(".dropdown-container");
    var closingBtn = document.querySelector(".closing-btn");
    var openingBtn = document.querySelector(".dropdown-menu img");

    if (dropdownReveal.style.display == 'block') {
      dropdownReveal.style.display = 'none';
      closingBtn.style.display ='none';
      openingBtn.style.display = 'block';
      
    } else {
      dropdownReveal.style.display = 'block'
      closingBtn.style.display ='block';
      openingBtn.style.display = 'none';
      
    };
  });
}

triggerDropdown();

The application.js file:

 // This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

And the index.js:

// Load all the channels within this directory and all subdirectories.
// Channel files must be named *_channel.js.

const channels = require.context('.', true, /_channel.js$/)
channels.keys().forEach(channels)

Any help would be highly appreciated 🙂

VueJS: Process is not defined

Trying to add Node modules, Vuesax to Frappe/Erpnext,

While adding import statements, throws ReferenceError: process is not defined from (vue.runtime.esm.js:383:18)

Note: few modules are working perfectly, eg. @morioh/v-perfect-scrollbar

Frappe: 12.18
Vue: 2.6.8

How do I hide the undrawn side of a polygon during draw mode of polygon using mapbox-gl-draw?

The normal function of the polygon draw tool of mapbox-gl-draw, shows the polygon that would be created if you clicked the original point from where you started.

enter image description here

But what I would like is to NOT show the line that hasn’t yet been drawn by the user during draw mode.

In this image, the left side and the bottom side are fine because the user placed the top point and the second point at the bottom.
But I do not want to see line connecting where my cursor is to the original point.

I am able to remove the fill color by changing the fill styling but I am unable to hide the “ghost” line as it uses the same stroke as the other user-drawn lines.

I have used the section “Lines and polygons” from this link:
https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/EXAMPLES.md

What I have tried to edit:

{
    id: "gl-draw-polygon-stroke-active",
    type: "line",
    filter: ["all", ["==", "$type", "Polygon"], ["!=", "mode", "static"]],
    layout: {
      "line-cap": "round",
      "line-join": "round",
    },
    paint: {
      "line-color": "#D20C0C",
      "line-dasharray": [0.2, 2],
      "line-width": 3,
    },
  }

But this changes the stroke of the “ghost” line as well.
Is it possible to just hide the ghost line or do I need to make a custom polygon implementation of mapbox-gl-draw polygon mode?

Threejs, “Texture marked for update but image is incomplete” while using uniforms, no work why?

I am following a tutorial and I can’t get my image to load. I understand there is an issue with async loading of the texture but I don’t know how to resolve it with the current way it is set up. Somehow it works in the tutorial but I can’t get it to work. I am also using Vite for the build while the tutorial’s module bundler is Parcel. That maybe causing the issue just because the sequence of how everything is run but back to topic on hand. I don’t know how to resolve it.

import './style.css'

document.querySelector('#app').innerHTML = `
<div class="content">
<a href="inside.html" class="item">
  <img src="nohem.png" class="js-image" alt="">
  <h2>Some title</h2>
  <p>Andsome very interesting description.</p>
</a>

<a href="inside.html" class="item">
  <img src="nohem.png" class="js-image" alt="">
  <h2>Some title</h2>
  <p>Andsome very interesting description.</p>
</a>
<div id="container"></div>
`

import * as THREE from "three";
import fragment from './shaders/fragment.glsl'
import vertex from './shaders/vertex.glsl'
import testTexture from './nohem.png';
import * as dat from 'dat.gui';
import { TimelineMax, CSSPlugin, ScrollToPlugin, Draggable } from "gsap/all"; 
import ASScroll from '@ashthornton/asscroll';


export default class Sketch {
  constructor(options){
    this.container = options.domElement;
    this.width = this.container.offsetWidth;
    this.height = this.container.offsetHeight;

    this.camera = new THREE.PerspectiveCamera( 30, this.width/this.height, 10, 1000 );
    this.camera.position.z = 600;

    this.camera.fov = 2*Math.atan(( this.height/2 )/600) * 180/Math.PI;

    this.scene = new THREE.Scene();

    this.renderer = new THREE.WebGLRenderer( {
       antialias: true,
      alpha: true } );
    this.renderer.setPixelRatio(window.devicePixelRatio); //2 pretty 1 less resources
    this.container.appendChild(this.renderer.domElement);
    // this.controls = new OrbitControls(this.camera, this.renderer.domElement);

    this.time = 0;
    this.setUpSettings();
    this.resize();
    this.addObjects();
    this.render();
    this.setupResize();
  }

  setUpSettings(){
    this.settings = {
      progress: 0
    }
    this.gui = new dat.GUI();
    this.gui.add(this.settings, "progress", 0, 1, 0.001);
  }

  resize(){
    this.width = this.container.offsetWidth;
    this.height = this.container.offsetHeight;
    this.renderer.setSize( this.width, this.height );
    this.camera.aspect = this.width/this.height;
    this.camera.updateProjectionMatrix();
  }

  setupResize(){
    window.addEventListener('resize', this.resize.bind(this));
  }

  addObjects(){
    this.geometry = new THREE.PlaneBufferGeometry(1, 1, 100, 100);
    this.material = new THREE.ShaderMaterial({
      uniforms: {
        time: { value: 1.0 },
        uProgress: { value: 0 },
        uTexture: {value: new THREE.TextureLoader().load(testTexture)},
        uTextureSize: {value: new THREE.Vector2(100, 100)},
        uCorners: {value: new THREE.Vector4(0, 0, 0, 0)},
        uResolution: { value: new THREE.Vector2(this.width,this.height) },
        uQuadSize: { value: new THREE.Vector2(300, 300)}
      },
      vertexShader: vertex,
      fragmentShader: fragment,
    })

    this.tl = gsap.timeline()
    .to(this.material.uniforms.uCorners.value,{
      x:1,
      duration: 1
    })
    .to(this.material.uniforms.uCorners.value,{
      y:1,
      duration: 1
    }, 0.1)
    .to(this.material.uniforms.uCorners.value,{
      z:1,
      duration: 1
    }, 0.2)
    .to(this.material.uniforms.uCorners.value,{
      w:1,
      duration: 1
    }, 0.3)
    
    this.mesh = new THREE.Mesh( this.geometry, this.material );
    // this.scene.add( this.mesh );
    this.mesh.position.x = 300
    this.mesh.scale.set(300,300,1);

    this.images = [...document.querySelectorAll('.js-image')];
    this.materials = [];

    this.asscroll = new ASScroll()
    this.asscroll.enable();

    this.imageStore = this.images.map(img=>{
      let bounds = img.getBoundingClientRect();
      let m = this.material.clone();
      this.materials.push(m);
      let texture = new THREE.Texture(img);
      texture.needsUpdate = true;

      m.uniforms.uTexture.value = texture;


      let mesh = new THREE.Mesh(this.geometry, m);
      this.scene.add(mesh);
      this.mesh.scale.set(bounds.width, bounds.height, 1);
      return {
        img: img,
        mesh: mesh,
        width: bounds.width,
        height: bounds.height,
        top: bounds.top,
        left: bounds.left,        
      } 
    })
  }

  render(){
    this.time += 0.05;
    this.material.uniforms.time.value = this.time;
    this.material.uniforms.uProgress.value = this.settings.progress;
    this.mesh.rotation.x = this.time / 2000;
    this.mesh.rotation.y = this.time / 1000;
  
    this.renderer.render( this.scene, this.camera );
    requestAnimationFrame(this.render.bind(this))
  }
}

new Sketch({
  domElement: document.getElementById('container')
});

Override setTimeout ajax post

I’m trying to post the current date to a page php, I’ve already the date which evolves dynamically in a value of the span “timestamp” but I need to override the data of the post, because I have the issue “Uncaught SyntaxError: missing ] after element list”, so I think data become an array because of the settimeout, but I only need the latest value of the date. Can you please help me? Here is my ajax script:


    <script>
        setTimeout($.ajax({
            type:"POST",
            url: "name.php",
            data: 'date='+$("timestamp").val()
        }),5000);
    </script>

converting liquid statement to JS

I have a liquid file which checks to see if products have a certain tag of ‘bundle’. If this is true certain code is executed else other code is executed. (see below):

{% if current_variant.compare_at_price != blank and current_variant.compare_at_price > current_variant.price %}
  {% if product.tags contains 'bundle' %}
    {% assign bundle_on_sale = true %}
  {% endif %}
{% endif %}

<div class="product-details-price-snippet" >
  <div data-product-compare-at-price>
    {% if bundle_on_sale %}
      <span data-product-price >
        {{ current_variant.price | money }}
      </span>
      <br>
      <p>Worth: {{ current_variant.compare_at_price | money }}</p> 
    {% else %}
      <span data-product-price >
        {{ current_variant.price | money }}
      </span>
    {% endif %}
    </div>
</div>

I also have a JS file which checks to see if a product is on sale:

var onSale = data.compare_at_price_min > data.price_min;
var priceVaries = data.price_min != data.price_max;

function buildPrice(data) {
        var html = '';
        
        if (boostPFSThemeConfig.custom.show_price) {
            html = '<p class="boost-pfs-filter-product-item-price">';
            if (onSale) {
                
                html += '<span class="boost-pfs-filter-product-item-sale-price">' + Utils.formatMoney(data.price_min) + '</span>';
                html += '<s>' + Utils.formatMoney(data.compare_at_price_min) + '</s> ';
            } else {
                if (priceVaries) {
                    html += '<span class="boost-pfs-filter-product-item-price-from-text">' + (boostPFSThemeConfig.label_basic.from) + ' '+ '</span>';
                }
                html += '<span class="boost-pfs-filter-product-item-regular-price">' + Utils.formatMoney(data.price_min) + '</span>';
            }
            html += '</p>';
        }

        return html;
    }

What I now need to do is write the liquid if statement as shown above, as a JS if statement and have it inside the ‘buildPrice’ function (some sort of else if statement to include it into the function).

sum object value in javascript by name

I have a data that type is object and I want to sum the value1 + value 2 as totalValue per each name by using for

//this is my object  
{
111:{name:'a', value1: 2 , value2: 2},
222:{name:'b', value1: 3 , value2: 3},
333:{name:'c', value1: 4 , value2: 4},
 }
 
 // this is the result that I expected
 {
 {name:'a' , totalValue:4},
 {name:'b' , totalValue:6},
 {name:'c' , totalValue:8},
 }

   

Javascript-Google App Script. I’m getting TypeError: Cannot read property ‘map’ of undefined

I have this code in Google Docs, I’m trying to create a registry sheet with data from the other sheets, but I keep getting TypeError: Cannot read property ‘map’ of undefined. What could be the problem?

function processData(sheetData){

 var transpose = m => m[0].map((x,i) => m.map(x => x[i]))
 
 var data = sheetData.map(x=>x.slice(0,lastRow))
 
 data[1] = data[1].map((l => (v, i) => l = v === ''  ? l : v)());
 var transposedData = transpose(data)
 transposedData[0] = transposedData[0].map((l => (v, i) => l = v === ''  ? l : v)());
 data = transpose(transposedData)
 
 var dataFilterProjects = data.filter(row=> row.slice(2,).map(j=> (j!='') ? 1 : 0).reduce((a, b) => a + b, 0)!=0)
 var dataFilterDays = transpose(transpose(dataFilterProjects).filter(row=> row.slice(4,).map(j=> (j!='') ? 1 : 0).reduce((a, b) => a + b, 0)!=0))
 var dataTotalFilter = dataFilterDays.filter(row=> row[1]!= 'Total')
 
 return dataTotalFilter
}

How to hide current slide in the slick slider nav?

I’m using the slick slider nav, but I want to hide the current slide in the nav slider.

Currently you can see the current slide image at the top, but you can also see that same image at the start of the nav slider. I want to hide this image though, so that the slider nav will only show the next images, not the current.

Any idea if this is possible?

Codepen for reference.

<div class="container">
    <div class="row">
        <div class="col">
            <div class="main-slider">
                <img src="https://images.freeimages.com/images/large-previews/76e/abstract-1-1174741.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/a31/colorful-umbrella-1176220.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/aaf/abstract-paper-free-photo-1175904.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/4d6/chugh-1171409.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/655/glass-abstract-1501217.jpg" alt="">
            </div>
             <div class="nav-slider">
                <img src="https://images.freeimages.com/images/large-previews/76e/abstract-1-1174741.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/a31/colorful-umbrella-1176220.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/aaf/abstract-paper-free-photo-1175904.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/4d6/chugh-1171409.jpg" alt="">
                <img src="https://images.freeimages.com/images/large-previews/655/glass-abstract-1501217.jpg" alt="">
            </div>
        </div>
    </div>
</div>
  // Gallery - Synced sliders
  $(".main-slider").slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: true,
    asNavFor: ".nav-slider",
  });
  // Gallery - Nav slider
  $(".nav-slider").slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    asNavFor: ".main-slider",
    dots: false,
    arrows: true,
    focusOnSelect: true,
  });

Server not returning data in JSON

I am trying to make a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON, and I am not sure why. I need help on 2 things:

  1. Why is my server not returning data in JSON?
  2. In case it starts returning the above JSON is my API call good to work?

Error msg:

react-dom.development.js:14757 Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType (react-dom.development.js:14757:1)
Code used on backend:

const http = require("http");
let user={"name":"Leo"};
var server = http.createServer(function(req ,res){
    res.writeHead(200, {'Content-Type': JSON});
   
    res.json([{
        number: 1,
        name: 'CR7',
        gender: 'male'
      },
      {
        number: 2,
        name: 'LEO',
        gender: 'male'
      }
    ]);
    res.end(" done");
});
server.listen(8000);

Code on the frontend(React):

import "./index.css";
function App() {
  return (
    <div className="App">
      <header className="App-header">
      <form>
  <div>
  <div className="form-group">
    <label htmlFor="exampleInputEmail1">Email address</label>
    <input type="email" className="form-control" />
    <small className="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div className="form-group">
    <label>Password</label>
    <input type="password" className="form-control"/>
  </div>
  <div className="form-group form-check">
    <input type="checkbox" className="form-check-input" />
    <label className="form-check-label" >Check me out</label>
  </div>
  <button type="submit" onClick="{fetcher()}"  className="btn btn-primary">Submit</button>
</div>
      </form>
      {//using state
      }
      function fetcher(){
        fetch("https://localhost:8000/user.name",{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
    
        })
        .then((data)=>{return data.json()})

How to pass main website’s secured session cookie to web worker and use it there to call APIs

We use a secure session cookie and the back-end set the cookie through the login API. Http requests are cross-origin. I want to use web-workers to do some calculations and call certain APIs. cookies will be lost in web worker API calls despite using credentials: 'include'. What can I do if I don’t want to pass back API calls to the main thread?

How to filtering out the multiple nested object in Javascript object

** Javascript**

I have a nested array of objects, I’m trying to filter the given array of objects using a property from the third level of its array property value. For example, from the below array I like to filter the entire array using the property “ListId”: 10

Example:
let z ={"group1": [
  {
    "name": "header",
    "value": [
      {
        "id": 0,
        "list": [
          {
            "ListId": 10,
            "Name": "string1"
          },
          {
            "ListId": 11,
            "Name": "string2"
          }
        ]
      }
    ]
  }
]}




//Filtervalue : ListId = 10 
   
   output needed : let z ={"group1": [
       {
         "name": "header",
         "value": [
           {
             "id": 0,
             "list": [
               {
                 "ListId": 10,
                 "Name": "string1"
               }
             ]
           }
         ]
       } ] }

How can I use the filter method using javascript to get this expected result?

Find if the sentence has 3 consecutive words

You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string “start 5 one two three 7 end” contains three words in succession.

Input : String
Output : Boolean

This is what I’m trying to do, please point out my mistake. Thanks.

function threeWords(text){
    let lst = text.split(' ');
    for (let i=0; i< 3; i++) { 
        if (typeof lst[i] === 'string' &&  Number(lst[i]) === NaN) {return true}
        else {return false;}}
}