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

In JavaScript, is using `a == null` the same as `a === null || a === undefined`?

$
0
0

It took me a while to note to always use === in JavaScript instead of ==.

But today I noticed

if (a == null) { ... }

seems identical as

if (a === null || a === undefined) { ... }

from a table in the MDN docs.

I hope to know:

  1. are they really identical?
  2. is it recommended to use the form a == null instead of a === null || a === undefined?

JS 'Firebase is not defined' error when trying to initialize

$
0
0

I am working with Glitch.com for my first ever IoT project (also no experience with front/back end). I set up this moisture plant sensor and added some code in Arduino. The moisture uploads from Arduino to a Firebase real-time database.

Now when trying to add this data from Firebase onto my webpage, I keep running into the same error. After multiple failed attempts myself, I decided to just remix an existing project for a Firebase connection. After filling in all my own Firebase info (auth, url ...) I still encountered the same issue, 'Firebase is not defined'. This error happens on these 3 rules;

firebase.initializeApp(config);
var rootRef = firebase.database().ref();
var myDBConn = firebase.database().ref("Moisture");

The full code (for some context):

<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>

    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
  var config = {
        apiKey: "your apiKey from firebase website",
        authDomain: "projectId.firebaseapp.com",
        databaseURL: "https://databaseName.firebaseio.com",
        storageBucket: "bucket.appspot.com",
      };
        firebase.initializeApp(config);

        var rootRef = firebase.database().ref();


  // List to hold my moisture value
  var myMoisture = [];

  // Define database connection to correct branch, Moisture
  var myDBConn = firebase.database().ref("Moisture");

  // Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
  myDBConn.on("child_added", function(data, prevChildKey){

    // The data returned from the branch is put into a variable, dataPoint
    var dataPoint = data.val();

    // Convert the 'Temp' field from dataPoint into integers, then put them into the myTemps list
    myMoisture.push(parseInt(dataPoint.Temp));

    // Add all the Temps and get the total
    var totalT = 0;
    var i=0;
    for (i=0; i<myMoisture.length; i++){
      totalT += myMoisture[i];
    }

    // Create an average by dividing the sum of temps by the number of temps
    var average = totalT / myMoisture.length;

    // Update the page elements with the average and the last item (most recent) off the list 
    document.getElementById("averageT").innerHTML=average;
    document.getElementById("LiveT").innerHTML=myMoisture[myMoisture.length - 1];
  });

Another thing I was wondering is, what does datapoint.Temp mean? The original code was made for a webpage displaying live temperature and average temperature, however I want the moisture value. I still have to edit the code a bit, but want to make sure the Firebase connection works before I start on that.

@ok listener is not triggered on b-modal with jest-test-utils (vue-bootstrap)

$
0
0

I am using the vue-bootstrap b-modal with the @ok="save" hook

The mycomponent.vue looks like this:

<template>
  <div>
    <b-button @click="add">open modal</b-button>
    <b-modal static lazy id="modal-detail" @ok="save">
      <b-form-input v-model="fooName"></b-form-input>
    </b-modal>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import { RestClient } from "./RestClient";

@Component({ name: "fooController" })
export default class FooController extends Vue {
  public fooName = "";
  public add(): void {
    this.$root.$emit("bv::show::modal", "modal-detail");
  }
  public save(): void {
    console.log("in save method");
    RestClient.create(this.fooName);
  }
}
</script>

The RestClient.ts looks like this:

export class RestClient {
  static create(payload: string) {
    return payload;
  }
}

The test looks like this:

import { createLocalVue, mount } from "@vue/test-utils";
import BootstrapVue from "bootstrap-vue";
import MyComponent from "./mycomponent.vue";
import { RestClient } from "./RestClient";

jest.mock("./RestClient.ts", () => ({
  RestClient: {
    create: jest.fn(() => {
      return {};
      //   return Promise.resolve({});
    })
  }
}));

describe("component test", () => {
  const localVue = createLocalVue();
  localVue.use(BootstrapVue);

  it("should call the create method on the REST client when ok-ing the modal", (done) => {
    const wrapper = mount(MyComponent, {
      attachToDocument: true,
      localVue
    });
    expect(wrapper.isVueInstance()).toBe(true);

    // there is just one button: the open modal button
    wrapper.find("button").trigger("click");
    const modal = wrapper.find("#modal-detail");

    modal.vm.$emit("ok");

    return wrapper.vm.$nextTick().then(() => {
      expect(RestClient.create).toBeCalled();
      return wrapper.vm.$nextTick().then(done);
    });
 });
});

I am emitting the ok event on the modal directly. Then I am watching for the console.log statement in the save-method to be executed, which i cannot see in the terminal, when executing the test.

Thus, the RestClient.create-method is not being called. Why?

Service workers event listener - fetch

$
0
0

