Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141307 articles
Browse latest View live

How to automate a function under a conditional statement

$
0
0

I have a code written as a function which I would like to automate in another function as long as a certain condition is not met, push the new values in a variable[] like a nested array and return the length of the variable. But the command line just freezes. This is what I have done so far.

First function to be automated which is ok:

function sh(v){
var f = [];
if (v.length == 3){
for (let i = 1; i < v.length; i += 2){
if(v[i - 1] < v[i]){
f.push(v[i - 1]);
}
}
}
else{
for (let i = 1; i < v.length; i += 2){
if(v[i - 1] < v[i]){
f.push(v[i - 1]);
}
}
}
if (v.length % 2 == 1){
var a = v[v.length -1]
f.push(a)
}
return f;
}

Now I want to automate like this:

/*(Point 1)This function should take the results of sh() which is an array and  apply sh() repeatedly as long as the given array.length  > 1 */
/*Whenever the array is shrunk by sh() function , it should push the new array into an initial empty array var receive = [] , till when the condition is satisfied the empty array will be nested with arrays receive = [[], []] , then return receive.length*/ 
function automated(x){
var receive = [];
receive.push(sh(x))
receive = receive
while(x.length > 1){
for(let g = 0; g < receive.length; g++){
/*attempting Last index of receive*/
let c = receive[g] - 1
}

receive.push(automated(receive[c]))
}
return receive.length
}

Expected results:

/*If i input an array like*/ 
z = [ 6, 5, 8, 4, 7, 10,9]
sh (z)
/*Outputs :*/
[7,9]
/*If sh is automated and retakes in [7,9] as input, 
Outputs:*/
 [7]
/*[7, 9]  and [7] should be nested into receive = [] as receive = [ [7,9] , [7]]
Then return receive.length which is 2.*/

Run JS when show section on HTML page

$
0
0

I have a javascript TypingText.js that executes "typing text", however, I need run javascript "typing text" when user scrolling to the section where that text is located. Can anyone help me, thanks.

HTML

<section id="mysection">

<div id="example1">My text here</div>

JS

new TypingText(document.getElementById("example1"));
TypingText.runAll();

Firestore get subcollection is slow

$
0
0

I have collections and their sub-collections. I loop over them and collect data. It works fine but it is too slow. Can anyone suggest to improve performance issue?

static async getSubCategories(category_id) {
    const db = Firebase.firestore(),
        subCategories = [];
        activeRef = await db.collection("sub_categories").where("category_id", "==", category_id).orderBy("id").get();
    for (let doc of activeRef.docs) {
        const subCategory = doc.data();
        if (_.isObject(subCategory)) {
            const subRef = await doc.ref.collection('sub_sub_categories').orderBy("id").get(),
                subSubCategories = [];
            for (let subDoc of subRef.docs) {
                const subSubCategory = subDoc.data();
                if (_.isObject(subCategory)) {
                    subSubCategories.push(subSubCategory);
                    // If SubCategory has image, download storage uri
                    if (subSubCategory.image_storage_uri) {
                        const imageRef = Firebase.storage().refFromURL(subSubCategory.image_storage_uri),
                            imageUri = await imageRef.getDownloadURL();
                        subSubCategory.image_uri = imageUri;
                    }
                }
            }
            if (subSubCategories.length > 0)
                subCategory.sub_sub_categories = subSubCategories;
            subCategories.push(subCategory);
        }
    }
    return subCategories;
}

enter image description here

can't get file content from server .txt file

$
0
0

I'm working in dhtml (html5, CSS3, latest JavaScript, and Perl 5.26.3) using an Apache/2.4.39 (Win64) and mod_perl/2.0.10 server on Windows 10. I don't seem to be able to get ajax to work.

I'm trying to 'get' a multi-line file (directory and file name) out of a database location. I'm thinking that the response text will return a string of lines separated by line ends (\n). I've tried the w3 simplest approach, jquery, and d3. The w3 approach is below.

    var mFn = document.forms[0]['thefdir'].value + 'Measures/all.mea?t=' + Math.random(); // Unique ID bypasses cache.

    var xhttp = new XMLHttpRequest();
    xhttp.open('GET', 'dog.txt', true);
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        fieldName3.value = this.responseText;
      }
    };    
    xhttp.send();

