javascript will run only in mobile view

I want to make this as mobile javascript, i run this code but in macbook safari laptop view it’s running also

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
    function scrollFinished() {
        vid = document.getElementsByClassName('my-video-scroll')
    
        //play video
        if (runningVideo < vid.length && runningVideo >= 0) {
            vidTop = vid[runningVideo].offsetTop
            window.scrollTo(0, vidTop - 0 - scrHeight * 0);
    
            vid[runningVideo].currentTime = 0;
            vid[runningVideo].play()
        }
    
        //show the currently playing video and the total video to the console
        console.clear()
        console.log('running: ' + (runningVideo + 1))
        console.log('total: ' + vid.length)
    
        setTimeout(function () {
            scrooling = false
        }, 500)
    }
}

I tried deleting the webOS/iphone/ipad/ipod its running as well

How to track changes to input value when changing it programmatically?

I have an input that I want to track for its changes, on keypress on the cut, on paste…etc it doesn’t matter. I want to track any change. if a change happened to the input, I want a console.log() message to say “input changed” with the new value of the input.

I can see the changes when a user uses the front-end to modify the input, but when I do that programmatically using a button for example it doesn’t track.

What could be the problem?

const input = document.getElementById("input");
const button = document.getElementById("btn");

input.addEventListener("change", (e) => {
  console.log("input changed, input value: ", e.target.value);
});

button.addEventListener("click", (e) => (input.value = "this one is not trackable, why?"));
<input id="input" type="text">
<button id="btn">change input value</button>

I was wondering what is the difference between these two ways of using the Node ChildProcess API

Frist

    import {exec} from 'child_process'
    let childProcess = exec(`node test.js`,(error, stdout, stderr) => {
        if (error) {
          console.error(`exec error: ${error}`)
          return
        }
        console.log(stdout)
    })
    childProcess.kill()

second

 import {exec} from 'child_process'
 let childProcess = exec(`node test.js`,(error, stdout, stderr) => {
        if (error) {
          console.error(`exec error: ${error}`)
          return
        }
        console.log(stdout)
    })
 process.kill(childProcess.pid,'SIGTERM')

Please tell me the difference between these two kill methods,thank you.

Make an array of strings of the names using .Map in Javascript [duplicate]

I was doing some exercises using the .map method in Javascript. Ultil I got stuck in one exercise, I almost finished it.

I found a similar topic but I still have some questions.

So the title of the exercise is this “Make an array of strings of the names”.
Make an array of strings of the names

I am trying to achieve this result -> [Angelina, Eric, Paris, Kayne, Bob, Robert, Kendra]
I also questioned myself if I had to use functions, because i’ve see some people using functions in the other article I listed above.

Thank you in advance.

    const arrPessoas = [ {
        name: "Angelina",
        sobreNome: "JolieJolie",
        age: 80,
        profissao: "Jogador de futebol"
    
    },
    {
    name: "Eric",
    sobreNome: "Jones",
    age: 2,
    profissao: "Empresario"
    
    },
    {
    name: "Paris",
    sobreNome: "Hilton",
    age: 5,
    profissao: "Digital Marketer"

},
{
    name: "Kayne",
    sobreNome: "West",
    age: 16,
    profissao: "Programador"

},
{
    name: "Bob",
    sobreNome: "Ziroll",
    profissao: "Desenvolvedor Web",
    age: 100
    },
    {
    name: "Robert",
    sobreNome: "Marchal",
    age: 100,
    profissao: "Software Engineer"
    },
    {
    name: "Kendra",
    sobreNome: "Odwell",
    age: 100,
    profissao: "Product Manager"

    }
    ];


    
<pre>let arrOfNames = arrPessoas.map(function({name}){
    return console.log(name);
}

)</pre>

How to save in localStorage that refreshing browser do not change the value (JavaScript)?

I have a counter of clicks. Every click increase value. I’d like to save to in local storage, that refreshing page keeps the value. Now it saves the value in local storage, but not keep it if I refresh the browser. What should I change in my code to make it work properly?

let countedClicks = 0;
    
const countingClicks = () => {
  countedClicks += 1;
  localStorage.setItem("btnClicksSaved", countedClicks);
  let savedClicks = localStorage.getItem("btnClicksSaved");
  clicks.innerHTML = `${savedClicks} times`;
  console.log(countedClicks + "counted");
  console.log(savedClicks + "local storage");

  if (savedClicks > 5) {
    resetBtn.style.display = "flex";
  } else {
    resetBtn.style.display = "none";
  }
};