I'd created a service worker by next code:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

and get fine answer, and event 'install' emit in sw.js ok, but event 'fetch' never emit.

I use http-server (node js) with 80 (http) port, i've seen my request in DevTools Chrome and in console from http-server, but my service worker hadn't emitted any.

My service worker code:

self.addEventListener('install', () => {
    console.log("event - install"); // OK
});

self.addEventListener("fetch", (e) => {
    console.log("A"); // BAD
    return e.request;
});

I use this code in the end of body

setTimeout(() => {
  alert("S");
  fetch("/svg.svg", {
    method: "GET"
  });
}, 10000);

Log a user out of a website when they put their computer to sleep

$
0
0

This is a bizarre one. We have a Laravel website, and on said site we have a timer per user, where they get 15 minutes of being inactive before being booted.

We do this through a timer that sits on the page in a react component, it works as we want it to, but now we have a new issue: If a user is logged in and shut the lid of their laptop the website should boot them. Banks do this, Schools and Universities do this, Government sites also do this. So it is possible, just not sure how.

We do use web sockets, using laravel-websockets library and Echo. What I would like to see happen is:

  • Once you close your laptop boot you to the login screen. So the next time you open the laptop and login, and see the browser you are on the login screen. It doesn't have to happen that quickly, but we need a way to send something to the front end basically telling them to refresh the page, once the session is killed, we set the session lifetime on laravel of 15 minutes.

Some people have suggested in other similar questions:

  • to create a custom web-socket handler
  • To compare the session cookie (in the browser) with the user cookie on the back end.
  • To have a timer running on the front end (we do, it just stops when you close the laptop lid)

The most popular one seems to be using web-sockets, listening for the user to disconnect and then boot them, which is fine and all, but then how do you send a request to a browser thats suspended to then boot them?

I have found requestIdleCallback() But again, I don't think this is what I want if I already have a heartbeat timer on the site. It also doesn't work in all browsers.

I am very lost here on how to accomplish this, the example I can give is:

Log in to your bank, put your computer to sleep, wait 15-20 minutes, awaken the computer, log in and see your bank now has you on the login screen. That's what I want. But I don't know how to accomplish that.

You cant send events to a "sleeping" browser from the back end, and while yes this would have to be a back end solution, how do you update the front end then, so that they are on the logout screen when they reawaken the laptop or computer?

How do I hide the "next" button until a certain time has passed or video has finished playing?

$
0
0

I'm building an online survey on the formr platform. In the survey, the respondent is shown a video as an experimental treatment. I want to hide the "next" button until the respondent has watched the entire video, or a suitable time has passed to ensure that the respondent can't skip the treatment.

I've been adviced to use JavaScript to solve this problem, but I am very much a novice, and after a few hours of googling and some unsuccessful attempts, I turn to you.

Please let me know if I have left out necessary information.

Best

I get a blank screen while using HTML5 video player with JS when CSS is attached

$
0
0

I would like to show some video clips randomly on the screen, once at a time. The site is working perfectly when I don't link any style sheets, including fonts but as soon as I link something video player goes blank even though source video is there.

Here's my code: https://codepen.io/ondersumer07/pen/poJVdVp

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vinematik</title>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700|Roboto:400,700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/style.css">
</head>

<body>
  <div class="grid-container">
    <h1 class="grid-header">Vinematik</h1>

    <div class="vid">



      <video class="grid-video" height="720" width="1280" controls>
        <source id="vsrc" />
        Please update your browser.
      </video>


    </div>

    <p class="grid-p"><i>Aykut Elmas</i> vine testi</p>
  </div>


  <script>
    document.getElementById("vsrc").src = Math.floor((Math.random() * 3) + 1) + ".mp4";
  </script>


</body>

</html>

Note:I take the videos from a folder, locally. They are named 1.mp4, 2.mp4, etc.

Using object destructuring instead of default parameters for my api calls

$
0
0

I'm trying to use object destructuring instead of default parameters for my api calls in my vue component. Can someone tell me why this would not work? They are both methods in my component, the caps lock variables are set outside the component and the this ones are pulled from data.

buildUrl() {
  const options = {
    parm1: PARM_1,
    parm2: PARM_2,
    parm3: this.parm3,
    parm4: this.parm4
  };
  const { parm1, parm2, parm3, parm4 } = options;
  return `things?parm1=${parm1}&parm2=${parm2}&parm3=${parm3}&parm4=${parm4}`;
}

async foo() {
  const { parm1, items: things } = await this.$axios.$get(
    this.buildUrl({ parm1: this.parm1 + 1 })
  );
  this.parm1 = parm1;
  this.things.push(...things);
},

Vue.js - prop binded to component not showing the right result

$
0
0