Its executed onChange to a field on a form generated by a Perl CGI program. The fieldName3.value would be processed downstream in the JS.

I've tried it with the fully qualified location (mFn) and a relative location (dog.txt) with 1 line in it. Neither worked. I don't know what directory the relative location resolves to. So I put a copy in the server root and the cgi-bin directories. It did not work. Nothing happens and no error information is generated.

Any help will be appreciated. craigt

How to load js file and use the function in that js file in c#

$
0
0

I have a js file (ABC.js) and want to load in c# and run the function in it.

When i am in browser Developer tool console i run the following code:

  1. i paste the whole JavaScript and enter
  2. var xx = Object.create(xobject);
  3. var Key = xx.encryptKey(abcdefgg);

How do i run the following code in c# console? To get the value 'Key'.

Javascript: Changing a div's background color to a random color on mouseover

$
0
0

I am relatively new to Javascripting and I am aware that there are answers related to this technique, however nowhere have I been able to get all the pieces.

On a webpage, I have created a 10 by 10 grid consisting of 100 identically-sized individual divs. When any div is moused-over I want it to display a random background color (mousing across divs, a trail of differently colored divs would be displayed).

Within any given div, the function "fnPickColor" (which creates a color) is activated in this way:

onmouseover ="fnPickColor()"

My problem is: having generated the color, I do not know how to put it into the individual div which called the function. I cannot use "getElementById" or the tag-based references since these refer to specific individual divs or groups of them, not to whichever div is currently being moused-over.

I attempted a construct using "this.style.backgroundColor" to transfer the color, however that failed.

I'm sure it's extremely simple - how is this done?

When using Redis with express sessions what should the resave property be set to?

$
0
0

I was looking into this parameter here:

https://github.com/expressjs/session#resave

and it says to look and see if your store implements the touch method:

Forces the session to be saved back to the session store, even if the session was never modified during the request. Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).

The default value is true, but using the default has been deprecated, as the default will change in the future. Please research into this setting and choose what is appropriate to your use-case. Typically, you'll want false.

How do I know if this is necessary for my store? The best way to know is to check with your store if it implements the touch method. If it does, then you can safely set resave: false. If it does not implement the touch method and your store sets an expiration date on stored sessions, then you likely need resave: true.

usage of useEffect blanks out page

$
0
0

Pretty much the title, when I add

   useEffect(() => {
    const fetchData = async () => {
      const result = await fetch('http://localhost.com/ping');
      console.log(result)
    };
    fetchData();
  }, []);

to my component, the page renders properly and then immediately blanks out. Not sure what I did wrong since it's literally the same in the React Documentation.

Full component:

import React from 'react';
import { useEffect } from 'react';
const Test = () => {

  useEffect(() => {
    const fetchData = async () => {
      const result = await fetch('http://localhost.com/ping');
      console.log(result)
    };
    fetchData();
  }, []);

  return (
    <>
      <h1>Test</h1>
    </>
  );
};

export default Test;

App

import { hot } from 'react-hot-loader/root';
import React from 'react';
import Navigation from './components/Navigation/Navigation.jsx';

const App = () => {
  return (
    <>
      <div>Stuff</div>
      <Navigation></Navigation>
    </>
  );
};
export default hot(App);

Navigation

/* eslint-disable react/display-name */
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import React from 'react';
import Home from './Home';
import Login from './Login';
import Logout from './Logout';
import Faq from './Faq';
import Dashboard from './Dashboard';
import Test from './Test';

const Navigation = () => {
  const isLoggedIn = false;
  return (
    <>
      <Router>
        <div>
          <ul>
            <li>
              <Link to='/'>Home</Link>
            </li>
            <li>
              {isLoggedIn ? (
                <Link to='/auth/logout'>Logout</Link>
              ) : (
                <Link to='/auth/login'>Login</Link>
              )}
            </li>
            <li>
              <Link to='/auth/dashboard'>Dashboard</Link>
            </li>
            <li>
              <Link to='/faq'>FAQ</Link>
            </li>
            <li>
              <Link to='/test'>Test</Link>
            </li>
          </ul>
        </div>
        <Switch>
          <Route exact path='/'>
            <Home />
          </Route>
          <Route exact path='/auth/login'>
            <Login />
          </Route>
          <Route path='/auth/logout'>
            <Logout />
          </Route>
          <Route path='/auth/dashboard'>
            <Dashboard />
          </Route>
          <Route path='/faq'>
            <Faq />
          </Route>
          <Route path='/test'>
            <Test />
          </Route>
        </Switch>
      </Router>
    </>
  );
};