how to write html code for automatic update of numbers

I m writing an html code where I have to add image and upon the image have to add number of projects recently added how to write html code for automatic update of new project on the image for ex if there are 10 projects previously and after adding a new project the number on the image should automatically increase to 11?

ERROR : CAN NOT READ PROPERTIES OF UNDEFINED ‘TITLE’

HERE IS THE CODE WHERE I AM PASSING PROPS

import Navbar from "../../components/navbar/Navbar"
import Sidebar from "../../components/sidebar/Sidebar"
import Widget from "../../components/widget/Widget"
import "./home.scss"

const Home = () => {
  return (
    <div className="home">
        <Sidebar/>
        <div className="homecontainer"><Navbar/> 
        <div className="widgets">
          <Widget type="user"/>
          <Widget type="order"/>
          <Widget type="earning"/>
          <Widget type="balance"/>
        </div>
        </div>
    </div>
  )
}

export default Home

HERE IS THE CODE WHERE I AM GETTING THE PROPS

import './widget.scss'
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import PersonOutlineIcon from '@mui/icons-material/PersonOutline';

const Widget = ({type}) => {

    let data;

    // temporary
    const amount = 100;
    const diff = 20;


    switch (type) {
        case "user":
            data={
                title:"USERS",
                isMoney:false,
                link:"See all Users",
                icon: <PersonOutlineIcon className='icon'/>,
            }
            break;
        case "order":
            data={
                title:"ORDERS",
                isMoney:false,
                link:"View all Orders",
                icon: <PersonOutlineIcon className='icon'/>  ,  
            }
            break;
        case "earnings":
            data={
                title:"ERANINGS",
                isMoney:true,
                link:"View net earnings",
                icon: <PersonOutlineIcon className='icon'/>   , 
            }
            break;
        case "balance":
            data={
                title:"BALANCE",
                isMoney:true,
                link:"See details",
                icon: <PersonOutlineIcon className='icon'/> ,   
            }
            break;
    
        default:
            break;
    }


  return (
    <div className='widget'>
        <div className="left">
            <span className="title">{data.title}</span>
            <span className="counter">{data.isMoney && "₹" }{amount}</span>
            <span className="link">{data.link}</span>
        </div>
        <div className="right">
            <div className="percentage positive">
                <KeyboardArrowUpIcon/> {diff}%
                </div>
            {data.icon}
        </div>
    </div>
  )
}

export default Widget

BUT IT IS SHOWING ERROR
Widget.jsx:56 Uncaught TypeError: Cannot read properties of undefined (reading ‘title’)
I think that every thing is fine there but i don’t know thy it is showing this error please do check it once

Tracking changes to the value of an input by the console

I have the input tag and don’t want that user insert value to input by console. so i tried to track that inserting value. but it does’t work. here’s code.

const input = document.getElementById("input")
const button = document.getElementById("button")

const eventList = ["input", "cut", "copy", "change", "input"]
eventList.forEach((event) => {
  input.addEventListener(event, () => {
    console.log(event)
  })
})

button.addEventListener("click", () => input.value = "hi")
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="input" />
    <button id="button">insert</button>
    <script src="home.js"></script>
  </body>
</html>

Adding new object into array using function push() with different input id in javascript

I’m creating a table as below using knockout js to add gifts. Normally, an object created by push() will have the same input id as the first one & in this situation it’s “nameOfGift”. And I want to create different input id each time I add a new gift.

What are you trying to achieve
what are you expecting to get out
What did you get out (include error messages)
What else have you tried?
What do you think is causing it?
Why do you need to make a new question for it? Why is your problem different to other, similar questions on here?

Editable Grid

    <form>
        <p>You have asked for <span data-bind='text: gifts().length'>&nbsp;</span> gift(s)
            . You have <span data-bind="text: 10 - gifts().length"></span> left!</p>
        <table data-bind='visible: gifts().length > 0'>
            <thead>
                <tr>
                    <th>Gift name</th>
                    <th>Price</th>
                    <th>Description</th>
                    <th />
                </tr>
            </thead>
            <tbody data-bind='foreach: gifts'>
                <tr>
                    <td><input id="nameOfGift" class='required' data-bind='value: name, uniqueName: true'
                            placeholder="Gift's name" /></td>
                    <td><input class='required number' data-bind='value: price, uniqueName: true'
                            placeholder="Gift's price" /></td>
                    <td><input class="required description" data-bind="value: description"
                            placeholder="Gift's description" /></td>
                    <td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>
                </tr>
            </tbody>
        </table>

        <button id="my-button" data-bind='click: addGift, enable: gifts().length < 10'>Add Gift</button>
        <button data-bind='click: save, enable: gifts().length > 3'>Submit to Json</button>
        <button data-bind="click: sortItems, enable: gifts().length > 1">Sort By Name</button>
    </form>
    <textarea data-bind='value: lastSavedJson' rows='6' cols='60' disabled='disabled'> </textarea>

