lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I tried with deno -V , it gives only deno 's version and does not include typescript version .
$ deno -Vdeno 1.0.0-rc2 $
How to see the typescript version is used in current deno version ?
JS
I am using twitter streaming api & johnny-five with some other modules http , express & socket.io with arduino unoMy script is working fine in laptop . But my production will be on a tablet . I have two tablets and both are responding differently . On hp omni tablet i am receiving following errorAlso i have arduino-uno...
var Twitter = require ( 'twitter ' ) ; var five = require ( `` johnny-five '' ) ; var express = require ( 'express ' ) , app = express ( ) , http = require ( 'http ' ) , server = http.createServer ( app ) , io = require ( 'socket.io ' ) .listen ( server ) ; server.listen ( 8080 ) ; // routingapp.use ( express.static ( ...
Nodejs modules not working as expected in different devices
JS
This may seem like a silly question , but what are the functional differences , if any , between these two patterns ? Is there no real functional difference and it 's just a matter of organization preference ? What are some instances when you would want to use one and not the other ? I 'm trying to find a design patter...
$ ( function ( ) { Core.init ( ) ; } ) ; var Core = { init : function ( ) { //some initialization code here } _plugins : function ( ) { //instantiate some plugins here } _display : function ( ) { //some more code here } _otherfunctions : function ( ) { ... . } } $ ( function ( ) { Core.init ( ) ; Plugins.init ( ) ; Dis...
JavaScript singleton patterns - differences ?
JS
Given N sorted arrays of integers ( no duplicates ) , I 'd like to calculate the first limit integers in their intersection.For example , given the following arrays : the intersection is [ 5 , 10 , 20 ] , so if limit = 2 , the result should be [ 5 , 10 ] .The given arrays should not be mutated.My attempt is below . Pla...
[ 2 , 5 , 7 , 8 , 10 , 12 , 13 , 15 , 20 , 24 ] [ 3 , 4 , 5 , 6 , 9 , 10 , 11 , 17 , 20 ] [ 1 , 2 , 3 , 5 , 6 , 10 , 12 , 20 , 23 , 29 ] function intersection ( sortedArrays , limit ) { var arraysCount = sortedArrays.length ; var indices = sortedArrays.map ( function ( array ) { return 0 ; } ) ; var values , maxValue ,...
Intersection of N sorted integer arrays with limit
JS
I have a Chrome extension in which I 'm trying to jump forward or backward ( based on a user command ) to a specific time in the video by setting the currentTime property of the video object . Before trying to set currentTime , a variety of operations work just fine . For example : BUT as soon as I try to jump to a spe...
document.getElementsByTagName ( `` video '' ) [ 1 ] .play ( ) ; // works finedocument.getElementsByTagName ( `` video '' ) [ 1 ] .pause ( ) ; // works finedocument.getElementsByTagName ( `` video '' ) [ 1 ] .muted = true ; // works finedocument.getElementsByTagName ( `` video '' ) [ 1 ] .muted = false ; // works fine d...
Set videoElement.currentTime in Hulu video player does n't work , and breaks the player
JS
I am using the ajax-datatables-rails . Below is the JS for my datatable . I want to convert the javascript into equivalent Opal.rb . It includes adding the CSRF token to the ajax request for data.I would like all of our javascript to be written as opal for readability , etc . Please do n't debate that choice , I only c...
jQuery ( document ) .ready ( function ( ) { var table = $ ( ' # organizations-datatable ' ) ; var token = $ ( 'meta [ name=csrf-token ] ' ) .attr ( 'content ' ) ; table.DataTable ( { `` processing '' : true , `` serverSide '' : true , `` ajax '' : { `` url '' : `` /organizations/datatable.json '' , `` type '' : 'POST '...
Converting Javascript datatables to use Opal in Rails app
JS
I watched John Resig 's Best Practices in JavaScript Library Design presentation ; one slide suggested `` tweaking '' the object constructor so it instantiates itself.With that , new jQuery ( `` # foo '' ) becomes jQuery ( `` # foo '' ) .I thought it was rather interesting , but I have n't written a constructor like th...
function jQuery ( str , con ) { if ( window === this ) { return new jQuery ( str , con ) ; } // ... }
Is wrapping new within the constructor good or bad ?
JS
I have some javascript that is supposed to run after the window loads but for some reason , it never runs.Here 's my code : The setClasses ( ) function does n't seem to run . It does however work when I manually call it through the console of FireBug.The code is placed in the header of my web page.Any help is appreciat...
function setClasses ( ) { document.getElementsByClassName ( `` gchoice_35_0 '' ) [ 0 ] .onclick = sedanShow ; document.getElementsByClassName ( `` gchoice_22_0 '' ) [ 0 ] .onclick = sedanShow ; document.getElementsByClassName ( `` gchoice_34_0 '' ) [ 0 ] .onclick = sedanShow ; document.getElementsByClassName ( `` gchoi...
Function is not Called
JS
I have 2 divs : A header div at the top of the page with a set height of 150px.A container div sitting under the header div.What I would like is for the container div to be dynamic and resize to 100 % of the remaining space underneath the header div . I have tried putting in height : 100 % but this makes the page need ...
body , html { margin : 0 ; height : 100 % ; } # header { width : 100 % ; height : 150px ; background-color : # 999999 ; } # container { width : 760px ; height : 100 % ; background-color : # CCCCCC ; margin : 0 auto ; } < div id= '' header '' > < /div > < div id= '' container '' > < /div >
Set height of div to 100 % of remaining space under header
JS
EDIT : I 'm still not there yet . I have placed a bounty on this question because I could really do with the answer . I have made do with the idea of elements that represent the planets that do n't revolve around the center . Because of this , you can skip steps 1 & 2 and go straight to 3 to try to help me out.ORIGINAL...
//this is an array that holds all of the json data var arr= [ { `` rowid '' : 1 , `` Host name '' : `` 11 Com '' , `` Number of Planets in System '' : 1 , `` Planet Mass or M*sin ( i ) [ Jupiter mass ] '' : 19.4 , `` Planet Radius [ Jupiter radii ] '' : null , `` Planet Density [ g '' : { `` cm**3 ] '' : null } , `` Di...
Visualise JSON elements using some math
JS
Supose you have a recursive function like : Is the child.add ( ) a tail call ? If not can it be written so it is ?
Blah.prototype.add = function ( n ) { this.total += n ; this.children.forEach ( function ( child ) { child.add ( n ) ; } ) ; } ;
Is this a tail call ? ( Javascript )
JS
I 'm trying to extract a substring matching a given pattern from a string in Javascript.Example : Is there an easier way to acheive this ? A one-liner , preferably ?
var classProp = 'active category_games ' , match = classProp.match ( /category_ [ a-z ] +\b/ ) , category ; if ( match ! == null & & match.length > 0 ) { category = match [ 0 ] ; }
Easier way to extract a substring in Javascript
JS
I want to be able to do this in JavaScript : I tried this and it does n't work . I do n't know how to call this type of parameters , could somebody point me in the right direction ? Thanks .
function myFunction ( one , two = 1 ) { // code } myFunction ( `` foo '' , `` 2 '' ) ; myFunction ( `` bar '' ) ;
pre-defined parameters
JS
I 'm getting the following error : Here 's the relevant part of the template : Here 's my code : The console.log at the end shows that it 's an observable : this.imagesData.getData ( ) return a regular RxJS observable from Angular 's Http service , so why would n't async pipe work with it ? Maybe the way I 'm using fla...
EXCEPTION : Can not find a differ supporting object ' [ object Object ] ' in [ files | async in Images @ 1:9 ] < img *ngFor= '' # file of files | async '' [ src ] = '' file.path '' > export class Images { public files : any ; public currentPage : number = 0 ; private _rawFiles : any ; constructor ( public imagesData : ...
Angular 2 AsynPipe is n't working with an Observable
JS
I 'm familiar with variant type of OCaml . For example , I know how to define Number and String in MongoDB , but my question is how to define the variant type as above in MongoDB : Does anyone have any idea ? Edit 1 : I just found this answer and this answer . They use classes or functions to mimic variant . It works w...
type foo = | Int of int | Pair of int * string var PostSchema = new mongoose.Schema ( { num : { type : Number } , name : { type : String } , variant : ? ? ? } )
Define variant type in Mongoose
JS
Let 's suppose I have these two functions : In most browsers , except Opera , this returns [ `` original '' , `` = > `` , `` original '' ] .But if I change the f function like this , it will return [ `` original '' , `` = > `` , `` changed '' ] in IE9 , Safari 5 , and Firefox 16 and 17.If I replace eval ( `` '' ) with ...
function change ( args ) { args [ 0 ] = `` changed '' ; return `` = > `` ; } function f ( x ) { return [ x , change ( f.arguments ) , x ] ; } console.log ( f ( `` original '' ) ) ; function f ( x ) { return [ x , change ( f.arguments ) , x ] ; eval ( `` '' ) ; }
Why does an unexecuted eval have an effect on behavior in some browsers ?
JS
I am just trying to get my head around event driven JS , so please bear with me . There are different kinds of modules within my app . Some just encapsulate data , others manage a part of the DOM . Some modules depend on others , sometimes one module depends on the state of multiple other modules , but I do n't want th...
var dataModule = { data : 3 } ; var configModule = { factor : 2 } ; var displayModule = { display : function ( data , factor ) { console.log ( data * factor ) ; } } ; pubsub.subscribe ( `` init '' , function ( ) { displayModule.display ( dataModule.data , configModule.factor ) ; } ) ; pubsub.publish ( `` init '' ) ; //...
Mediate and share data between different modules
JS
I am trying to make a button that increments a counter 's value by 1 when clicked . My code , however , does n't seem to work .
var count = 1 ; var button = document.querySelector ( `` # increment '' ) ; button.addEventListener ( `` click '' , function ( ) { var increment = document.getElementById ( `` # count '' ) ; increment.value = count ; count++ ; } ) ; < h4 > Current count : < span id= '' count '' > 0 < /span > < /h4 > < div class= '' con...
How can I create a button that increments a counter when clicked ?
JS
In the code below I expected to see the following sequence but I get Why ?
1 , 2 , loaded 1 , loaded , 2 < html > < script > window.onload = function ( ) { alert ( 'loaded ' ) ; } ( function ( ) { alert ( ' 1 ' ) ; } ( ) ) ; ( function ( ) { alert ( ' 2 ' ) ; } ( ) ) ; < /script > < body > < /body > < /html >
Javascript strange loading sequence
JS
Well , this is kind of hacky : Is there a better way to do this in Javascript ? Using any ofmore intelligent boolean/number handlingsneaky array or functional operationsAnd so forth . Javascript and Node solutions welcome.In my actual problem , the options are coming from the Node module commander , so I 'm not dealing...
function b2n ( boo ) { return boo ? 1 : 0 ; } if ( b2n ( opt1 ) + b2n ( opt2 ) + b2n ( opt3 ) ! == 1 ) { throw new Error ( `` Exactly one option must be set '' ) ; }
Check exactly one boolean option set
JS
I am testing module example from JavaScrit : The Good Parts . I do n't know who passes in a and b in function ( a , b ) . Somehow it works .
Function.prototype.method = function ( name , f ) { this.prototype [ name ] = f ; return this ; } String.method ( 'de ' , function ( ) { var entity = { lt : ' < ' , gt : ' > ' } ; return function ( ) { return this.replace ( / & ( [ ^ & ; ] + ) ; /g , function ( a , b ) { document.write ( `` < br > a= '' + a + `` b= '' ...
What are values of function ( a , b ) ?
JS
To avoid memory leaks in my Angular app i 'm using the following well-known pattern to unsubscribe from Observables : This seemingly works fine , but in some examples i 've noticed that complete ( ) is also called on the Subject in addition to next ( ) : Is calling complete ( ) necessary here ? If so , why ? What are t...
unsubscribe = new Subject ( ) ; ngOnInit ( ) { this.myService.getStuff ( ) .pipe ( takeUntil ( this.unsubscribe ) ) .subscribe ( result = > { // processing the result } ) ; } ngOnDestroy ( ) { this.unsubscribe.next ( ) ; } ngOnDestroy ( ) { this.unsubscribe.next ( ) ; this.unsubscribe.complete ( ) ; // like this }
Is completing the Subject necessary when using the takeUntil pattern to unsubscribe from Observables ?
JS
You can use destructuring assignment to define enumerations in ES6 as follows : Instead , I 'd like the right hand side of the destructuring assignment to be dynamic . For example : Unfortunately , this seems like a hack . What if I want a bigger enumeration in the future ? Hence , I was thinking of using destructuring...
var [ red , green , blue ] = [ 0 , 1 , 2 ] ; var MAX_ENUM_SIZE = 32 ; var ENUM = new Array ( MAX_ENUM_SIZE ) ; for ( var i = 0 ; i < MAX_ENUM_SIZE ; i++ ) ENUM [ i ] = i ; var [ red , green , blue ] = ENUM ; var [ red , green , blue ] = enumeration ( /* I do n't want to specify size */ ) ;
How to use destructuring assignment to define enumerations in ES6 ?
JS
I 've got a bunch of working unit tests for various Angular ( 1.4.7 ) directives , and I 'm using Karma , Jasmine and Sinon for testing.I 'm trying to add a unit test for a new directive , which is the only directive I currently have that uses $ window but I 'm seeing a cryptic error in the console output : TypeError :...
testElement = document.createElement ( 'div ' ) ; testElement.setAttribute ( 'data-my-directive ' ) ; document.body.appendChild ( testElement ) ; $ compile ( testElement ) ( $ scope ) ; module ( 'app ' , function ( $ provide ) { $ provide.value ( ' $ window ' , { id : 'test ' } ) ; } ) ;
Unable to unit test an Angular directive that uses $ window
JS
Can someone explain to me why this returns an empty string ( `` '' ) instead of a boolean ( false ) ? ... While this works as expected , returning true : I am basically just trying to do a simple shorthand check to see if a value exists in a variable ( ensuring it 's not undefined , null , or empty string ) .I know I c...
var x = `` '' ; alert ( x & & x.length > 0 ) ; var y = `` abc '' ; alert ( y & & y.length > 0 ) ;
Javascript returning string on what should be a shorthand boolean test
JS
I have some data which isThe data is flat and I need to convert it into something like : ( I think the above is valid ) ? I 'm very lost as to how . I am going to show my effort but , I 'm not sure if my approach is correct or not.I think I 've made a mess of it . In the comments I 've put a ** explaining that it is n'...
var currentData = [ { 'ticket ' : 'CAP ' , 'child ' : 'CT-1 ' } , { 'ticket ' : 'CAP ' , 'child ' : 'CT-2 ' } , { 'ticket ' : 'CT-1 ' , 'child ' : 'CT-1-A ' } , { 'ticket ' : 'CT-1 ' , 'child ' : 'CT-1-B ' } ] ; { 'ticket ' : 'CAP ' , children : [ { 'ticket ' : 'CT-1 ' , 'children ' : [ { 'ticket ' : 'CT-1-A ' , 'child...
How to convert an array into a hierarchical array
JS
we are using below code to filter rows based on selected From & To date.we can able to filter successfully & displaying results.phpformjquerynow we want to display how many rows are selected . if result is as above image we want to display `` rows : 1 '' . i am very new to php & i tried below code , but its not display...
/* to show selected date */if ( isset ( $ _POST [ 'post_at ' ] ) & & $ _POST [ 'post_at ' ] ! = `` ) { $ orderFromDate = $ _POST [ 'post_at ' ] . `` 00:00:00 `` ; } else { $ orderFromDate = `` ; } if ( isset ( $ _POST [ 'post_at_to_date ' ] ) & & $ _POST [ 'post_at_to_date ' ] ! = `` ) { $ orderToDate = $ _POST [ 'post...
Show the count of Displayed results
JS
This is not a real coding question , more of a real-world statement.I have previously noted that DOMReady events are slow , very slow . So , I noticed while browsing the jQuery source that the jQuery domeready event can be trigger using $ .ready ( ) . Then I thought , placing this simple execution script just before cl...
< script > $ .ready ( ) < /script > < /body >
$ .ready ( ) before closing body
JS
I 'm creating an object ( dataObj ) that returns several items within it , inside a $ getJSON : When I console.log the dataObj.cities it all looks fine and there are lots of items , however the length is at 0 , which I 'm sure is the source of my problems . I 've been fiddling around and searching for some time for a s...
var cities = [ 'london ' , 'paris ' , 'munich ' , 'geneva ' , 'prague ' , 'vienna ' , 'barcelona ' , 'istanbul ' ] , totalCities = cities.length , i = 0 , $ container = $ ( ' # cities ' ) , htmlFragment , data , obj , dataObj = { cities : [ ] } ; function appendData ( ) { var city = cities [ i ] , locationQuery = escap...
Object length is 0 , but there are several items within it
JS
Let 's say we have an Object : Now I would like to add some functionality that occurs any time a property is set ( also get for this matter actually ) in this object . Let 's just keep it simple and say the added functionality is just a console.log ( `` a set/get action was just triggered on obj ! `` ) .How can I achie...
const obj = { foo : bar , boop : `` beep '' , } // simple : obj.foo = `` not bar anymore ! `` ; // console output : a set/get action was just triggered on obj ! obj.rand = `` a randomly added prop here '' ; // console output : a set/get action was just triggered on obj ! // advanced : obj.boop = `` burp '' ; // console...
Is it possible to define a 'global ' getter/setter method on a Javascript object , so that it is invoked whenever any property is got/set ?
JS
What are the repercussions of adding functions to the String class in JavaScript ? Is this a bad idea ? E.g. ,
// String functionsString.prototype.startsWith = function ( string ) { return ( this.indexOf ( string ) === 0 ) ; } String.prototype.empty = function ( ) { //console.log ( $ .trim ( this.valueOf ( ) ) ) ; if ( $ .trim ( this.valueOf ( ) ) == `` ) { return true ; } else { return false ; } }
What are the performance repercussions of adding functions to the String class in JavaScript and Node.js ?
JS
My project relies on JavaScript to dynamically display content on a hyperlink click . In order to make it cleanly degrade without JavaScript enabled , I 'm simply showing all page content and using hyperlinks and anchors to connect the pieces.I 'm relying on jQuery to identify the click of the hyperlink by ID , so with...
< div id= '' link1 '' > < noscript > < a href= '' # link1content '' > < /noscript > 1 . Link Name Here < noscript > < /a > < /noscript > < /div >
noscript to filter add hyperlinks - Clean JavaScript degrade
JS
I am using Ext JS 3 and I need to get ahold of the menu of my column header . I tried to use afterrender of grid.My code is somewhat likeBut apparently headerCt is not available in Ext JS 3 . What other possible options can I use ? I did not get any ideas from the Docs .
listeners : { afterrender : function ( ) { var menu = this.headerCt.getMenu ( ) ; // wrong } }
What is the alternate of headerCt.getMenu ( ) ; in Ext JS 3
JS
The AJAX response returns a list of < a > elements : How do I select only the first n a elements from the response ? That 's what I 'm currently trying but I 'm getting a Uncaught Error : Syntax error , unrecognized expression followed by the whole response .
< a href= '' /1/ '' > One < /a > < a href= '' /2/ '' > Two < /a > < a href= '' /3/ '' > Three < /a > $ .ajax ( { url : '/ ' + page , success : function ( res ) { btn.after ( $ ( ' a ' , $ ( res ) ) .slice ( 0,20 ) ) ; } } ) ;
Limit number of elements from AJAX response
JS
Say that I have two classes called Book and Library as follow : andMy question is : How can I Unit testing the Library class using QUnit to have a real atomic and independent test ? I wrote this test function but it has not satisfied me . It does not seem to be very atomic and independent since it mix several functions...
var Book = function ( title , author ) { this.title = title ; this.author = author ; } ; var Library = function ( ) { var dbName = 'test ' ; this.getLibrary = function ( ) { return JSON.parse ( window.localStorage.getItem ( dbName ) ) ; } ; this.save = function ( library ) { window.localStorage.setItem ( dbName , JSON....
How to have a real atomic test in QUnit ?
JS
We are using hydrate from react-dom in a project and are having a hard time detecting broken image links . These images come from a 3rd party API so we have no way of knowing which links work beforehand.The above code works if we use render instead of hydrate . Is there a way to detect broken images when using hydrate ...
export default class Image extends PureComponent { render ( ) { return ( < img src= { this.props.src } onError= { ( e ) = > { e.target.src='https : //mycdn.com/fallback.jpg ' ; } } / > ) } }
Detect broken image when using hydrate instead of render from react-dom
JS
Using parse.com and the JavaScript SDK . The code should let a user sign up and upload a profile picture.Updated , this is the code I 'm using that is returning an error when trying to sign up a user the console message is Uncaught TypeError : Can not read property 'length ' of undefined
> $ ( ' # SignUp ' ) .click ( function ( e ) { > UserSignUp ( ) ; } ) ; > > > function UserSignUp ( ) { > > var user = new Parse.User ( ) ; > userFirstname = $ ( ' # firstnamesu ' ) .val ( ) ; > userLastname = $ ( ' # lastnamesu ' ) .val ( ) ; > userUsername = $ ( ' # usernamesu ' ) .val ( ) ; > userGender = $ ( ' # ge...
Unable to let user upload profile picture in sign up process ( Parse.com/JS SDK )
JS
I am new to angular 6 and it 's navigation/routing , I am sorry if this sounds obvious.I am trying to have a button with a function to navigate to the login page , but I keep getting this error : '' Error : Uncaught ( in promise ) : Error : Can not match any routes . URL Segment : 'login'Error : Can not match any route...
< button ion-button ( click ) = `` openLogin ( ) '' > Efetuar login < /button > import { NgModule } from ' @ angular/core ' ; import { Routes , RouterModule } from ' @ angular/router ' ; import { LoginComponent } from './login/login.component ' ; const routes : Routes = [ { path : 'login ' , outlet : 'login ' , compone...
Error when creating a navigate function through button click using router Angular 6
JS
Can someone explain this ? IE8
( function ( ) { window.foo = function foo ( ) { } ; console.log ( window.foo === foo ) ; // false } ( ) ) ;
IE8 ` window.fn ! == fn `
JS
I have a Gatsby app setup.src/ -- -images/foo.jpg // < -- - the img i want on my facebook shareable URL ( og : image ) . -- -images/ // < -- note , there are loads of PNG files i 'm using that seem to trip/default onto the FB image/share. -- -assets/ // < -- - loads of SVGs i 'm using that -- -components/seo.js // comp...
function Home ( ) { return ( < React.Fragment > < SEO / > const SEO = ( { title , description , image , article } ) = > { const { pathname } = useLocation ( ) const { site } = useStaticQuery ( query ) const { defaultTitle , titleTemplate , defaultDescription , siteUrl , defaultImage , // < -- defaultImage is destructur...
Why ca n't Gatsby / Facebook find my og : image
JS
I have a class : I hook filterSelection method to other items through : When filterSelection is called , the event.data points to the instance of my class . Now I need to call filterSelection manually from within the initialize ( ) method . How can I do this which setting the correct parameters ?
function x ( ) { this.initialize = function ( ) { } this.filterSelection = function ( event , ui ) { /* code */ } } $ ( item ) .on ( `` click '' , this , this.filterSelection ) ;
Execute an event manually in JavaScript
JS
While digging into the source code of the underscore library , I found at that _.each relies on an ECMAScript 5 API Array.forEach whenever available : I noticed that jQuery.each ( the static one , not the .each method of a jQuery wrapper ) does just a traditional for that calls the callback function , no matter if forE...
var each = _.each = _.forEach = function ( obj , iterator , context ) { if ( obj == null ) return ; if ( nativeForEach & & obj.forEach === nativeForEach ) { obj.forEach ( iterator , context ) ; } else if ( obj.length === +obj.length ) { for ( var i = 0 , l = obj.length ; i < l ; i++ ) { if ( iterator.call ( context , o...
Is there a reason why jQuery.each does n't rely on Array.forEach when available ?
JS
I have this text : nisi non text600 elit where 600 is added dynamically . How can I get it ? This alerts text600 , how can I alert only 600 without an additional replace of the word text ( if that is possible ) ? Any help is appreciated , thank you !
var str = ( 'nisi non text600 elit ' ) .match ( /text\d+/ ) ; alert ( str ) ;
JavaScript ( regex ) : excluding matches from output
JS
Nullish coalescing operator allows to assign a variable if it 's not null or undefined , or an expression otherwise.It is an improvement over previously used || because || will also assign other if b is empty string or other falsy , but not nullish value.However sometimes , we also use & & for value assignment , for ex...
a = b ? ? other a = b & & func ( b )
Opposite of nullish coalescing operator
JS
I open a window using javascript window.open ( ) The window that opens has the following code : Now this code is triggered upon 'lang ' select menu change . I open the window programmatically using window.open and I managed to populate data into the window fields using Window.executeScript ( ) . For example this works ...
jQuery ( document ) .ready ( function ( ) { jQuery ( `` # lang '' ) .change ( function ( ) { var lname = jQuery ( this ) .val ( ) .split ( `` - '' ) ; window.location = ' < ? php echo JURI : :root ( ) ; ? > index.php ? lang='+lname [ 0 ] ; alert ( lname [ 0 ] ) ; alert ( 'lang '+lang ) ; } ) ; loginWindow.executeScript...
Change selectMenu option programmatically in child inAppBrowser
JS
I got another question regarding jQuery 's architecture . $ ( 'div ' ) constructs a new jQuery object : I 'd like to know why it is possible to query it like an array , allthough it is n't an array ? I just love this syntax , it looks so clean ! I also noticed this returns the DOM nodes as an array : Can somebody expla...
$ ( 'div ' ) instanceof jQuery ; // true $ ( 'div ' ) [ 0 ] ; // returns the first div in the document as a DOM node. $ .isArray ( $ ( 'div ' ) ) ; // false console.log ( $ ( 'div ' ) ) ; var a = [ ' a ' , ' b ' , ' c ' ] ; a.method = function ( ) { return 'test ' ; } ; a ; // [ ' a ' , ' b ' , ' c ' ] a [ 0 ] ; // ' a...
Why is it possible to query jQuery ( 'div ' ) like an array ?
JS
With short circuiting you can prevent the evaluation of part of an expression : Since the logical ops form expressions you can use them in function invocations or return statements.But ultimately , that 's nothing more than conditional branching and can be easily reached with the ternary operator : This is more readabl...
let x = `` '' , y = 123 ; x & & alert ( `` foo '' ) ; // `` '' y || alert ( `` bar '' ) // 123 x ? alert ( `` foo '' ) : x ; // `` '' y ? y : alert ( `` bar '' ) ; // 123
Can the ternary operator be equivalent to short circuiting with the logical operators ?
JS
I am interested in validating or automatically correcting the use of the indefinite articles `` a '' and `` an '' in blocks of English text from a textarea.The grammatical rule is that the choice of article depends on the sound that begins the next word . Details here and here . This appears incredibly broad , however ...
function fixArticles ( txt ) { var valTxt = txt.replace ( /\b ( a|an ) ( \w* ) \b/gim , function ( match , article , following ) { var newArticle = article.charAt ( 0 ) ; switch ( following.charAt ( 0 ) .toLowerCase ( ) ) { case ' a ' : case ' e ' : case ' i ' : case ' o ' : case ' u ' : newArticle += ' n ' ; // an bre...
Replace incorrect use of `` a '' and `` an '' in text input
JS
Below is my array : Now in above array , selected property represent check/uncheck status of checkbox and i am posting above array to web service ( WCF ) as string using json.stringify.Above array contains 2000 - 4000 records and now user can check/uncheck checkboxes.Now consider there are 4000 records in above array i...
var.child.Cars1 = { name : null , operation:0 , selected : false } Error : ( 413 ) Request Entity Too Large
Suggestions on posting huge string to web service
JS
Background : I am getting 400 errors ( and a blank 400 page response ) from a malformed cookie on my site ( coming from one of my affiliate pages ) . I have wrote a code to delete the cookie , but some of my customers still get an error because it 's in their cache . Once they clear their cache the problem is fixed . T...
const clearDefectiveCookies = ( req , res , next ) = > { const cookies = req.cookies ; const defectiveCookies = Object.keys ( cookies ) .filter ( key = > typeof cookies [ key ] === 'string ' & & ( cookies [ key ] .charAt ( 0 ) === '= ' ) ) ; if ( defectiveCookies.length > 0 ) { defectiveCookies.forEach ( defectiveCooki...
How to Avoid throwing 400 errors from ExpressJS
JS
I 'm trying to to implement touch scroll in less extension to jQuery Terminal . It work similar to less unix command.I have this code : and inside less I have : I also have this css : on Mousewheel scrolling works good it scroll with the same amount of scroll_by which is by default 3 ( seems about right ) . ( pos is li...
self.touch_scroll ( function ( event ) { // how much difference changed since last touch move var delta = event.current.clientY - event.previous.clientY ; var ret ; var interpreter = interpreters.top ( ) ; if ( is_function ( interpreter.touchscroll ) ) { ret = interpreter.touchscroll ( event , delta , self ) ; } else i...
Touch move fire only once when implementing `` less '' like scrolling on mobile
JS
Given a named function utilized to handle a Promise valuea ) Passing the named function handlePromise as a reference to .then ( ) b ) Using an anonymous or named function as parameter to .then ( ) and returning the named function handlePromise with Promise value as parameter within the body of the anonymous or named fu...
function handlePromise ( data ) { // do stuff with ` data ` return data } promise.then ( handlePromise ) promise.then ( function /* [ functionName ] */ ( data ) { return handlePromise ( data ) } )
Are there differences between .then ( functionReference ) and .then ( function ( value ) { return functionReference ( value ) } ) ?
JS
If I specify YYYY-MM-17 as a date to moment.js , it says it is a valid date : https : //jsfiddle.net/seu6x3k3/3/I 'm also seeing different results on different browsers . According to the docs : ... we first check if the string matches known ISO 8601 formats , then fall back to new Date ( string ) if a known format is ...
var myMoment = moment ( 'YYYY-MM-17 ' , 'YYYY-MM-DD ' ) ; console.log ( myMoment.isValid ( ) ) ; // - > trueconsole.log ( myMoment.get ( 'year ' ) ) ; // - > 2017console.log ( myMoment.get ( 'month ' ) ) ; // - > 0console.log ( myMoment.get ( 'day ' ) ) ; // - > 0 var date = new Date ( 'YYYY-MM-17 ' ) ; // - > NaNconso...
moment.js is doing weird things when parsing a badly formatted date
JS
There are two types of images in our json files ... .1.Mask imagesWhich have Transparent background as below :2.Background images : Any normal imagesRight now I am displaying Icons on all images as in below codepens ... .Icons on Mask images : https : //codepen.io/kidsdial/pen/aMPvamIcons on Background images : https :...
`` layers '' : [ { `` src '' : `` image1.png '' , `` name '' : `` mask_image_1 '' } , `` layers '' : [ { `` src '' : `` image2.png '' , `` name '' : `` bg_image '' } , if ( layer.name == mask_image_1 ) { imageUrl : imageUrl , } var target ; var imageUrl = `` https : //i.imgur.com/As37YCl.png '' ; let jsonData = { `` la...
Display icons only on mask images
JS
From the quickstart sb-admin-angular , I am trying to run the tests , but I get the error unable to init ocLazyLoad . ( This is a Windows7 machine . ) The command I use to run the tests is : I understand from this thread that I must make sure that the path to the ocLazyLoad script is added in karma.conf.js . I have als...
$ grunt test -- force files : [ 'bower_components/angular/angular.js ' , 'bower_components/angular-mocks/angular-mocks.js ' , ... 'bower_components/oclazyload/dist/ocLazyLoad.min.js ' , 'app/scripts/**/*.js ' , 'test/mock/**/*.js ' , 'test/spec/**/*.js ' ] , Unable to find a suitable version for oclazyload , please cho...
Karma tests error `` unable to init ocLazyLoad ''
JS
Node.JS v0.11.3 claims to have support for ECMAScript 6 symbols with the -- harmony_symbols flag ( see here ) . The latest draft says Properties are identified using key values . A key value is either an ECMAScript String value or a Symbol value.I have tried the following examplebut I get an error on the last line Type...
var mySymbol = new Symbol ( 'Test symbol ' ) ; console.log ( mySymbol.name ) ; // prints 'Test symbol ' , as expectedvar a = { } ; a [ mySymbol ] = 'Hello ! ' ;
How do symbols work ?
JS
I have a form created in vue and added to a blade page.app.jsblade.phpAdviceForm ComponentWhen I try to add v-model for inputs I get an error saying Property or method `` name '' is not defined on the instance but referenced during render . I am sure the name is defined in the data property . Also , the < advice-form >...
new Vue ( { router , components : { 'advice-form ' : AdviceForm , } } ) . $ mount ( ' # app ' ) ; < div class= '' my-6 '' > < advice-form > < /advice-form > < /div > < template > < input class= '' md : w-auto w-full '' type= '' text '' name= '' name '' id= '' name '' placeholder= '' Full name '' v-model= '' name '' / >...
Vue-Laravel form Submission
JS
Can anybody break down for me into steps how this ( it looks simple in the first place ) is interpreted by the browser : it will bring 1 . If I would change a function name to anything else , etc : it will alert 10 .
var a = 1 ; function b ( ) { a = 10 ; function a ( ) { } } b ( ) ; alert ( a ) ; var a = 1 ; function b ( ) { a = 10 ; function m ( ) { } } b ( ) ; alert ( a ) ;
How this simple javascript script actually works ( might be scoping ) ?
JS
I was testing performance ( with chrome timeline ) on cases if variable defined inside a closure . So it 's values would not be exposed to user.As expected run_proto_fn run few times faster and with minimal garbage collections , and low memory heap.But run_proto_obj happened to make exact opposite , as if it was costly...
SOME = function ( ) { } ; SOME.prototype.exe = function ( v ) { var x = { a : 'Lorem ipsum dolor sit amet , consectetur adipisicing elit . Ea , quae repudiandae eveniet cumque consequatur vitae aut . Nisi perspiciatis magnam explicabo optio reprehenderit dignissimos at porro quam , neque dolorum , architecto odit ? Lor...
Javascript profiling mystery - closure variables
JS
I am working on a page that uses JavaScript to manage a queue . My challenge is my code has nested callbacks . The nested callbacks are confusing me in regards to the scope of my queue . Currently , I have the following : The send function behaves differently based on the details of item . Sometimes the item will be se...
function MyApp ( ) { } module.exports = MyApp ; MyApp.myQueue = [ ] ; MyApp.queueIsLocked = false ; MyApp.enqueue = function ( item , onSuccess , onFailure ) { if ( ! MyApp.queueIsLocked ) { MyApp.queueIsLocked = true ; MyApp.myQueue.push ( item ) ; MyApp.queueIsLocked = false ; item.send ( function ( ) { console.log (...
Managing a queue in JavaScript via callbacks
JS
I am building my Ionic application for production . To do so , I am using ionic build -- prod command and the application is building successfully , But when I am running my application on the server then it is giving me errors of : cordova.js , main.js , Vendor.js . ( Please ignore the errors of Firebase ) The screens...
< ! DOCTYPE html > < html lang= '' en '' dir= '' ltr '' > < head > < meta charset= '' UTF-8 '' > < title > BOS < /title > < meta name= '' viewport '' content= '' viewport-fit=cover , width=device-width , initial-scale=1.0 , minimum-scale=1.0 , maximum-scale=1.0 , user-scalable=yes '' > < meta name= '' format-detection ...
How to build an Ionic application in Production mode , Ionic build is behaving differently
JS
i was wondering if there was some sort of event triggered when javascript is enabled in a browser ( ie . in firefox , tools- > options- > check off enable javascript- > click ok ) . i want to redirect a user to a page when this happens . any ideas ? Thanks ! EDIT : i 've put an iframe into the page but am not getting t...
< iframe style= '' display : none '' > < html > < head > < title > my iframe < /title > < meta http-equiv= '' Refresh '' content= '' 5 '' / > < script type= '' text/javascript '' > window.parent.location.href = 'home.php ' ; alert ( `` HELLO '' ) ; < /script > < /head > < /html > < /iframe >
how do you redirect to a page as soon as a user enables their javascript ?
JS
I 'm trying to edit an array and remove elements that do not meet a certain condition . If I use a reverse for loop combined with .splice ( index , n ) , the code works just fine . I 'm stuck at implementing the same using the ES6 for ... of loopUsing for..ofIs there a way to achieve this functionality using a for ... ...
let array= [ 1,2,3 ] ; //reverse for loopfor ( var i=array.length - 1 ; i > =0 ; i -- ) { if ( array [ i ] > =2 ) { /*Collect element before deleting it . */ array.splice ( i,1 ) ; } } console.log ( array ) ; // returns [ 1 ] let array= [ 1,2,3 ] ; for ( let entry of array ) { if ( entry > =2 ) { let index = array.inde...
Remove array item using for ... of loop
JS
I am trying to retrieve the data dynamically from MySQL database into web page using AJAX technique but the div content is repeated . I want to refresh the div without duplicate the information . here is the codeapi.php client.php
< ? php require 'db.php ' ; $ query = `` SELECT * FROM variables '' ; $ result = mysqli_query ( $ con , $ query ) ; $ data = array ( ) ; while ( $ row = mysqli_fetch_row ( $ result ) ) { $ data [ ] = $ row ; } echo json_encode ( $ data ) ; ? > < html > < head > < script language= '' javascript '' type= '' text/javascri...
Stop repeating div content in PHP AJAX MySQL
JS
I have a code source that contains a long variable name ( postCustomThumbnailsScrollerHeight ) .I do n't want to rename this variable for the whole code source so that I easily continue the project , but to have a shorthand of its name . I tried following solution ( which works ) at the first declaration of the variabl...
var postCustomThumbnailsScrollerHeight= d= $ ( '.post-scroller ' ) .outerHeight ( ) ;
Give a second name to a variable in javascript
JS
According to this MDN page , toLocaleString is about converting dates . However , Chrome exposes the function on more than strings . For example : What is the toLocaleString ? Why is it exposed , for example , on the empty function ?
a = function ( ) { } ; a.toLocaleString ( ) ; // `` function ( ) { } ''
What is toLocaleString ( ) ?
JS
I 'm trying to bing a click event to a new < div / > in jQuery . The following snippit works ( when I click the div , I see the 'clicked ' message ) however , the second doesn't.Could anyone tell me why ? Working snippet : Not working snippet : ( The alert 'ready ' is fired , but not the click ' ) UpdateJust tried the ...
'use strict ' ; ( function ( ) { $ ( document ) .ready ( function ( ) { var $ display = $ ( ' # display ' ) , $ drawingArea = $ ( ' < div / > ' ) .attr ( 'id ' , 'drawing-area ' ) .click ( function ( ) { alert ( 'clicked ' ) ; } ) ; $ display.wrap ( $ drawingArea ) ; } ) } ) ( ) ; 'use strict ' ; ( function ( ) { $ ( d...
Why does my first snippit work , but my second does n't ?
JS
I have a range input field with a numeric value which changes when I drag : When I drag all the way to the right , the max value of the input increases . Then , when I release ( onMouseUp or onTouchEnd ) , the max value decreases so that I can drag further and continue increasing max by dragging : When I drag all the w...
// After arbitrary period , increase the rate at which the max value incrementsthis.fasterChangeStake = setTimeout ( ( ) = > { this.stakeChangeTimeout = this.FAST_STAKE_CHANGE_TIMEOUT ; } , 2000 ) ; clearTimeout ( this.increaseStakeLimits ) ; clearTimeout ( this.decreaseStakeLimits ) ; clearTimeout ( this.timer ) ; con...
Recursive ` setTimeout ` does n't engage in expected way
JS
So I 'm messing around with trianglify.js.My aim here is that when the mouse moves my trianglfied canvas ' variance will change.In theory fine but in practice it 's not really taken I have tried a few different code formats but just ca n't actually seem to get trianglify to respect the new value.So hopefully , someone ...
//Do Traingle Canvaswindow.onload = function ( ) { var pattern = Trianglify ( { width : window.innerWidth , height : window.innerHeight , cell_size : 120 , stroke_width : 1.3 , variance : 0.75 , seed : '9rqsn ' , x_colors : 'Blues ' } ) ; var homecan = document.getElementById ( 'home ' ) ; homecan.appendChild ( pattern...
Change variance on mouse movement
JS
I 'm trying to wrap a function from a node package with wrapAsync . The stat function is below . Everything seem to work fine ... the request call responds with the correct result , the final callback is called , the whole thing executes synchronously / yields correctly as far as I can tell ... but the sync call never ...
filepicker = new Filepicker ( 'API Key ' ) filepickerStatSync = Meteor.wrapAsync ( filepicker.stat , filepicker ) result = filepickerStatSync ( url ) ; console.log ( 'after ' ) Filepicker.prototype.stat = function ( url , options , callback ) { callback = callback || function ( ) { } ; if ( ! options ) { options = { } ...
Meteor wrapAsync executes synchronously but never returns
JS
I 've got what may be a stupid question . In the code below , the function doStuff appears to reassign myArray to an empty array , but when tried it in the console , myArray is still [ 2,3,4,5 ] . Further , a function that modifies the array seems to work fine . For example : Could someone please help me understand wha...
var myArray = [ 2 , 3 , 4 , 5 ] ; function doStuff ( arr ) { arr = [ ] ; } ; doStuff ( myArray ) ; console.log ( myArray ) // = > [ 2,3,4,5 ] function changeSecondIndex ( arr ) { arr [ 2 ] = 25 ; } changeSecondIndex ( myArray ) console.log ( myArray ) // = > [ 2,3,25,5 ]
Referencing Arrays in Javascript
JS
I just wrote this piece of code to represent this error that is killing me ( Grrr ! ) I wonder why when I get error : method undefined I have checked in Safari and this variable inside parserDidStart ( ) method is not of type EpisodeController it is of type EpisodeFeedParser why is this ?
< html > < head > < script type= '' text/javascript '' > var EpisodeFeedParser = function ( url ) { this.url = url ; this.didStartCallback = null ; } ; EpisodeFeedParser.prototype.parse = function ( doc ) { this.didStartCallback ( this ) ; } ; var EpisodeController = function ( ) { this.episodes = new Array ( ) ; this....
Why *this* is not *this* ?
JS
I 'm writing a form with 4 < select > elements . They all have the same options and I would like to disable , hide , or remove the selected option from one < select > in the other < select > elements with the same options in order to prevent the user to select the same option in multiple < select > elements.No jQuery ,...
< select class= '' custom-select mb-3 '' id= '' name_typage_0 '' > < option class= '' select-items '' selected > Sélectionnez.. < /option > < option class= '' select-items '' value= '' designation '' > Désignation < /option > < option class= '' select-items '' value= '' email '' > Email < /option > < option class= '' s...
How do I disable , hide , or remove selected option in other selects with the same options ?
JS
I 'm making a game with socket.io and nodejs , and I 'm making a module called rooms.js , this module require users.js module and fiveSocket.js modulebut when I call Rooms.New from the main server file , it says that fiveSocket is undefined , same problem when Rooms.New calls a users.js function , I got TypeError : Can...
var mysql = require ( '../mysql/mysql.js ' ) ; var headers = require ( './headers.js ' ) ; var users = require ( './users.js ' ) ; var fiveSocket = require ( './sockets.js ' ) ; var Rooms = { Obj : { } , Room : function ( data ) { var room = this ; this.name = data.name ; this.users = [ ] ; this.floorCode = data.floor ...
NodeJS some modules not working
JS
I 'm asking this more out of curiosity rather than really being concerned with it , but I 've been wondering whether or not the JavaScript event system violates the Liskov substitution principle ( LSP ) or not.By calling EventTarget.dispatchEvent , we may dispatch an Event of an arbitrary type that might get handled by...
interface EventListener { void handleEvent ( in Event evt ) ; } interface EventListener { bool handleEvent ( in Event evt ) ; //returns wheter or not the event could be handled }
Does the JavaScript event system violates the LSP ?
JS
I saw the code below that someone posted . I ’ m confused about what it logs . It logs the function a , not 200 . Why ?
var a = 1 ; ( function a ( ) { a = 200 ; console.log ( a ) } ) ( )
Why is the named IIFE logged instead of the variable with the same name ?
JS
I 've got a `` text box '' whose contents I want to send to an unordered list when the user mashes the `` Enter '' key : HTMLCSSjQueryWhen I enter something into `` InputUPC '' and mash the key , the value appears in the unordered list , but only for a `` brief second '' then it disappears . The value in `` InputUPC ''...
< input type= '' text '' name= '' InputUPC '' id= '' InputUPC '' / > < ul id= '' CandidateUPCs '' name= '' CandidateUPCs '' class= '' ulUPCs '' > < /ul > .ulUPCs { min-height:160px ; height : auto ! important ; height:160px ; max-width:344px ; width : auto ! important ; width:344px ; border-style : solid ; border-width...
Why is the val I 'm adding to an unordered list vanishing right after I add it ?
JS
I have this custom stringify function which can handle circular references : but if I use it to stringify an event object : v is just string that looks like this : so bizarre . I tried a few other custom stringifying helper functions , and they all give me the same result.I looked at this thread : How to stringify even...
const customStringify = function ( v ) { return JSON.stringify ( v , function ( k , v ) { if ( v instanceof Node ) { return 'Node ' ; } if ( v instanceof Window ) { return 'Window ' ; } return v ; } ) ; } ; window.addEventListener ( 'click ' , function ( ev ) { // MouseEvent const v = customStringify ( ev ) ; // { `` i...
Stringifying event object works , but is practically empty
JS
I 'm hoping this does n't get marked as `` duplicate '' , because I have reviewed several threads and followed the advice I found . I know I 'm missing something simple , and need other eyes on this . I 'm a newbie , so please bear with me . I am testing a simple button element that I have a click event handler on , bu...
< div > < button id='handler ' > Event < /button > < /div > < div id='stringText ' > < h4 > Some Description < /h4 > < p > Some more information < /p > < /div > < script > document.getElementById ( `` handler '' ) .addEventListener ( `` click '' , display , true ) ; function display ( ) { if ( document.getElementById (...
Problems with javascript event handler
JS
Is there a way to get all javascript associated with an html element by class name returned in an array ? Any suggestion as to how one would achieve doing this ? Are there any node packages that would allow me to do something like this ? For example : HTMLJSI would want something like ( psuedo-code either on the client...
< div class= '' click_me '' > Click Me < /div > $ ( '.click_me ' ) .on ( 'click ' , function ( ) { alert ( 'hi ' ) } ) ; function meta ( ) { let js = [ ] ; js = getAllJavascriptByClassName ( 'click_me ' ) ; console.log ( js [ 0 ] ) ; } $ ( '.click_me ' ) .on ( 'click ' , function ( ) { alert ( 'hi ' ) } ) ;
How to get all related javascript to an html element
JS
I am writing some code that loops over a CSV and creates a JSON file based on the CSV . Included in the JSON is an array named photos , which is to contain the returned urls for the images that are being uploaded to Google Cloud Storage within the function . However , having the promise wait for the uploads to finish h...
const csv=require ( 'csvtojson ' ) const fs = require ( 'fs ' ) ; const { Storage } = require ( ' @ google-cloud/storage ' ) ; var serviceAccount = require ( `` ./my-firebase-storage-spot.json '' ) ; const testFolder = './Images/ ' ; var csvFilePath = './Inventory.csv ' ; var dirArr = [ './Images/Subdirectory-A ' , './...
Promise Resolving before Google Cloud Bucket Upload
JS
If I have an element on a web page that I expect to be showing and hiding quite a bit using javascript , which would be the most appropriate way to set it as initially invisible ? orUsing class= '' ... '' is preferable to style= '' ... '' in most cases , but I 'm not convinced it 's the best fit in this case . Semantic...
< div class= '' hidden '' > ... < /div > < div style= '' display : none ; '' > ... < /div > < div class= '' hidden '' style= '' display : block ; '' > ... < /div >
I expect to toggle an element 's visibility : should I start with class= '' ... '' or style= '' ... '' ?
JS
I have a custom loader that load the following file data.jswhen I change the above file like changing b value the app breaksthis is the custom webpack loader Here is a reproduction repo
const data = { a : ( ) = > 8885555 , b : ( ) = > 55555 } module.exports = name = > { return data [ name ] & & data [ name ] ( ) } ERROR in ../data.js ? name=aModule build failed : Error : Final loader ( ../data-loader.js ) did n't return a Buffer or String at runLoaders ( C : \Users\010\Saber.js\webpack-hmr-3-ways\midd...
Hot reloading breaks the app . Final loader did n't return a Buffer or String
JS
I am trying to develop a web-ar experience that allows the user to switch between front and back cameras throughout the experience , while utilizing SLAM/6dof while using the back camera . Ideally I 'd like to use PlayCanvas , but was unable to get the front camera to work . I have had some mild success implementing th...
init : function ( ) { this.el.sceneEl.addEventListener ( 'stopxr ' , event = > { console.log ( `` AR has been stopped . `` ) ; const videoCanvas = document.querySelector ( 'canvas.a-canvas ' ) ; XR.XrController.configure ( { disableWorldTracking : true } ) ; XR.run ( { canvas : videoCanvas , cameraConfig : { direction ...
Is there a way to switch between front and back cameras mid application
JS
I 'm wondering if it 's possible to have a setter for a dynamic property in Javascript ? So this : Would call a function being able to retrieve 'a_custom_prop ' and 'something'To be clear , I would like a function similar to : to be called like this : instead of : Knowing that the name of the property is not static rel...
var myobj = new MyObj ( ) ; myobj.a_custom_prop = 'something ' ; MyObj.property.define = function ( prop , value ) { } ; myobj.prop = value ; myobj.define ( 'prop ' , value ) ; Object.defineProperty ( MyObj.prototype , 'a_custom_prop ' , { set : function ( value ) { /* ... */ } } ) ;
Setter for a dynamic property in javascript
JS
I have a simple dojo treeGrid that is categorized just by first column . But how to make it categorized/collapsible by second as well ? Note the treeGrid has totals shown in each category . Also , is there a way to move totals to the category level but not to the bottom ? sample JSON store :
var layout = [ { cells : [ [ { field : `` year '' , name : `` Year '' } , { field : `` childItems '' , children : [ { field : `` unid '' , name : `` unid '' , hidden : true } , { field : `` geography '' , name : `` Geography '' } , { field : `` country '' , name : `` Coungtry '' } , { field : `` status '' , name : `` S...
How to make dojo treeGrid categorized by two columns ?
JS
I 've often used the following pattern in my Javascript : because it beats than : I also frequently use a slight variant of that same pattern : That 's all great ... except the problem is , I recently discovered : In other words , if you have a string , and you do string.aPropertyThatStringDoesntHave || foo , you 'll g...
x = couldBeNullThing || valueIfItIsNull ; x = couldBeNullThing ? couldBeNullThing : valueIfItIsNull ; x = x || valueIfXIsNotDefined ; foo = `` '' ; //assert foo.x === undefined ; foo.x = foo.x || valueIfXIsNotDefined ; //assert foo.x === undefined ;
Javascript Undefined String Property Truthiness
JS
Why is this happening ? But Array.prototype.map.call ( numbers , parseInt ) ; returns [ 1 , 2 , 3 , 4 ] ; . I 'm running this code in Google Chrome 26.0.1410.65 .
var numbers = [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ] ; var intNumbers = numbers.map ( parseInt ) ; // intNumbers = [ 1 , NaN , NaN , NaN ] var fltNumbers = numbers.map ( parseFloat ) ; // fltNumbers = [ 1 , 2 , 3 , 4 , 5 ]
parseInt misbehaves when passed as argument to a map call
JS
As title states , I am trying to animate a square div into a trapezoid using jquery .animate ( ) . However , the only animation I am getting is the width adjustment and I am not quite sure why this is occuring .
$ ( function ( ) { $ ( '.square ' ) .hover ( function ( ) { $ ( this ) .animate ( { borderRight : '100px solid red ' , borderTop : '50px solid transparent ' , borderBottom : '50px solid transparent ' , height : '100px ' , width : ' 0 ' } ) ; } ) ; } ) ; div.square { height : 100px ; width : 100px ; background-color : r...
Animate square div into trapezoid
JS
I want to separate my JavaScript function documentation into TypeScript .d.ts files.For example : Similarly how Material UI does this . https : //github.com/mui-org/material-ui/tree/master/packages/material-ui/src/ButtonMy issue is that TypeScript & VSCode does not recognize the .d.ts file for the current JavaScript fi...
components/ Button/ Button.jsx # JavaScript component Button.d.ts # TypeScript documentation with prop types interface Props { text : string onClick : ( ) = > void } declare const Button : ( props : Props ) = > Elementexport default Button import React from 'react'const Button = ( { text , onClick } ) = > { return < bu...
How to use TypeScript declaration files alongside JavaScript
JS
i have this code : However , when i click in bold button , or italic , even with right click in top bar with the formatting options , the ajax request is reloaded . So the dojo editor is loaded when i press the formatting toolbar Any idea ? demo here
< ! DOCTYPE HTML > < html > < head > < script src= '' http : //ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js '' type= '' text/javascript '' djConfig= '' parseOnLoad : true '' > < /script > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js '' > < /scri...
click handler with dojo editor
JS
I want to create timer in JavaScript , I will setup 10 secs and have user to click on images and display the counts when time stopped.How can i achieve this task ? index.htmlindex.js
< div class= '' container '' > < div class= '' row '' > < div class= '' col-md-2 '' > < img src= '' https : //images.omkt.co/Files/402/15EAC0/19F78/8c2112737cfe4cd88779712a4906ef6d/0/hero_forte_2014 -- kia-1920x.png '' height= '' 150px '' width= '' 150px '' id= '' clicks '' onClick= '' clickMe ( ) '' > < /div > < div c...
How to create timer in javascript and count the clicks in specified time ?
JS
The following behaves differently between jQuery 1.9 and 1.10+ : The idea behind this code is to select the first option.After 1.10 , the $ ( ' # s1 ' ) .val ( `` ) ; part is no longer working in the same way . I suppose that it was never meant to be used that way but its old code and have to be modernized in some way ...
< select id= '' s1 '' > < option value= '' 1 '' > 1 < /option > < option value= '' 2 '' > 2 < /option > < option value= '' 3 '' > 3 < /option > < /select > $ ( ' # s1 option [ value=1 ] ' ) .hide ( ) ; $ ( ' # s1 ' ) .val ( `` ) ; $ ( ' # s1 option [ value=1 ] ' ) .hide ( ) ; $ ( ' # s1 ' ) .val ( $ ( ' # s1 option ' )...
jQuery select box .val ( `` ) behavior differs from 1.9 to 1.10+ what is the shortest way to do that
JS
In a Json , there are multiple image sources as `` src '' : `` image.png '' , , `` src '' : `` image2.png '' , For image.png , right now i am fetching X value as `` 40 '' [ 3rd position in below image ] For image2.png , right now i am fetching X value as `` 100 '' [ 6th position in below image ] Requirement : Instead o...
let jsonData = { `` layers '' : [ { `` x '' : 10 , `` layers '' : [ { `` x '' : 20 , `` y '' : 30 , `` name '' : `` L2a '' } , { `` x '' : 40 , `` layers '' : [ { `` x '' : 50 , `` src '' : `` image.png '' , `` y '' : 60 , `` name '' : `` L2b-1 '' } , { `` x '' : 70 , `` y '' : 80 , `` name '' : `` L2b-2 '' } ] , `` y ...
Add the X values in Json with respect to Image
JS
I have written the following recursive input validator and it works for me . Is there a better way to visit each dom element and check if it is an input field and validate it ?
function formValidator ( parent ) { //base case no children if ( parent.children ( ) .length == 0 ) return //recurse through each childs ' child parent.children ( ) .each ( function ( ) { formValidator ( $ ( this ) ) ; /** * Work : check if this node is an input node */ if ( $ ( this ) .is ( `` input '' ) ) { var type ...
Recursively validating HTML input elements
JS
Suppose I have a function Foo , and I want objects constructed from it to have a bar property : Now suppose I bind Foo in some way . Bound functions can still be used in constructor calls , and the bound this is ignored : Proxies are supposed to be general and transparent . However ... I would expect the second proxy t...
function Foo ( ) { } Foo.prototype.bar = 'baz'console.log ( 'new Foo ( ) .bar : ' + new Foo ( ) .bar ) new Foo ( ) .bar : baz const Bound = Foo.bind ( 42 ) console.log ( 'new Bound ( ) .bar : ' + new Bound ( ) .bar ) new Bound ( ) .bar : baz const PFoo = new Proxy ( Foo , { } ) console.log ( 'new PFoo ( ) .bar : ' + ne...
Constructor call to proxy of a bound function
JS
In JavaScript it is possible to do : but with ES6 property shorthand I get SyntaxError : This is not a real use case but I am just wondering what is the difference between these two . I thought it should do the same ( either create a new object or throw an error ) .UPDATE : I run this example in Firefox 42.0 . However ...
var a = { this : this } var b = { this } ; // SyntaxError : this is a reserved identifier
Object Literal Property Value Shorthand incompatible with ` this `
JS
There 's a async call I 'm making that queries a database on a service , but this service has a limit of how many it can output at once , so I need to check if it hit its limit through the result it sends and repeat the query until it doesn't.Synchronous mockup : Obviously the above does not work , I 've seen some othe...
var query_results = [ ] ; var limit_hit = true ; # While this is true means that the query hit the record limitvar start_from = 0 ; # Pagination parameterwhile ( limit_hit ) { Server.Query ( params= { start_from : start_from } , callback=function ( result ) { limit_hit = result.limit_hit ; start_from = result.results.l...
Call hierarchy of async functions inside a loop ?
JS
I 'm newbie in React and I have some issue to display dynamic unicode value ?
{ '\u { 1F680 } ' } become { '\u { MyVar } ' }
Concatenate unicode and variable
JS
In my project there could be any amount of divs like a thousand , two thousand , a million etc.. I want their background colors to go from green to red . so they all get a different shade of color . the first div will be `` real '' green the last div will be `` real '' red.Here is what I have . As you can see there are...
$ ( function ( ) { var r = 20 ; var g = 200 ; var b = 10 ; for ( var i = 0 ; i < 300 ; i++ ) { $ ( `` body '' ) .append ( `` < div class = 'box ' > '' ) ; } $ ( `` .box '' ) .each ( function ( ) { if ( g > 0 & & r < 255 ) { $ ( this ) .css ( `` background '' , `` rgb ( `` + r + `` , '' + g + `` , '' + b + `` ) '' ) ; g...
Set the color of many divs from green to red