I have this SwitchButton component in my Vue.js app that has a custom event 'toggle'. When clicking (switching) the button, the toggle event sets isEnabled to false or true. No problems with that but when I bind isEnabled in the parent component to the SwitchButton child component to set its initial value, it doesn't seem to work.

Code used in parent component (giving isEnabled true as initial value)

<SwitchButton v-model="distSwitch" :isEnabled="true">
    <label slot="left">{{ $t('general.dealer') }}</label>
    <label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>

SwitchButton component:

<template>
    <div class="switch-button-control">
        <div class="switch-button-label">
            <slot name="left"></slot>
        </div>
        <div class="switch-button" :class="{'enabled': isEnabled}" @click="toggle">
            <div class="button"></div>
        </div>
        <div class="switch-button-label">
            <slot name="right"></slot>
        </div>
    </div>
</template>

<script>
export default {
    name: 'SwitchButton',
    model: {
        prop: 'isEnabled',
        event: 'toggle'
    },
    props: {
        isEnabled: {
            type: Boolean,
            required: true
        }
    },
    methods: {
        toggle() {
            this.$emit("toggle", !this.isEnabled);
        }
    },
    created() {
        /*eslint-disable no-console*/
        console.log('isEnabled', this.isEnabled)
    }
}
</script>

I expect the console.log in the created hook to output "isEnabled > true" but it outputs "false" instead

What am I missing here?

Getting CSRF token mismatch Laravel

$
0
0

I'm trying to submit a form with javascript but I keep getting this error CSRF token mismatch. I tried to change var url = "{{ route('review.store') }}"; to {{ route('review.store') }}?_token={{ csrf_token() }} and it was submitting the form to the database without data. I have seen a lot of question similar to this but I didn't get a solution for my case.How can I fix this?

<form id="form" enctype="multipart/form-data">
    <input type="hidden" value="{{csrf_token()}}" id="token"/>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title">
</div>

<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description">
</div>
</form>
<input type='button' value="Submit" id="btn"/>

Javascript

var token = $("#token").val();
$(document).ready(function(){

$("#btn").click(function(event){
event.preventDefault();
var url = "{{ route('review.store') }}";
var form = $('#form')[0];
var formData = new FormData(form);
formData.append('_token', token);
$.ajax({
    url: url,
    data: formData,
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    success:function(data){
    if($.isEmptyObject(data.error)){
    $("#msg").html("successfull");
    $("#msg").fadeOut(3000);
     }
    }
});
});

});

Route

  Route::resource('review','ProductReviewController');

React Reduct - Select Onchange get method request

$
0
0

I have the following situation, i provide the a codesandbox demo to demonstrate my existing problem.

A bit of explanation about and how to reproduce the case

I am here in the component League.js, any league in the list has a link

<a href={`#${item.league_id}`} onClick={(e) => onClick(e, item.league_id)}>

  const onClick = (evt, id) => {
    evt.preventDefault();
    getDetail(id)
  };

The onclick function populates in the Details.js component the select options with the names of the teams. You can see below.

  if (teamsDetail.length) {
    details = (
      <select value={selectedOption} onChange={selectTeamStat}>
        {teamsDetail && teamsDetail.length > 0
          ? teamsDetail.map(item => (
              <option key={`${item.team_id}`} value={item.team_id}>
                {item.name}
              </option>
            ))
          : null}
      </select>
    );
  }

This is now the problem i have in Detail.js component, when i select the team name in my select i want send a get request getStats where i have to set two parameters ( team_id and league_id )

Here the relevant code

const [selectedOption, setSelectedOption] = useState("");

  const selectTeamStat = evt => {
    const { value } = evt.target;
    setSelectedOption(value);
    getStats(357, value);
  };

At the moment i can only pass the team_id which is the select value selectedOption

How can i also pass the league_id parameter?

I have hardcoded now putting 357 but i need to use the parameter league_id. How can i pass it from League.js Component?

how to apply a few styles properties depends on condition styled-components

$
0
0

Is it possible to apply a few styles properties at once?

const Button = styled.div`
  color: blue;
  opacity: 0.6;
  background-color: #ccc;
`

I need to pass active property, which will be affect color, opacity, background-color. How can I apply styles for active button at once instead of declare condition for each property?