export default Navigation;

I have to write some stuff here because stack overflow decided that i am not allowed to post the code that people asked for ...


Problem Importing to excel with js-excel-generator

$
0
0

I have a big problem when exporting to excel with this javascript library. Well the library works well for me wonderfully it does its job however, when exporting more than 800 records in a table well, the library gives an error, destroys the table structure and only exports one column, and leaves the rest in white. I need help with this problem.

The library files can be found on their official github.

https://github.com/ecscstatsconsulting/js-excel-generator

How to stop showing camera in chrome extenson

$
0
0

I have chrome extension which opens camera on content page when clck extension icon. my code works well, but when i click extension second time, i want to turn off camera. please help me.

my code

function setupCam() {
    navigator.mediaDevices.getUserMedia({
        video: true
    }).then(mediaStream => {
        document.querySelector('#videoElement').srcObject = mediaStream;
    }).catch((error) => {
        console.warn(error);
    });
}

setupCam();
document.body.innerHTML += html;

Hide div refresh while using SetInterval

$
0
0

I use SetInterval to update a table every 5 seconds which works great except that it creates a "blinking" effect since the Div refreshes as if I pressed F5.

Is it possible to hide it with example fadeIn() function? I have tried but without any luck so far. Anyone have any experience with this?

<script>
    var append_increment = 0;
    setInterval(function() {
        $("#_change tr").remove();
        $.ajax({
            type: "GET",
            url: "{% url 'tables' %}",
            data: {' tables ': append_increment}
        })
        .done(function(response) {
            $('#_change').append(response).fadeIn("milliseconds", "linear");

            append_increment += 0;
        });
    }, 5000)
</script>

How can i fix intelliSense on visual studio code?

$
0
0

How do i get IntelliSense and Autocomplete to function on Visual studio code

i tried doing it but the got automaticallyoverrodedefaultvalue

I don't know what that means

Promise within while loop won't run - causing infinite loop

$
0
0

I am trying to run a Promise within a while loop. The code after the promise (in the .then) will eventually break the while loop.

However, the promise never runs. The while loop just keeps running infinitely without triggering the promise.

Why is this? Is it impossible to use a promise in a while loop?

A simplified version of code is below

while(relevantRefundRequests.length >= waitList[0].quantity){

    stripe.paymentIntents.create({

    })
    .then(data => {

    ***code that will break while loop

    })

}

Modifying javascript to change web page font color to black

$
0
0

I have retinal damage in my left eye that makes reading text in serif fonts difficult.
Someone once posted this javascript snippet that I save in my Chrome bookmark's bar, that changes a web page's fonts to Tahoma when I click it. It's wonderful.

I've noticed in recent years there is a trend for designing web pages with text displaying in shades of gray, rather than solid black. Gray is harder to read for me than black, and it renders poorly when printed.

I'm not a coding expert. Is there a simple addition that can be made to this code that will also change font color to solid black?

Here's the code snippet:

    javascript:Array.prototype.forEach.call(document.getElementsByTagName("*"), function(e){e.style.fontFamily ="Tahoma"})

If statement not catching variable?

$
0
0

So I am getting the length of some data images that update every second or so the first data image is completely black and blank so it always has the same size when my canvas renders the scene the data image size changes this is what I am trying to catch, anyways my below If statement doesn't seem to catch the change in the var what am I doing wrong? Everything works fine apart from the if statement.

function render() {
 renderergl.render( scene, camera );
 testa();
}


// First Image Store Nunber
var previousImgFileSize;
var data_urlii = renderergl.domElement.toDataURL();
var imgFileSizeii = Math.round((data_urlii.length)) ;
previousImgFileSize=imgFileSizeii;
console.log(previousImgFileSize);

//Second Image
var data_url;
var imgFileSize;

function testa() {
// Add length and keep updating    
data_url = renderergl.domElement.toDataURL();
imgFileSize = Math.round((data_url.length)) ;
var logit = console.log(imgFileSize);
}