</div>

<script>
    var GiftModel = function (gifts) {
        var self = this;
        self.gifts = ko.observableArray(gifts);

        self.addGift = function () {
            self.gifts.push({
                name: "",
                price: "",
                description: ""
            });
        };

        self.removeGift = function (gift) {
            self.gifts.remove(gift);
        };

        self.save = function () {
            self.lastSavedJson(JSON.stringify(ko.toJS(self.gifts), null, 2));

        };

        self.lastSavedJson = ko.observable("");

        self.sortItems = function () {
            self.gifts.sort(function (a, b) {
                return a.name < b.name ? -1 : 1;
            });
        };

    };

    var viewModel = new GiftModel([
        { name: "Soccer Ball", price: "15$", description: "fun to play" },
        { name: "Pine Tree", price: "220.00$", description: "for christmas eve" }
    ]);


    ko.applyBindings(viewModel);

    $("form").validate({ submitHandler: viewModel.save });




</script>

<script type="text/javascript">
    $(function () {
        $('#my-button').click(function () {
            var colorR = Math.floor((Math.random() * 256));
            var colorG = Math.floor((Math.random() * 256));
            var colorB = Math.floor((Math.random() * 256));
            $('body').css("background-image", "linear-gradient(to right, rgba(" + (colorR - Math.floor(Math.random() * 1200)) +
                "," + (colorG + Math.floor(Math.random() * 1600)) + "," + colorB + "), rgba(" + colorR + "," + colorG + "," + colorB + "))");
            var d = new Date();
            var i = d.getTime();
            //$('input').attr("id", i);

        });


    });
</script>

How to activate an event with on() method when the value of a div tag is changed?

I am currently writing HTML and JS code in the following form, but when I put a new value in the div tag value, the event does not happen.

the Javascript code is

$('#CdText').on('input', function () {
    $('#CdText').innerHTML = concat($('#CdText').innerHTML, 'test');
});

HTML is

<div id="CdText" class="ui-state-highlight" contenteditable="true">1234</div>

The above code does not work.
However it works

$('#appInput').on('input', function () {
   $('#appInput').val(concat($('#appInput').val(), 'test'));
});

because HTML is

<input id="appInput" class="form-control ap-input">
  <div>1234</div>
</input>

By the way, changing $(‘#CdText’).on(‘input’, function () { as follows did not work.
$(‘#CdText’).on(‘div’, function () {
$(‘#CdText’).on(‘change’, function () {
$(‘#CdText’).on(‘change’, ‘div’, function () {

I hope I’m doing something wrong with Jquery’s use of the on() method, but as of yet I haven’t found what’s wrong.

If you know how to write an event to be triggered every time something is entered into a div like the above, please let me know.

By the way, $(‘#CdText’).on(‘input’, function () { is properly contained in $(function () {}).
css of CdText div tag is inline-block. so it can write as input.

Thank you for reading.

Restrict datepicker to select dates on fromDate and toDate

I have 2 text fields [fromDate, toDate] for date in html.
Conditions for datepicker :

  1. If fromDate is current date, then toDate should be automatically selected as current date as well.
  2. If fromDate is before current date, then difference between fromDate and toDate should be max 5 days based on the following scenarios:
    For example,
    a) If fromDate is 11-07-2022, then toDate should be 11-07-2022 & 12-07-2022.
    b) If fromDate is 10-07-2022, then toDate should be 10-07-2022, 11-07-2022 & 12-07-2022.
    c) If fromDate is 09-07-2022, then toDate should be 09-07-2022, 10-07-2022, 11-07-2022 & 12-07-2022.
    d) If fromDate is 09-07-2022, then toDate should be 09-07-2022, 10-07-2022, 11-07-2022 & 12-07-2022.
    e) If fromDate is 08-07-2022, then toDate should be 08-07-2022, 09-07-2022, 10-07-2022, 11-07-2022 & 12-07-2022.

