Posts

Showing posts with the label javascript

How can I find closest date value from an array according to the current date?

How can I find closest date value from an array according to the current date? I want to get the next closest date on this array according to the current date. var dates = [ 'Aug 18, 2018 03:24:00', 'August 19, 2018 03:24:00', 'September 17, 2018 03:24:00', 'September 14, 2018 03:24:00', 'August 18, 2018 03:24:00', 'July 16, 2018 03:24:00', 'July 15, 2018 03:24:00', 'December 15, 2018 03:24:00', 'July 13, 2018 03:24:00', ]; var now = new Date(); 4 Answers 4 First you need to convert each date into a timestamp then subtract each of them by the current date and store the timestamp difference in the temp array then get the index of the minimum value and use the index to access the closest date in the original array. var dates = [ 'July 16, 1995 03:24:00', 'Aug 18, 1995 03:...

undefined variable that equals to a node module

undefined variable that equals to a node module I try to transpire my file using browserify or webpack. This is my code: let rangy = require('rangy') rangy.init() const rang = () => rangy After transpire my code and add in a html page, I try to get rangy in console, but when i type rangy and press enter button, js says: rangy Uncaught ReferenceError: rangy is not defined When i type rang() and press enter, js says: rang() undefined But line 2 runs correctly. I need to use rangy in script tag of my index.html . rangy index.html How can I do this? This is my transpired file: (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n...

Trying to populate 16 random images using Math.random and a filter

Trying to populate 16 random images using Math.random and a filter ``import React from 'react' import { getCard } from '../redux' import { connect } from 'react-redux' import CardBoard from './CardBoard' class Board extends React.Component{ componentDidMount(){ this.props.getCard() } render(){ let gameCard = Math.floor(Math.random() * (54 - 2) +2); const game = () => { let cards = ; if(cards.length < 16) { cards.push(gameCard); } return cards; }; return( {this.props.cards .filter(one => one.number === gameCard) .map(card => ( ))} ); } } export default connect(state => state, { getCard })(Board)`` Welcome to stackoverflow B L! There is not quite enough information in your q...

Convert Javascript string to Dictionary

Convert Javascript string to Dictionary I'm trying to get Redis data in NodeJS. The Redis data needs to be converted to a dictionary for further processing. I gave it a try but finding difficult as parseFloat on string keeps giving me NaN. Can anyone please help me to do it the correct way? Variable string has the sample data in below code. Please see the expected results below. var string = "[ '[Timestamp('2018-06-29 15:29:00'), '260.20', '260.40', '260.15', '260.30']' ]"; string = string.replace("[", ""); string = string.replace("]", ""); string = string.replace("[", ""); string = string.replace("]", ""); s1 = string var array = string.split(","); var final = "{" + ""date"" + ":" + """ + array[0] + ","Open"" + ":" + """ + array[1].trim(...

How can I set timeout option on every request in page.goto function

How can I set timeout option on every request in page.goto function I use puppeteer to scrab resources in a page. but one of the js request can not success because of connection timeout, and it will block the page.goto('url') function for a long time. I want to skip this js request and continue to request next. so i need to set timeout on every request, but not a total timeout option on page.goto function. Follow is my code test.js: const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on('request', request => { console.log(request.url()) }) await page.goto(process.argv[2], {timeout: 10000}).then( () => { }, () => { console.log("timeout"); }); browser.close(); node test.js http://ipv6ready.wanwuyunlian.com:8080/ http://ipv6ready.wanwuyunlian.com:8080/ http://ipv6ready.wanwuyunlian.com:8080/js/bootstrap.min.js http://ipv6ready.wanwuyunlian.com:8080/js/echarts/echarts.min.js https://www.google-analytics.com/analyt...

Draggable and Record Marker Location Google Map Api

Draggable and Record Marker Location Google Map Api here I have a map, in my map, I want to make a marker there can be draggable. When i drag and drop the marker i want it make a record or just change my value of my input. here my script : var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { parking: { icon: iconBase + 'parking_lot_maps.png' }, library: { icon: iconBase + 'library_maps.png' }, info: { icon: iconBase + 'info-i_maps.png' } }; var locations = [ ['location 1', -33.80010128657071, 151.28747820854187, 2,"info"], ['location 2', -33.950198, 151.259302, 1,"info"] ]; var map = new google.maps.Map(document.getElementById('map'), { zoom: 11, center: new google.maps.LatLng(-33.92, 151.28747820854187), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i;...

reloading a web page and placing page at same place where user was at

reloading a web page and placing page at same place where user was at Is there a way in react or javascript to after reloading a page make that page to be at the same place where the user was looking at? So far, location.reload reloads the page but places that page at its beginning. 3 Answers 3 Add additional true parameter to force reload. document.location.reload(true) document.location.reload() stores the position, document.location.reload() ordinary reload tries to restore the scroll position after reloading the page, while in forced mode (when parameter is set to true) the new DOM gets loaded with scrollTop == 0. Reference : https://developer.mozilla.org/en-US/docs/Web/API/Location/reload My web page is defined by react components and the html page has only with an id tag. It seems this method does not work under these circumstances. – Jose Cab...

Reset/Submit button won't work once text area is edited by user?

Reset/Submit button won't work once text area is edited by user? My form's reset and submit buttons do not work when I edit the output of the form in the textarea. I created a form that outputs custom sentences based on user inputs. If I don't edit the textarea these buttons work fine, resetting or resubmitting onclick. However, if I edit the textarea all functionality seizes. Any ideas? Thanks! <3 <!DOCTYPE html> <html> <head> <title>Experiment</title> <style type="text/css"> table,td,th{ margin-left: auto;margin-right: auto } .display{ display: flex;align-items: center;justify-content: center; } p{ text-align: center; } textarea{ display: block;margin-left:auto;margin-right: auto; } </style> function sentence(){ document.getElementById("s1").style.display= 'block'; document.getElementById("r1").style.display= 'blo...

Session handling in HTML page using JavaScript [on hold]

Session handling in HTML page using JavaScript [on hold] Can we do session handling in HTML page with the help of javascript? If yes, how? If not, why? Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question. What do you mean with session handling? You can set and edit cookies if that is what you mean. – TJHeuvel May 7 '12 at 9:29 6 Answers 6 javascript only support cookies. You can set them up to keep track of a user session but they do not support the use of sessions. fu...

Get the node where you write

Image
Get the node where you write I want to get the node where the cursor is when it is being written document.getElementById('parent').addEventListener('keypress', function(e) { console.log(e.target); }); .root { padding-right: 1px; } #parent>div { border-color: yellow; float: left; } Qué es Lorem Ipsum </div> the problem is complicated because I am using for each word a div. I need to use div so you can display the suggestions in the words (I'm doing a spellchecker) So you need to do a list of suggestions based on the word the user has typed. To do that better use keyup event to get the word after being typed and not before. – facundo Jun 30 at 3:50 3 Answers 3 You could use window.getSele...

Dynamic select2 options using api

Dynamic select2 options using api I'll try to explain my problem as much as I can. I am trying to create, with select2 plugin, a way for the user to write some letters and on each letter pressed a call to an API that gives the first 20 results given by that API. select2 So I have my HTML select : <select name="filtre_products" class="form-control products-select2" multiple> </select> And then my JS (it's commented) : $(".products-select2").select2({ width: '100%', closeOnSelect: false, placeholder: '', minimumInputLength: 3, query: function (query) { var data = {results: }, i, j, s; if(query.term != null) { var ajax_r = ; $.ajax({ url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term, success: function(data_a){ //Getting the data data_a = JSON.parse...

how to scroll the list to top on button click in angular?

how to scroll the list to top on button click in angular? could you please tell me how to scroll the list to top on button click in angular ? I tried like this scrollToTop(el){ el.scrollIntoView(); } <button (click)="scrollToTop(target)">scroll to top</button> It scroll the list to top .but it hide my addressbar and then user not able see header I think it is not a good solution .anybody have any other good solution addressbar header here is my code https://stackblitz.com/edit/angular-f9qxqh?file=src%2Fapp%2Fapp.component.html 2 Answers 2 You can scroll to the top of the list by setting the scrollTop property of the container to zero. See this stackblitz for a demo. scrollTop {{i}} <button (click)="container.scrollTop = 0">scroll to top</button> Here is a simple method that scrolls smoothly to the top of the list. It is based on this an...

Custom Event emitter/consumers in Browser Javascript outside DOM

Custom Event emitter/consumers in Browser Javascript outside DOM Currently I have the following structure, an Object WebsocketService and multiple FrontendController s. WebsocketService FrontendController The WebsocketService listens on a websocket (duh) and updates the internal application state. This means in some cases the front end must be updated with new values. WebsocketService To keep my UI code and the application logic nicely seperated I envision a design where the FrontendController s can subscribe to events emitted the WebsocketService and very likely other Services later on. FrontendController WebsocketService I have read the documentation for Creating and triggering events on MDN. But all of that is very DOM centric. My WebsocketService obviously doesn't have an addEventListener function. WebsocketService addEventListener I would prefer to not use 3th-party libraries. A hack that comes to mind is simply have an id="events" DOM Node somewhere and having...

Why is my iframe blocked by cross origin even it is not

Why is my iframe blocked by cross origin even it is not I have a <iframe> inside a <div> . My outer url is http://localhost:9090 and the src in iframe is http://localhost:9090/Server/v1 . In my outer context I have below code to access iframe dom: <iframe> <div> http://localhost:9090 http://localhost:9090/Server/v1 const f1 = window.frames[iframeName]; const iFrameHead = f1.document.getElementsByTagName("head")[0]; and I get an exception on the second line: Uncaught DOMException: Blocked a frame with origin "http://localhost:9090" from accessing a cross-origin frame. The reason I want to access ifame dom is that I need to insert a script into that iframe. The src in iframe has the same protocol, hostname and port number. What I don't understand is the iframe is on the same origin as the parent context. Why does it complain about the cross origin? After some debugging, I found there is because the iframe was redirected to a different ...

Is the WebSocket constructor native Javascript?

Is the WebSocket constructor native Javascript? I'm wondering, is the WebSocket() constructor a part of native Javascript? Or is it a part of the "ws" module of node.js? If it's a part of the "ws" module, I'm confused, because I'm in a lynda.com training course, and this is a client-side js file that me and my instructor set up: var ws = new WebSocket("ws://localhost:3000"); ws.onopen = function() { setTitle("Connected to Cyber Chat"); }; ws.onclose = function() { setTitle("DISCONNECTED"); }; ws.onmessage = function(payload) { printMessage(payload.data); }; document.forms[0].onsubmit = function () { var input = document.getElementById('message') ws.send(input.value); input.value = ''; }; function setTitle(title) { document.querySelector('h1').innerHTML = title; } function printMessage(message) { var p = document.createElement('p'); p.innerText = message; document.querySelector('div.mes...

SyntaxError: Unexpected token ' { ' while starting the reactjs app in my terminal [duplicate]

SyntaxError: Unexpected token ' { ' while starting the reactjs app in my terminal [duplicate] This question already has an answer here: I tried to run existing clone reactjs app, the following error is accured in terminal, SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3 Here my start.js coding from (myappname)/node_modules/react-scripts/scripts/start.js:31 start.js (myappname)/node_modules/react-scripts/scripts/start.js:31 const { choosePort, createCompiler, prepareProxy, prepareUrls, } = require('react-dev-utils/WebpackDevServerUtils'); Then how to solve this problem? This question has been asked before and already has an answer. If those answers do not fully addre...

How to update a web page in reaction to a push-notification?

How to update a web page in reaction to a push-notification? I am exploring the world of push-notifications in Node.js and have one question. Following a few tutorials, I now have a small app firing a few notifications and those pop up in my web browser as expected. Here is the question: Instead of having a notification popping up, would it be possible to have a field in my web page updated? (For example: a clock or a counter) If the answer is YES, how can I do it? Do I need to change the service worker? The client? Or what? Here is the current code: const SECS = 5 * 1000; let rankVal = 0, counterVal = 1; const notificationLoop = setInterval(() => { let currentDate = new Date(), timeLag = (currentDate-referDate)/1000 const payload = JSON.stringify({ title:'Event is reached!', timeLag:timeLag.toString() }); webPush.sendNotification(subscription,payload).catch(err => console.error(err)); consol...

Wrapping Provider in same component throws Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Wrapping Provider in same component throws Element type is invalid: expected a string (for built-in components) or a class/function but got: object I wrote a simple counter example in both Mobx & Redux & it works Full demo is available https://codesandbox.io/s/nw303w6jxl But if I remove Provider from ./src/index.js Provider ./src/index.js const App = () => ( ); & put it in ./src/redux.js while default exporting it throws an error ./src/redux.js export default ( <Provider store={store}> <ConnectReduxApp /> </Provider> ); Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object Its working but I don't know why its happening? I checked the typeof the default exported function from ./src/redux.js ,i.e, typeof ./src/redux.js console.log( typeof( <Provider store={store}> <ConnectReduxApp /> ...

Stop click on child calling method on parent - React/JavaScript

Stop click on child calling method on parent - React/JavaScript I have a modal in React. When you click the background of the modal, the modal should close. The way I have it set up right now, if you click inside* the modal, it closes as well. Because the modal is inside the background> handleClose(e) { e.stopPropagation(); this.props.history.push('/business/dashboard') } render() { return ( <Background onClick={e => this.handleClose(e)} name="BACKGROUND"> <Container onClick={console.log("IT CLICKED")} to={'/business/dashboard'} name="CONTAINER"> .... When I click on Container, the onClick event for Background gets called. I don't want this to happen. This is a form that users will be clicking on all the time. I need the modal to only close when you click outside the modal on Background. while you could use something like npmjs.com/package/react-onc...