const Button = styled.div`
  color: ${props.active ? 'green' : 'blue'};
  opacity: ${props.active ? 1 : 0.6};
  background-color: : ${props.active ? 'white' : '#ccc'};

I'm trying to make objects appear and disappear in the viewer with some degree of transparency [closed]

$
0
0

I'm working on a revi model to put in the forge where you can read the history of the building. from the nascia - collapses - demolitions - reconstructions. between one passage and the next I would like to add a degree of transparency (fade in fade out) for the change of models or model parts.

function T00()
{
NOP_VIEWER.model.search('00', function onSuccess(dbids) {NOP_VIEWER.showAll(); NOP_VIEWER.isolate(dbids); }, function onError(err) { console.error(err); }, 'Timeline_Storico');}.fadeToggle(400)

I isolate the parts of the model that I want to see. how can i add the degree of transparency?

iframe and JS function combination

$
0
0

I am currently trying to make a full iframe web-based game to avoid page refresh.

I have this function in JS that works perfect:

function changeUrl(){
    var site = "modules/news/news.php";
    document.getElementsByName('game_frame')[0].src = site;
}

This is my HTML:

<a href="#" onclick="changeUrl('news')">News</a>

<iframe frameBorder="0" style="height: width: 100%; height: 650px; visibility: visible; color: white;" allowtransparency="true" class="content" name="game_frame">
</iframe

But I would like to fetch a value through the function so that I don't have to repeat the code for every page.

I was trying this but I can't get it to work:

function changeUrl(siteName){
    var site = "modules/".siteName."/".siteName.".php";
    document.getElementsByName('game_frame')[0].src = site;
}

I have tried for about 2 days to fix this but can't seem to find the solution. I might be googling wrong ofc. Thanks in advance for answers :)

Best way to update button type after uploading file

$
0
0

I'm working on a work project that I need to modify. 

The web app works as follow : When user click "Add file" button, its attach the file... then when user click "Start upload" it start uploading the file thru googledrive API, and list/display the file on the list below the two buttons, then user can click Back button to go back to the previous page. (See pic attached)

but what I want now is, when it completes to upload the file, and display/list the file, the back button must change to Done.

as inside Done button, there's an action method that send notification thru API.

https://i.imgur.com/yiX7AcI.png

The thing is I'm unable to pass data from action method  in which upload is processing to the View to change back button to Done.

I tried to use ViewData in upload action method, but I'm unable to use it in View to change back button to Done and action that Done button.

Can you please help? Not sure if I need to change the logic, or need a better way of passing data from controller to View.

So my point is : I just want to change BACK button in Done button after the upload is successfully.

This is the upload Method

   [HttpPost]
    public JsonResult Upload(string folderName, string contextType = null)
    {
        var resultList = new List<ViewDataUploadFilesResult>();            

        var CurrentContext = HttpContext;
        filesHelper.UploadAndShowResults(CurrentContext, resultList, folderName);
        JsonFiles files = new JsonFiles(resultList);

        if (!resultList.Any())
        {                

            return Json("Error");
        }
        else
        {
            ViewData["UploadSuccess"] = "true".ToList();
            return Json(files);
        }
    }


    public void UploadAndShowResults(HttpContextBase ContextBase, List<ViewDataUploadFilesResult> resultList, string folderName)
    {
        var httpRequest = ContextBase.Request;

        foreach (string inputTagName in httpRequest.Files)
        {
            var file = httpRequest.Files[inputTagName];
            var googleDriveFile = DocumentManagementService.UploadFileToGoogleDrive(folderName, file);
            if (!String.IsNullOrEmpty(googleDriveFile.Id))
            {
                resultList.Add(UploadResult(googleDriveFile));
            }
        }
    }

promise.all render twice and return undefined

$
0
0

hello guys i am working with a react native project i am working with offline so i have to store data offline and when the internet is back i must redirect the user to a screen and send data to web and change a percentage but my problem is that the fetch render twice and the data returned after all promis is undefined and the fetch to server passed by the way in server and data base is changer well

here is my functions

export const syncOfflinedata = activities => {
  return dispatch => {
    Promise.all(
      activities.map(item => {
        Api()
          .put(putEvaluation(item._id), {evaluation: item.evaluation})
          .then(data => {
            dispatch(setProgressporcentage(1 / activities.length));
          })
          .catch(err => {
            console.log(err.message);
          });
      }),
    )
      .then(datafinished => {
        console.log('finished', datafinished);
      })
      .catch(e => {
        console.log(e);
      });
  };
};

close notification modal when click on host in angular 9

$
0
0

i have a component for topbar and in that topbar i have conponent for notification .

in notification component i have icon , when click on the icon , open the modal and when click again to going to close . for open or close i must click on icon .

my problem is here : i want when click on the other place on the page that modal going to close . i want handle that with angular .

Demo

how can i solve this problem ???????

Can I generate source code during webpack processing / bundling?

$
0
0

From another question I got a way to dynamically scan source folders using WebPack API, and I've written some code that loads each found class using dynamic imports.

But there's nothing really dynamic here, since source files will be fixed once bundled; so the above code could then be replace with one that statically imports each discovered class.

Is there a way to generate source code during webpack execution and add it to the bundling process?

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 check email id already exists in nodejs

$
0
0

Question:- How to check email id already exists in nodejs

Answer:- This code do two works. email id checked in database and otherwise new user created. first of all try this code and after that talk me right or wrong.

Viewing all 142159 articles
Browse latest View live


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