setInterval(function(){ 
var imgFileSizeCh = imgFileSize;
var previmg = previousImgFileSize;

//If second image is bigger than the first do the below
if (imgFileSizeCh =! previmg){

   $('body').css('display','none');
   console.clear();

   } }, 1000);

Thanks in advance!


Cannot initialize Node.js on ec2

$
0
0

This is my first experience with Node.js.

Using an ubuntu ec2 instance on which I have installed Node, I am following this tutorial: https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/

My index.js file looks like this:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 22

app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.get('/', (request, response) => {
  response.json({ info: 'Node.js, Express, and Postgres API' })
})

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

When I get to the part where I run node index.js, I get this error:

ubuntu@ip-172-31-87-85:~/riapi$ node index.js 
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES 0.0.0.0:22
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at Server.setupListenHandle [as _listen2] (net.js:1350:19)
    at listenInCluster (net.js:1408:12)
    at Server.listen (net.js:1492:7)
    at Function.listen (/home/ubuntu/riapi/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ubuntu/riapi/index.js:17:5)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)

I found this SO issue: ExpressJS - throw er Unhandled error event

And when I tried a couple things from it, but without success:

ubuntu@ip-172-31-87-85:~/riapi$ netstat -tulnp | grep 22
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   
ubuntu@ip-172-31-87-85:~/riapi$ ps aux | awk '/node/{print $2}' | xargs kill -9
kill: (20586): No such process

Does anyone see what I'm doing wrong?

Dropdown within dropdown javascript

$
0
0

On http://severinereard.be/test/ I'm trying to make a dropdown from the 'main' section class named 'Kinésithérapie' which holds all the 'sub1' sections and another one from 'Esthétique' which holds all 'sub2' sections. It should be triggered when you push the 'open' p class on the right. this shoud change in '-' when opened.

I tried doing this with the javascript code I have but I can't make it work. Can anybody help me out?

coffeescript - Why does this always output as '1'?

$
0
0

How come this always outputs as "1" even if randomArea isn't North?

if randomArea = "North"
    id.innerHTML = "1"
else if randomArea = "South"
    id.innerHTML = "2"
else if randomArea = "East"
    id.innerHTML = "3"
else if randomArea = "West"
    id.innerHTML = "4"
else if randomArea = "Central"
    id.innerHTML = "5"
else if randomArea = ""
    id.innerHTML = "6"

Get clicked mark data using react-vega and vega-lite

$
0
0

I have a vega-lite chart and would like to add an event listener to get the data in React, but can't seem to figure this out. Specifically I'm trying to display a table below the vega chart that depends on some attributes of the mark that has been clicked.

Here's the beginning of the spec:

const spec = {
    width: 'container',
    height: 500,
    signals: [
        {
            name: 'click',
            value: 0,
            on: [{events: '*:mousedown', update: 'datum'}]
        }
    ],
    layer: [
        {
            mark: {type: 'point', filled: true, tooltip: {content: 'data'}},
....

And here is my latest attempt at getting the clicked point (based on https://github.com/vega/react-vega/tree/master/packages/react-vega#approach1-create-class-from-spec-then-get-a-react-class-to-use):

const handleClick = (...args) => {
    console.log(args);
}
const signalListeners = { click: handleClick };
const vegaChart = <VegaLite spec={spec} data={data} signalListeners={signalListeners}/>;

However I'm getting Cannot add invalid signal listener. Error: Unrecognized signal name: "click" even though I have the click signal defined. Any help would be appreciated; I can't seem to find anything like this online.

JavaScript + SVG: Raphaël drawing a happy face how to draw the eyes inside the big circle?

$
0
0

all I'm just wondering how to draw a smiley face without SVG or canvas method like I can draw a circle using Raphael library, but I don't know how to draw the eyes inside the outer circle and later for the mouth is a Bézier curve I assume you will need to use Q to specify the path? Here is the code so far Thank you

    setup = function() {
      paper = Raphael('container', 500, 500)
      circ = paper.circle(25, 25, 24)
      circ.attr({

        'stroke': '#000',
        'stroke-width': '2'
      })
    }
    jQuery(document).ready(setup) 
Viewing all 141307 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>