Array only showing last result of the loop – JAVASCRIPT

i want to get the full list of my google contacts on a JSON file, but im only getting the last value on my contacts.

What should i change? or what is the problem here?

function contactsJSON() {

  var contactsjson = {}
  var myContacts = ContactsApp.getContactGroup('System Group: My Contacts').getContacts();
  for (var i = 0; i < myContacts.length; i++) {

    var id = myContacts[i].getId();
    var name = myContacts[i].getFullName();

    var emailsobj = myContacts[i].getEmails();
    var email = {}
    for (var j = 0; j < emailsobj.length; j++) {
      email[emailsobj[j].getAddress().toLowerCase()] = 1;
    };

    var phonesobj = myContacts[i].getPhones();
    var phone = {}
    for (var j = 0; j < phonesobj.length; j++) {
      phone[phonesobj[j].getPhoneNumber().replace(/[_)(s.-]/g, '')] = 1;

    };

    for (var j = 0; j < id.length; j++) {
      contactsjson = { id: id, name: name, phone: phone, email: email };
    }
  }

  contactsjson = JSON.stringify(contactsjson);
  contactsjson = JSON.parse(contactsjson);
  Logger.log(contactsjson);
  return contactsjson;
}

Hope you can help me,

Federico.

BuildFire LocalStorage Not Saving Between Admin and Widget

I am having issue in BuildFire that works on my local computer but fails in production when the plugin is uploaded.

In my plug-in, I am having the user enter and save values to the buildfire local storage as such in my Content.js:

function saveCredentionals (){

    buildfire.localStorage.setItem("bw_organizer_id", organizer_id, (error) => {
      if (error) return console.error("something went wrong!", error);
      console.log("All is well, data saved and other plugins can now access it");
    });

    buildfire.localStorage.setItem("bw_access_token", access_token, (error) => {
      if (error) return console.error("something went wrong!", error);
      console.log("All is well, data saved and other plugins can now access it");
    });

  }

The files save correctly and values can be retrieved in the Content.js, even with page reloads. Now I am trying to retrieve the values in Widget.js as such:

Promise.all([
        buildfire.localStorage.getItem("bw_organizer_id"),
        buildfire.localStorage.getItem("bw_access_token"),
      ]).then(items => {

        let has_organizer_token = false;

        let has_access_token = false;

        if (items[0]) {
          has_organizer_token = true;
        }

        if (items[1]) {
          has_access_token = true;
        }

        if (has_access_token && has_access_token) {
          displayVideoPage(items[0], items[1]);
        } else {
          setMainContent(<div>Organizer ID and access token required.</div>);
        }


      });

This works on my local computer but fails to retrieve the value when I publish my plugin and run it on the app.buildfire.com . The items are both null on production, but returns the values in the Content.js.

Any thoughts on why this is happenings? The code is also open sourced here: https://github.com/BingeWave-Libraries/buildfire-livestream

grapejs add internal script as well as external script to canvas

As of now I have

const editor = grapesjs.init({
            // Indicate where to init the editor. You can also pass an HTMLElement
            container: '#gjs',
            canvas: {
                scripts: ['https://somelink.js', 'https://anotherlink.js]
            },
});

I would like to have this link as well as some scripts which are internally added, say

function alertMe() { alert('Ninja') }

I am unable to add the above function block into the canvas scripts. Anybody have an idea?

Note: It is not possible to create separate file for these script because these are extracted during run time

Promise.then then not run [duplicate]

Hi I know there are a lot of similar answers on the site, but I still cannot debug why my then is not running in my case. Can you please take a look, it is a very simple code.

let getDuration = new Promise(() => {
            durationRetrieveHandler("text_duration", sumDuration);
        })
getDuration.then(() => {
            console.log('then is running!!!')
            }
        }).catch((e)=>{
            console.log("error occur: " + e);
})

Here in code, durationRetrieveHandler() run perfectly without a mistake, catch() is not running at all (meaning there is no error).

durationRetrieveHandler() is a function use fetch() API to GET some data from DB, sumDuration is a callback insides durationRetrieveHandler().

durationRetrieveHandler() and sumDuration() is below for your reference

function durationRetrieveHandler(sheet, callback) {
    getHandler("https://some.url")
        .then(function(data){
            console.log(data);
            return callback(data);
        })
        .catch(function(error) {
            console.log(error);
        })
}

function sumDuration(data) {
    // sum things up, no return 
}

Thank you so much for the help, I will be super super appreciate!!!