lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | On a Desktop browser , I can use the following javascript to vertically fix an element , but still allow for horizontal scroll . As you see , it re-positions the element on every scroll event . To see what I mean , try horizontally and vertically scrolling in this JSFiddle.However , this logic fails for mobile browsers... | var verticallyFixedBox = document.getElementById ( 'verticallyFixedBox ' ) ; window.addEventListener ( 'scroll ' , function ( ) { verticallyFixedBox.style.top = `` + document.body.scrollTop + 'px ' ; } ) ; | How do I vertically fix an element in a mobile browser but still allow for horizontal scroll ? |
JS | In Javascript I have a function that should find the elements on the page that have the `` connected '' class , and when a button is clicked the classes for these elements are cleared . I have written this code : However , it only ever deletes the class attribute of the first `` connected '' element on the page . When ... | var prev_connected = document.getElementsByClassName ( `` connected '' ) ; if ( prev_connected.length > 0 ) { for ( var j = 0 ; j < prev_connected.length ; j++ ) { prev_connected [ j ] .removeAttribute ( `` class '' ) ; } } | For loop only iterates once when trying to remove classes from elements |
JS | I 'm trying to get the userid , and the array object that contains the specific location within locations.What I want to accomplish is the following : The query will return the array location 's result.If not userid exist at all , create it , then return the array of the matching location.If the location id Number is n... | easyCrime.findOne ( { userid : userid , `` locations.location '' : location } , { `` locations. $ .location '' : 1 } ) .then ( function ( err , stats ) { } } ) ; userid : { type : String , default : '57c1c0f3b6b20c011242bf22 ' } , locations : [ { userid : { type : String , default : '57c1c0f3b6b20c011242bf22 ' } , loca... | Mongoose find and create multidimensional arrays |
JS | I 'm trying to write a script that prints the names of the previous 12 months . Since this month is January , it should print : DecemberNovemberOctoberSeptemberAugustJulyJuneMayAprilMarchFebruaryJanuaryInstead , it prints March twice . http : //jsfiddle.net/h69gm04g/2/NovemberOctoberSeptemberAugustJulyJuneMayAprilMarch... | < div id= '' test '' > < /div > monthNames = [ `` January '' , `` February '' , `` March '' , `` April '' , `` May '' , `` June '' , '' July '' , `` August '' , `` September '' , `` October '' , `` November '' , `` December '' ] ; d = new Date ( ) ; for ( i = 0 ; i < 12 ; i++ ) { d.setMonth ( d.getMonth ( ) - 1 ) ; mon... | JavaScript : Print previous 12 months -- `` March '' prints twice ? |
JS | For a given reducer , my redux state tree typically looks something like this : Typically , when I do an async request , I fire a SOME_ACTION_REQUEST action , which sets the metadata.pending property to true . It 's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later... | { someField : 'some value ' , // ... more fields metadata : { pending : false , fetched : true , } } case actions.SOME_ACTION_REQUEST : { return { ... state , metadata : { ... state.metadata , pending : true } , } ; } | How to update redux state further down the tree |
JS | As many as Articles as i 've read , I still have some questions.I already know ( and understand ) the usages of closure like : The Infamous Loop Problem ( loop of links with alert on each one of them with kept number ) increased counter ( keep calling a function - > which alerts increased numbers ) From here : inner fu... | function functionMaker ( ) { var x = 1 ; function innerFunction ( ) { alert ( x ) ; x++ ; } return innerFunction ; } ( function ( a ) { alert ( a ) ; } ) ( 4 ) ; function myFunction ( ) { var myVar = 1 ; var alertMyVar = function ( ) { alert ( 'My variable has the value ' + myVar ) ; } ; setTimeout ( alertMyVar , 1000 ... | Javascript Closure Clarification ? |
JS | I have this deeply nested array with group of node which i want to create query string something likeThe json data i have is , list of nodes to receive user inputoperator to handle multiple node joiningif user selects to NOT , the main container which contains it will not have the nodes so it will look like this NOT ( ... | ( FULL_NAME= '' x '' AND NOT ( AGE= '' 30 '' OR AGE= '' 40 '' AND ( ADDRESS= '' y '' AND STREET= '' z '' AND NOT ( USER= '' admin '' OR USER= '' super admin '' ) ) ) AND TITLE= '' Developer '' ) [ { `` uuid '' : '' b7f0ddf4-0290-4c7e-bb59-771aa46bc850 '' , `` operator '' : '' AND '' , `` isMain '' : true , `` nodes '' ... | Create string out of multi dimensional children array with group nodes |
JS | Looking at this piece of code : I have n't actually seen a loop like this before and I want to be sure I understand it correctly.Am I correct in assuming that if families.length == 2 that the 2nd part of the for line would return false on f = families [ 2 ] ? I would have thought it would need to be something like f ==... | for ( var i = 0 , f ; f = families [ i ] ; i++ ) { } | Javascript for loop with object instead of counter ? |
JS | There are a couple of ways I could do this ( That I 'm aware of ) .Test css displayTest the visibilityIn the visibility I can check if the element is there . Elements are considered visible if they consume space in the document . Visible elements have a width or height that is greater than zero . Elements with visibili... | if ( $ ( ' # foo ' ) .css ( 'display ' ) == 'none ' ) if ( $ ( ' # foo ' ) .is ( ' : visible ' ) ) if ( $ ( ' # foo ' ) .is ( ' : visible ' ) & & $ ( ' # foo ' ) .css ( 'opacity ' ) > 0 & & $ ( ' # foo ' ) .css ( 'visibility ' ) ! = 'hidden ' ) | What 's the best way to test an element in the DOM |
JS | I think I have finally managed to bend my mind around javascript/ES6 Promises , for the most part . It was n't easy ! But there 's something that 's baffling me about the design.Why does the Promise constructor take a callback ? Given that the callback is called immediately , could n't the caller just execute that code... | function get ( url ) { return new Promise ( function ( resolve , reject ) { var req = new XMLHttpRequest ( ) ; req.open ( 'GET ' , url ) ; req.onload = function ( ) { if ( req.status == 200 ) { resolve ( req.response ) ; } else { reject ( Error ( req.statusText ) ) ; } } ; req.onerror = function ( ) { reject ( Error ( ... | Is javascript Promise API more convoluted than it needs to be ? |
JS | I 'm fairly new to Node , and I 'm trying to connect to a Clover Mini device through a websocket using the API provided by Clover.I 've tried modifying the example code below to work using only node , but when I open it in node nothing happens . ( No errors , just nothing happens at all ) It works in Chrome just fine ,... | var $ = require ( 'jQuery ' ) ; var clover = require ( `` remote-pay-cloud '' ) ; var log = clover.Logger.create ( ) ; var connector = new clover.CloverConnectorFactory ( ) .createICloverConnector ( { `` oauthToken '' : `` 1e7a9007-141a-293d-f41d-f603f0842139 '' , `` merchantId '' : `` BBFF8NBCXEMDV '' , `` clientId ''... | How do I connect to a Clover mini device using ONLY node ? |
JS | I basically have the following validation on my page - its a word rule in that a description in a text box can not be greater than 3 words excluding the word 'and ' . I have implemented the following server side validation in C # which is working fineHowever I am having difficulty getting the same working in Javascript... | if ( Desc.Trim ( ) .ToString ( ) ! = `` '' ) { MatchCollection collection = Regex.Matches ( Desc.Replace ( `` and '' , `` '' ) , @ '' [ \S ] + '' ) ; if ( collection.Count > 3 ) { ErrorMsg.Append ( `` Description should contain at most 3 words ( excluding 'and ' ) . `` ) ; ErrorMsg.Append ( `` \\n '' ) ; } } if ( Desc.... | Replicate C # Server Side Validation in Javascript |
JS | Possible Duplicate : Javascript : var functionName = function ( ) { } vs function functionName ( ) { } What is the reason you would do : In stead of doing : | somename = function ( param1 , param2 ) { } function somename ( param1 , param2 ) { } | Javascript function declaration . When to use what ? |
JS | I 'm on my way to learn a bit of CSS and today I 've found myself wanting to implement a similar context menu ( the one it 's shown when you the vertical elipsis on youtube cards is clicked ) but my attempt did n't make it very far : D . Here 's what I 've got : As you can see the code is dirty and broken ... but there... | < ! DOCTYPE html > < html > < head > < style type= '' text/css '' > .container { display : inline-block ; position : relative ; } .dropdown { position : absolute ; right : 1rem ; top : 1rem ; } .dropdown-opener { cursor : pointer ; user-select : none ; position : absolute ; right : 0 ; } .dropdown .dropdown-toggle , .d... | How to implement context menus similarly to youtube cards ? |
JS | I want to make `` animation '' of my Rect more smooth . Currently it 's really clunky . I know the reason for it . One of the coordinates becomes wanted value before the other.For example if I 'm currently at ( 0,0 ) and I need to go to ( 150,75 ) and I increment each one equally every second , y-cord will come much so... | var canvas = document.getElementById ( 'canvas ' ) ; var ctx = document.getElementById ( 'canvas ' ) .getContext ( '2d ' ) ; var aniTimer ; var x ; var y ; var tx = tx || 0 ; var ty = ty || 0 ; var xDir ; var yDir ; function followMouse ( e ) { x = e.offsetX ; y = e.offsetY ; cancelAnimationFrame ( aniTimer ) ; moveObj... | Make moving Rect more smooth |
JS | I have created in my code an ArrowHelper and I update its parameters by calling the function below ( each call of this function updates the ArrowHelper dimensions ) : I would like to make disappear the head of ArrowHelper if its length ( given by transportedVector.coordLocal.length ( ) ) is zero , what I have done with... | function updateArrowHelper ( ) { // Update parameters for transportedVector transportedVector.arrowHelper.setLength ( transportedVector.coordLocal.length ( ) , headLengthVector , headWidthVector ) ; transportedVector.arrowHelper.setDirection ( directionVector.normalize ( ) ) ; transportedVector.arrowHelper.position.cop... | Three.js - Remove the head of an ArrowHelper |
JS | I wrote a simple extension method.987654321.toMillion ( ) raises : SyntaxError : Unexpected token ILLEGALBut ( 987654321 ) .toMillion ( ) works.So my question is : what 's the difference between 987 and ( 987 ) ? Just FYI : And | Number.prototype.toMillion = function ( ) { if ( ! Number.isNaN ) { return this/1000000 ; } } typeof ( 987 ) = > returns `` number '' typeof ( ( 987 ) ) still returns `` number '' | What 's the difference between 987 and ( 987 ) in JavaScript ? |
JS | I have a bug that I do n't understand is if I 'm doing something wrong with Golang or if I 'm doing something wrong with javascript fetch ( ) statement . It 's a simple situation where I want to make fetch ( ) call to a golang endpoint and simply print hello world . But for some reason , the golang code is firing twice... | // main.gopackage mainimport ( `` route/page '' `` github.com/gorilla/mux '' `` log '' `` net/http '' ) func main ( ) { router : = mux.NewRouter ( ) router.HandleFunc ( `` /page '' , page.Search ) .Methods ( `` GET '' , '' OPTIONS '' ) log.Fatal ( http.ListenAndServe ( `` :8000 '' , router ) ) } //route/page.gopackage ... | Javascript fetch ( ) is pinging my golang rest end point more than once ? |
JS | How do I make this javascript alert 0 , 1 and 2 instead of 3 3 's ? I know the reason why it does this , but I ca n't figure out , how to pass i to the anonymous function . | var vals = [ 1 , 2 , 3 ] ; for ( var i = 0 ; i < vals.length ; i++ ) { window.setTimeout ( function ( ) { alert ( i ) ; } , 1000 ) ; } | How to make anonymous functions with local parameters |
JS | At least in V8 something likewill give an error about an unexpected 'var ' keyword . However there is no error if the var happens before the if ( ) but I still leave the assignment of i in the expression . Why such an odd exception ? Is this in the ECMA script standard somewhere ? Is there a undetectable closure happen... | if ( ( var i = x*x ) == 2 ) { } | Why is it illegal to have var inside an if ( ) expression in javascript ? |
JS | I 've always thought that browsers execute JavaScript code from top to bottom string by string ( you kinda expect this behavior from a scripting language ) . But clearly it 's not the case here : //works perfectbut if I declare function as a variable it fails with 'Uncaught ReferenceError : test is not defined ' : So t... | < script > test ( ) ; function test ( ) { alert ( 'test ' ) ; } < /script > < script > test ( ) ; var test = function ( ) { alert ( 'test ' ) ; } < /script > | How exactly is JavaScript interpreted ? |
JS | Is there any difference if I do : versusDo they do the same thing ? What are the differences and which should I use ? It 's weird cause the jQuery docs does not really mention .next ( ) , they always say to use .dequeue ( ) but at my workplace people use the .next ( ) function so this has got me rather confused . | $ queue.queue ( function ( next ) { // ... next ( ) ; } ) .queue ( function ( next ) { // ... next ( ) ; } ) ; $ queue.queue ( function ( ) { // ... $ ( this ) .dequeue ( ) ; } ) .queue ( function ( ) { // ... $ ( this ) .dequeue ( ) ; } ) ; | How to determine what one to use - next ( ) ; or dequeue ( ) ; ? |
JS | David Flanagan 's excellent book on JavaScript has an example that shows how to perform XPath queries in IE . On page 518 of fifth edition , you can see the following code snippet taken from example 21-10 : I found out the hard way that this code is absolutely necessary . It appears ( although I cant understand why ) t... | // In IE , the context must be an Element not a document , // so if the context is a document , use the documentElement insteadif ( context == doc ) context = doc.documentElement ; return context.selectNodes ( this.xpathText ) ; | Baffled by an XPath issue on IE |
JS | I have built a SPA using Create React App . I have integrated google analytics and using google tag manager ( tag ) for sending events.While analyzing the events I have noticed that my application is only firing landing pageview event ( Only on first-page user visit ) .What I am not able to figure out is even though th... | window.dataLayer = window.dataLayer || [ ] ; function gtag ( ) { dataLayer.push ( arguments ) ; } gtag ( 'js ' , new Date ( ) ) ; gtag ( 'config ' , 'UA-xxxxxxxxxx ' ) ; | Google analytics page per session is more than 1 for SPA |
JS | Why is not every cube in my loop casting a shadow ? I work with a directional light all of the cubes should cast shadows . But for some reason , it stops after 5 or so columns . | let dirLight = new THREE.DirectionalLight ( 0xFFFFFF , 1.5 ) ; dirLight.position.set ( 300 , -300 , 400 ) ; dirLight.castShadow = true ; scene.add ( dirLight ) ; dirLight.shadow.mapSize.width = 512 ; dirLight.shadow.mapSize.height = 512 ; dirLight.shadow.camera.near = 0.5 ; dirLight.shadow.camera.far = 1000 ; let cubeG... | Object in loop wo n't cast shadow over whole lopop with Three.js |
JS | Hello I am new to NodeJs . I was making a website dynamic with the use of EJS and Node . I was trying to make a navigation dropdown which has three levels inside it like below . : -Now I am trying to mimic this and this is what I am getting : -The below is the code which I have tried in the js file : -Main Category is ... | MainCategory.find ( { } , function ( err , mainCategories ) { if ( err ) { console.log ( err ) } else { app.locals.mainCategoriesHeader= mainCategories ; mainCategories.forEach ( function ( mainCategories ) { var MC = mainCategories.slug ; Category.find ( { mainCategory : MC } , function ( err , categories ) { if ( err... | Not able to display all the data across navigation dropdown on hover correctly |
JS | I can set up two routes like thisindex.js./routes/index.js./routes/sub1.jsFor brevity ./routes/sub2.js looks exactly the same , but its variables are named subTwoWhat is the shortest way to nest sub2 under sub1 ? Within index.js I have tried But that did n't work at all . Within index.jsDoes work , but it seems it coul... | var express = require ( 'express ' ) ; var app = express ( ) ; var router = express.Router ( ) ; const PORT = 3001 ; app.get ( '/ ' , function ( req , res ) { res.send ( 'hello app ' ) ; } ) ; app.use ( '/routes ' , require ( './routes ' ) ) ; app.listen ( PORT , function ( ) { console.log ( 'listening on port : ' , PO... | Correct/Concisest way to nest routers with Express |
JS | I am pretty new to the whole object-oriented paradigm.I am trying to model a character in a certain game , you have different levels , classes , and lots of equipment choices and such.My goal in the end would be to create a `` dresser '' of some sort where players could open up the site , try on some equips and see how... | var Lord = function ( ) { this.Level = 1 ; this.Gender = 'Male ' ; this.Faction = 'Knight ' ; this.Attack = 0 ; this.Defense = 1 ; this.SpellPower = 0 ; this.Knowledge = 0 ; this.Luck = 0 ; this.Morale = 1 ; this.Initiative = 0 ; this.addParameter = function ( Parameter , amount ) { this [ Parameter ] += amount ; } ; t... | Trying to model with object-oriented javascript |
JS | I 've been injecting Google DFP ads in my blog-posts by using a bound helper so far . Since all Handlebars APIs have been removed in Ember 2.0 what can I use as of Ember 2.0 instead ? | import Ember from `` ember '' ; export default Ember.Handlebars.makeBoundHelper ( function ( value , options ) { var parsedHtml = Ember. $ ( ' < div / > ' ) .html ( value ) // Push the ads after the divs have been rendered Ember.run.schedule ( 'afterRender ' , function ( ) { googletag.cmd.push ( function ( ) { googleta... | makeBoundHelper alternative in Ember 2.0 |
JS | I have a JavaScript function : Which generates several divs , using this code : The mouse events work fine in all major browsers except IE . It seems that all divs except the last will have the mouse event in lowercase which will have the mouse event exactly as written , with upper case letters.All mouse events will fi... | function addTool ( id , text , tool , pic ) { var container = getById ( 'infobox ' ) ; var origimg = getById ( 'tempimg ' ) .src ; container.innerHTML += `` < div id= ' '' + id + `` ' class='toolText ' > '' + text + `` < br > < img class='toolImg ' src='img/tools/ '' + tool + `` ' > < /div > '' ; getById ( id ) .setAtt... | onmouseover for the last of several generated divs will not work in IE |
JS | What is the easiest was to populate an array with a large number of objects created with a constructor ? I have a constructor function than makes TV and movie objects : I am making many objects that I want to put into an array . This does not work : I also tried putting table.push ( at the beginning of each line . Do I... | function Media ( name , boxCover ) { this.name = name ; this.boxCover = boxCover ; } ; var table = [ var avengers = new Media ( `` avengers '' , '../assets/boxcovers/avengers.jpg ' ) ; var blade_runner = new Media ( `` blade_runner '' , '../assets/boxcovers/blade_runner.jpg ' ) ; var brave = new Media ( `` brave '' , '... | Javascript : best way to instantiate an array of objects |
JS | I 've seen a lot of idioms , most of them clever and logical once explained . But while I was looking over SO 's javascript to get some ideas about good interface design I saw the following line : Which really threw me for a loop . Obviously , they initialize the tag renderer with two arrays containing exactly one null... | initTagRenderer ( `` '' .split ( `` `` ) , `` '' .split ( `` `` ) ) ; | `` `` .split ( `` `` ) in SO 's javascript |
JS | I 'm trying to understand JavaScript 's ( or at least V8 's ) behaviour regarding constructor functions.I know , JavaScript constructor functions should never return anything ( so : undefined ) .But consider this JavaScript : Now , if you do this : And even : So , why does a constructor function in JavaScript return an... | function Thing ( ) { return `` ; } var t = new Thing ( ) ; console.log ( t , typeof t ) ; // = > Thing { } `` object '' function Thing ( ) { return { hi : `` } ; } var t = new Thing ( ) ; console.log ( t , typeof t ) ; // = > Object { hi : `` '' } `` object '' function Thing ( ) { this.a = ' a ' ; return { hi : `` } ; ... | Why do constructor functions return objects , but not primitives in JavaScript ? |
JS | I have a array , let 's say : What is the fast way to check if my String has any of the words in myArray ? Bellow is my code , but im not sure if it would be the best way to go ... Please help me anyone . That function will run in A LOT of strings ! Thank you all : ) | var myArray = [ `` ibira '' , `` garmin '' , `` hide '' , `` park '' , `` parque '' , `` corrida '' , `` trote '' , `` personal '' , `` sports '' , `` esportes '' , `` health '' , `` saúde '' , `` academia '' ] ; var myString = `` I went to the park with my garmin watch '' ; function score ( arKeywords , frase ) { if (... | fastest way to compare a string with a array of strings |
JS | I 'll try to clarify what I mean as quickly as possible . As you can see , the parsing fails at position 0 for the string `` ce '' and at position 1 for the string `` te '' . This means that the parser believes that there is some legal JSON that starts with the character `` t '' . Does anybody know what that would be ?... | JSON.parse ( `` te '' ) VM297:1 Uncaught SyntaxError : Unexpected token e in JSON at position 1 at JSON.parse ( < anonymous > ) at < anonymous > :1:6JSON.parse ( `` ce '' ) VM342:1 Uncaught SyntaxError : Unexpected token c in JSON at position 0 at JSON.parse ( < anonymous > ) at < anonymous > :1:6 | Why does JSON parsing not fail on the first character for strings starting with `` t '' ? |
JS | I have recently started using typescript and reviewing some of my favorite repos , I have seen people use back ticks for template string in console.log . This seems odd to me , but I am pretty inexperienced overall with canonical javascript . To me , console.log already provides the mechanism for formatting by putting ... | // set list of itemsfunction printMyItems ( item1 , item2 ) { // What I have been doing console.log ( item1 , item2 ) ; // What I have seen console.log ( ` $ { item1 } $ { item2 } ` ) ; } // Also variadic arguments seem to work better with the former approach.function printMyItems ( ... args ) { // What I have been doi... | What is more Canonical javascript , console.log |
JS | I would never think this is possible , but there are a lot of clever people here so I thought I 'd ask . I 'm looking for a way to have a full-height container whose width depends on how much content there is . I want the text to fill the area taking up the full height while using the smallest possible width . The heig... | < div > < p > Lorem Ipsum is simply dummy text of the printing and typesetting industry . Lorem Ipsum has been the industry 's standard dummy text ever since the 1500s , when an unknown printer took a galley of type and scrambled ... . < /p > < /div > div { background : red url ( http : //lorempixel.com/600/400/ ) ; fl... | Full height content with the smallest possible width |
JS | ECMA script documentation says in abstract equality comparison alogorithm that , If Type ( y ) is Boolean , return the result of the comparison x == ToNumber ( y ) .So for instance , [ ] == false will be coerced like , My question is , the coercion will be happened recursively until the two operands becomes primitive o... | 1 . [ ] == Number ( false ) 2 . [ ] == 0 //comparison happens here . 1 . [ ] == Number ( false ) 2 . [ ] == 03 . ToPrimitive ( [ ] ) == 04 . 0 == 0 5. true | How type coercion happens when [ ] == false ? |
JS | I have a problem . I made a loop with buttons in HTML . So now I want them to change the color when I press the button . But I have the problem that they all change the color . But I only want to change the color of the button that was pressed.HTMLTS | < ion-item *ngFor= '' let friend of friendsList '' > < ion-avatar item-start > < img src= { { friend.img } } > < /ion-avatar > < button ion-button color= '' rank '' class= '' avat '' > < /button > < h2 > { { friend.name } } < /h2 > < p > { { friend.status } } < /p > < button ( click ) = '' toggleNamedColor ( ) '' ion-b... | How to change the color of only one button ? |
JS | Why does this javascript line looks like this ? I mean , why there 's an extra + near the end ? Source : http : //code.google.com/p/closure-library/source/browse/trunk/closure/goog/base.js # 511 | ' < script type= '' text/javascript '' src= '' ' + src + ' '' > < / ' + 'script > ' | Why does this line of Google closure look like it looks ? |
JS | We 've all seen people who do this : and so on . I was wondering what people have seen the most common JavaScript/jQuery technique that is slowing down the page and/or wasting time for the JavaScript engine.I know that this question may not seem to fit into what 's an accepted question , yet I 'm asking `` what is the ... | jQuery ( ' a ' ) .each ( function ( ) { jQuery ( this ) [ 0 ] .innerHTML += ' proccessed ' ; } ) ; function letsPoluteNS ( ) { polute = `` ; for ( morePolution = 0 ; morePolution < arguments.length ; morePolution++ ) polute.join ( arguments [ morePolution ] ) ; return polute ; } | What is the most common waste of computing power in Javascript ? |
JS | Below is my js code that is appending the route and its parameter in anchor tag.It gives below urlhttp : //localhost:1234/public/system-users/ % 20+ % 20row.RoleID % 20+ % 20I am expecting below . http : //localhost:1234/public/system-users/1Am I missing anything ? | var href = `` { ! ! route ( 'ShowUserMainForm ' , [ 'RoleID'= > '' + row.RoleID + `` ] ) ! ! } '' ; var UserColumn = `` < td > < a href= ' `` + href + `` ' > < button > Users < /button > < /a > < /td > '' ; | Issue while trying to append route parameter in js |
JS | I have this Rational class that has a method for each operation ( add , mult etc ) Can I make it more `` natural '' e.g . to enable console.log ( a * b ) ? | function Rational ( nominator , denominator ) { this.nominator = nominator ; this.denominator = denominator || 1 ; } Rational.prototype = { mult : function ( that ) { return new Rational ( this.nominator * that.nominator , this.denominator * that.denominator ) ; } , print : function ( ) { return this.nominator + '/ ' +... | Enable a Rational class to handle math operators |
JS | i have the following index.html : the console outputs : < div id= '' foo '' > i 'm a div < /div > why ? | < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < title > < /title > < script src= '' http : //code.jquery.com/jquery-latest.min.js '' type= '' text/javascript '' > < /script > < script type= '' text/javascript '' > jQuery ( document ) .ready ( function ( $ ) { console.log ( foo ) ; // jQuery assumes... | jquery assumes element id ? normal behaviour ? |
JS | In Internet Explorer 10 , this : evaluates to [ 'def ' ] , as I 'd expect , but in Firefox 21.0 , it evaluates to [ 'abcdefghi ' ] . ( See this jsFiddle . ) I get the same sort of unexpected behavior for certain other regexes that both begin and end with optional content , such as /. ? e . { 0,2 } / and /. { 0,2 } e . ... | 'abcdefghi'.match ( /. ? e . ? / ) | /. ? e . ? / matches entire string , rather than expected substring |
JS | I can create a class that does not inherit from Object.prototype using the older syntax.How can I do this using ES6 classes ? | function Shape ( x , y , width , height ) { this.x = x , this.y = y , this.width = width , this.height = height ; } Shape.prototype = Object.create ( null , { constructor : { configurable : true , writable : true , value : Shape } , move : { configurable : true , writable : true , value : function ( x , y ) { this.x +=... | How do you create a class that does not inherit from Object.prototype using ES6 classes ? |
JS | I know how to pass some parameters to a JQuery $ .getJSON callback method , thanks to this question : And I can also submit a form to a $ .getJSON callback method : But I want to pass some parameters AND submit some form elements . How can I combine the two things togheter ? I could serialize the form elements and manu... | $ .getJSON ( '/website/json ' , { action : `` read '' , record : `` 1 '' } , function ( data ) { // do something } ) ; $ .getJSON ( '/website/json ' , $ ( formName ) function ( data ) { // do something } ) ; $ .getJSON ( '/website/json ' , 'action=read & record=1 & ' + $ ( formName ) .serialize ( ) , function ( data ) ... | How to submit a form and pass some extra parameters to a $ .getJSON callback method ? |
JS | Why does the following go from true to false ; and then it continue switching true , false , true , false ... ... | var r = /e/gi ; r.test ( ' e ' ) ; // truer.test ( ' e ' ) ; // false | Why does RegEx.test changes the result in subsequent calls ? |
JS | I 'm trying to write a test download works , which requires to check if xhr response has status READY . I created a client function in TestCafe , using promises , but it 's failing in case of recursion . How should I fix my code to handle this situation ? P.S . many apologies for newbies questions , I have just started... | fixture ` Download report works ` test .requestHooks ( logger ) //connected a request hook , will wait for logger request ( ' I should be able to download PDF report from header of the page ' , async t = > { //recursively check if response status is READY , and then go to assertions const waitForDownloadResponseStatus ... | How to add recursive function checking xhr response in testcafe script ? |
JS | I 'm using WebStorm and everytime I run the local server for testing purposes using npm start , it crashes inevitably sometimes after doing nothing , and sometimes after making a change or so.I 'm using this React boilerplate and the actual author responded to a bug issue I brought up about this saying `` Based on the ... | Error : EPERM : operation not permitted , lstat ' C : \ProjectDirectory\.git\index.lock ' at Error ( native ) | WebStorm keeps crashing my locally ran server because of Git 's index.lock |
JS | I have text that was created created with CKeditor , and it seems to be inserting & nbsp ; where spaces should be . And it appears to do similar conversions with > , < , & , etc . which is fine , except , when I make a DOMSelection , those codes are removed.So , this is what is selected : But this is what is actually i... | before < a href=\ '' http : //wiki.teamliquid.net/starcraft2/Hatchery\ '' style=\ '' text-decoration : none ; color : rgb ( 0 , 43 , 184 ) ; background-image : none ; background-attachment : initial ; background-origin : initial ; background-clip : initial ; background-color : initial ; background-position : initial in... | Is there a javascript function that converts characters to the & code ; equivalent ? |
JS | Supposed I have an array of objects structured like thisHow can I re-structure it like this : I tried It can successfully delete the chk property , but how can I combine the two objects ? | `` err '' : [ { `` chk '' : true , `` name '' : `` test '' } , { `` chk '' : true `` post '' : `` test '' } ] `` err '' : [ { `` post '' : `` test '' `` name '' : `` test '' } ] arr.filter ( obj = > delete obj.chk ) ; | Combine object and delete a property |
JS | Here is a part of my < HTML/ > : And additional my CSS : The System : As you see I use a swiper . When somebody clicks on a swiper child I use this JS code to set the sub_loading_help container over the swiper at a special position : The Problem : As I know I need to set the style.position of sub_loading_help to absolu... | < div style= '' position : relative '' > < div id= '' sc '' class= '' swiper-container '' style= '' margin : 30px ; overflow : hidden ; '' > < div class= '' swiper-wrapper '' > < div id= '' swiper_prev_0 '' class= '' swiper-slide '' onclick= '' openSub ( 0 , this ) '' > Slide 1 < /div > < div id= '' swiper_prev_1 '' cl... | Set element to special coordinates even with position relative ? |
JS | Let 's say I have a text with mark , such as : And I would like to disable selecting such that start or end of selection is not in the mark . Therefore , all of these selections should be possible : On the other hand , these selections should be disabled : So far , I tried only using some simple css , jsfiddle linkIs t... | mark { -khtml-user-select : all ; -webkit-user-select : all ; -o-user-select : all ; user-select : all ; } This is < mark > marked text < /mark > . I want to disable selecting only part of < mark > marked text < /mark > . function checkSelection ( ) { var sel = window.getSelection ( ) ; var marks = document.getElements... | How to disable selecting some of the text in div ? |
JS | I am working on solutionI have created a basic html banner where I want to keep image and text animations in sync.Basically image animation is like scale logo for about 3 seconds , meanwhile logo is animated I want text for same in typing effect I have created basic solution using css and javascript but it is not in sy... | var typewriter = function ( txt ) { var container = document.getElementById ( 'typewriter ' ) , speed = 28 , i = 0 , wordsObj = txt.split ( `` `` ) container.textContent = `` '' ; runAllWords ( ) ; function runAllWords ( ) { if ( i < wordsObj.length ) { var a = ( i == 0 ) ? i : i - 1 ; setTimeout ( function ( ) { showW... | How to sync two animations using css keyframes ? |
JS | I 'm struggling to port some JavaScript code ( which includes async and graph functionality ) to R. Help please ! Here 's what I 'm trying to port : And this is what I have so far in R : Please note that I 've included some commented out some lines of JavaScript code where I 'm not sure what the R equivalent is . Most ... | import jsonpFetch from `` ./jsonpFetch '' ; import bus from '../bus ' ; /** * This function builds a graph from google 's auto-suggestions . */export default function buildGraph ( entryWord , pattern , MAX_DEPTH , progress ) { entryWord = entryWord & & entryWord.trim ( ) ; if ( ! entryWord ) return ; entryWord = entryW... | Port JavaScript async and igraph code to R ? |
JS | I have a video tag that I want to play continuously while a user can simultaneously do stuff on the site . However I have found that if the background transitions between background images that the video starts buffering . I have a runnable example in the snippet below.Note : The buffering does not seem to occur if the... | function changeBackground ( ) { const randomColor = ' # '+Math.floor ( Math.random ( ) *16777215 ) .toString ( 16 ) ; const element = document.getElementById ( 'background ' ) ; const currentOpacity = element.style.opacity ; const currentBackground = element.style.backgroundImage ; switch ( currentBackground ) { case '... | CSS background-image transition makes video tag buffer |
JS | Here is the case : Output : I need this Output : Contiguous / repeated characters must be ignored , just take the single `` = '' to split.Maybe some regex ? | var stringExample = `` hello=goodbye==hello '' ; var parts = stringExample.split ( `` = '' ) ; hello , goodbye , ,hello hello , goodbye==hello | Split by a character in JavaScript but not contiguous ones |
JS | Anyone knows why in javascript this worksbut this does n't ? It throws the exception : TypeError : Function.prototype.apply was called on undefined , which is a undefined and not a function | m = Math.maxm.apply ( null , [ 1,2,3 ] ) m = Math.max.applym ( null , [ 1,2,3 ] ) | Assigning apply to a variable |
JS | I have an application that in debug mode is written in many separate javascript files , but are loaded synchronously as part of the head block of a page . In release , I merge all these files together and minifiy them . Today I kept finding an error in the minified version , so I loaded up a single merged file to debug... | < head > < script > var a = { } a.X = function x ( ) { console.log ( `` should n't be executed '' ) ; } ( function ( a ) { console.log ( `` self execution '' ) ; } ( a ) ) ; < /script > < /head > self execution should n't be executed < head > < script > var a = { } function x ( ) { console.log ( `` should n't be execut... | Why are functions on the object being executed from a self executing function ? |
JS | With prototype inheritance in ES5 , it looks not trivial to inherit from Array and get the expected behavior , like updating .length automatically when adding item to Array ( see below code ) . ES5 creates object of the derived function ( MyArray ) then pass it base type to do initialization , why is this model hard to... | function MyArray ( ) { } MyArray.prototype = Object.create ( Array.prototype ) ; var myArr = new MyArray ( ) ; myArr [ 0 ] = 'first ' ; console.log ( myArr.length ) ; // expect ' 1 ' , but got ' 0 ' in output | Why inheriting from Array is difficult to implement in ES5 ? |
JS | I have the code snippet below . If you press `` Run code snippet '' then you will see the following 1 - p.getClientRects ( ) .length 2 - span.getClientRects ( ) .lengthBut if you press `` Expand snippet '' at first , and then `` Run code snippet '' then you will see a bit different result : 1 - p.getClientRects ( ) .le... | var p = document.querySelector ( ' p ' ) ; var span = document.querySelector ( 'span ' ) ; console.log ( p.getClientRects ( ) .length , `` - p.getClientRects ( ) .length '' ) ; console.log ( span.getClientRects ( ) .length , `` - span.getClientRects ( ) .length '' ) ; p { border : 1px solid green ; } span { border : 1p... | Why does the same code using getClientRects ( ) produce different results ? |
JS | I have two array of objects like following : I want a merged result of above like thisPlease notice the merging is happening on id , which both of the arrays have.I tried to follow this one How to merge these arrays/json objects ? and this one How can I merge properties of two JavaScript objects dynamically ? But , I t... | result = [ { id:24 , name : '' xyz '' } , { id:45 , name : '' tze '' } ] moreDetails = [ { id:24 , name2 : '' hyi '' } , { id:45 , name2 : '' tikw '' } ] mergedResult= [ { id:24 , name : '' xyz '' , name2 : '' hyi '' } , { id:45 , name : '' tze '' , name2 : '' tikw '' } ] | How to merge two array of objects |
JS | in my project , I am having one challenge . ie.. I need to call multiple API calls one by one . Here I am using RxJS flatMap operator for that . it is working expected . but my additional requirement is I need to set 10 seconds delay for every API call . I have used 'throttle ' operator but It is not working.I have att... | public makeSubmitAPI ( oncallData ) : Observable < any > { let orderPayload = this.postAPIService.prepareOrderPayload ( oncallData ) ; let url = `` '' ; let orderResponse : any ; return this.apiCallsService.apiCall ( 'placeOrder ' , orderPayload , 'post ' , false ) .map ( ( orderRes : any ) = > { orderResponse = orderR... | set delay for 5 sec after one API call |
JS | I 'm trying to find out the most effecient way to create a new instance of an object.When I started , I used something like this : Afterwards I heard it be better to skip the prototype because the new prototypes would use up unneeded memory , getting something like this : However , now I have the problem of creating th... | var Foo = function ( a , b , c ) { this.a = a ; this.b = b ; this.c = c ; } Foo.prototype.func = function ( ) { // Do stuff ; } var bar = new Foo ( 1 , 2 , 3 ) ; bar.func ( ) ; var Foo = function ( a , b , c ) { return { a : a , b : b , c : c , func : function ( ) { // Do stuff ; } } } var bar = Foo ( 1 , 2 , 3 ) ; bar... | The most efficient way to create a new instance of JS object |
JS | So we have this activity in our computer course , it is about creating a website for entering personal information with 'submit ' and the problem is , one of the task is for the client/server to be able to search the information entered by the users . So , i 'm confused as to how to handle the 'submit ' and 'search ' .... | < form name= '' keke '' onsubmit= '' return that ( ) ; '' method= '' post '' > < td > First Name < br > < input autofocus= '' 1 '' required= '' 1 '' type= '' text '' name= '' firstn '' id= '' txtbox_firstname '' style= '' width : 99 % ; color : black ; '' > < /td > < ! -- this is the submit input type , it is part of <... | How to save user input with js and show info when searched specifically |
JS | I am trying to close Android emulator using telnet command via Appium script but after executing the telnet command waiting for manual input for `` kill '' command.Unable to execute the `` Kill '' command along with Appium script . | Runtime.getRuntime ( ) .exec ( `` telnet localhost 5554 '' ) ; Process proc= Runtime.getRuntime ( ) .exec ( `` kill '' ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( proc.getInputStream ( ) ) ) ; System.out.println ( `` executed3 '' ) ; String line ; while ( true ) { line = r.readLine ( ) ; if ( li... | Android emulator close using telnet via appium script |
JS | After upgrade jQuery 3.4.0 to 3.4.1 , on blur ( ) or focus ( ) events on input I 'm getting Can not read property 'value ' of undefined error.I think that may be cause of this change in jquery source code : https : //github.com/jquery/jquery/commit/24d71ac70406f522fc1b09bf7c4025251ec3aee6 ? diff=unified # diff-031bb62d... | that.container.on ( 'click ' , '.binary_field ' , function ( ) { $ ( `` input : focus '' ) .blur ( ) ; } | JQuery 3.4.1 Can not read property 'value ' of undefined |
JS | Minimal problem example : https : //codepen.io/sidouglas/pen/LYPZaOG When input range is focused , with either Chrome Vox or Mac 's Voice over — every value of valuetext is read out continuously.Contrast this to the very accessible https : //plyr.io/ # audio component - When focused it continues to update its aria valu... | < input ... v-bind : aria-valuemax= '' valueMax '' v-bind : aria-valuenow= '' valueNow '' v-bind : aria-valuetext= '' currentTime + ' of ' + totalDuration '' ... / > new Vue ( { el : ' # range ' , data : { valueMax:100 , duration:100 , current:0 , totalDuration : ' 1:40 ' } , computed : { currentTime : function ( ) { r... | HTML Audio accessibility with Input Range |
JS | I was looking through the React source and stumbled across a requirement with var emptyFunction = require ( 'fbjs/lib/emptyFunction ' ) ; .I looked at this function and was confused by what it does.Here is the functionIn the comments , they give the following explanation which I was confused by : This function accepts ... | function makeEmptyFunction < T > ( arg : T ) : ( ... args : Array < any > ) = > T { return function ( ) { return arg ; } ; } const emptyFunction : ( ... args : Array < any > ) = > void = function ( ) { } ; | What purpose does makeEmptyFunction serve in fbjs ? |
JS | I 'm confused about scopes in Javascript and how to get a global function recognized . On my page I havedefined . Then in another file , I haveThe alert executes without a problem . However in the `` mytoherfile.js '' references to the Base64 class result in a RerefernceError . So at the top of my myotherfile.js I trie... | < script src= '' base64.js '' > < /script > var xhr = new XMLHttpRequest ; ... var full = location.protocol+'//'+location.hostname+ ( location.port ? ' : '+location.port : `` ) ; alert ( Base64.decode ( `` abc '' ) ) ; xhr.open ( `` get '' , full + `` myotherfile.js '' , true ) ; xhr.send ( ) import { Base64 } from 'ba... | How do I get a global function recognized by my JS file loaded through AJAX ? |
JS | I receive an object that looks like this : I want to filter by id and remove the Object which id matches the id I receive from the store . What I tried so far : This replaces the Object with undefined - which would work for my purposes but is obviously not ideal.Any help is much appreciated ! | this.tokensData = { O : { id : 0 , name : value1 , organization : organization1 , ... , } , 1 : { id : 1 , name : value1 , organization : organization1 , ... , } , 2 : { id : 2 , name : value2 , organization : organization2 , ... , } , ... } const filteredObject = Object.keys ( this.tokensData ) .map ( ( token ) = > { ... | Filter nested object |
JS | I 'm getting started with javascript unit testing ( with Jasmine ) .I have experience in unit testing C # code . But given that javascript is a dynamic language , I find it very useful to exploit that , and writing tests using the expressive power of javascript , for instance : As far as doing this kind of non-conventi... | describe ( 'known plugins should be exported ' , function ( ) { var plugins = [ 'bundle ' , 'less ' , 'sass ' , 'coffee ' , 'jsn ' , 'minifyCSS ' , 'minifyJS ' , 'forward ' , 'fingerprint ' ] ; plugins.forEach ( function ( plugin ) { it ( 'should export plugin named ' + plugin , function ( ) { expect ( all [ plugin ] )... | Unit testing javascript code style |
JS | Google Analytics initially uses a _gaq [ object Array ] . Passing an array to a function is in JavaScript passing an object , thus by reference . ( Edit : As pointed out in answers , the reference is passed by value . See https : //stackoverflow.com/a/5314911/120521 for more details on reference/value passing in JavaSc... | var _gaq = _gaq || [ ] ; _gaq.push ( [ '_setAccount ' , _gAAccount ] ) ; _gaq.push ( [ '_trackPageview ' ] ) ; ( function ( ) { var ga = document.createElement ( 'script ' ) ; ga.type = 'text/javascript ' ; ga.async = true ; ga.src = ( 'https : ' == document.location.protocol ? 'https : //ssl ' : 'http : //www ' ) + '.... | Why are n't prototype changes passed by reference to a method ? |
JS | I 've got a binding for multiple inputs.Since there are other ways of initiating a change of an input , ( jquery 's .change ( ) method for one ) , Is there a way to tell if a checkbox was actually clicked to cause the change event ? I tried focus however the focus event fires before a checkbox 's change event so that d... | $ ( `` # foo '' , `` # bar '' , `` # fooCheckbox '' , `` # barCheckBox '' ) .bind ( `` change '' , function ( ) { // do something here // do something extra here if $ ( this ) was actually clicked } ) ; $ ( `` # foo '' , `` # bar '' , `` # fooCheckbox '' , `` # barCheckBox '' ) .bind ( `` change '' , function ( ) { // ... | How can I tell if a checkbox was actually clicked ? |
JS | I 've come across this way of isolate binding specification : What does the asterisk mean here ? Can someone please provide an example ? | scope : { property : `` =* '' } | What is `` =* '' in AngularJS |
JS | I want to change the word in the span tag every 1.5 seconds but so far it is just displaying the last word in the array 'list'.Here is my javascriptAnd here is the html | var list = [ `` websites '' , `` user interfaces '' ] ; setInterval ( function ( ) { for ( var count = 0 ; count < list.length ; count++ ) { document.getElementById ( `` word '' ) .innerHTML = list [ count ] ; } } , 1500 ) ; < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < title > < /... | Loop is only displaying the last string in an array when adding it a span tag |
JS | I wanted to dig in into the language specific construct `` prototype '' of javascript.And here is my learning purpose code : When i debug this code now with firebug , i get the following : Where does this infinite nesting come from ? Let 's begin from top ( OK=unterstood ) : f ( OK ) - ext ( OK ) - prototype ( OK ) - p... | var f = function ( ) { } ; f.ext = 1 ; f.prototype.pext = 2 ; | Firebug showing infinite recursion for constructor |
JS | This question is coming from a javascript point of view , but it certainly could apply to other languages . I have been running into this more and more lately , and was wondering if there was a best practice , or at least good design standard , for when how to build your methods.The obvious options that I see are as fo... | this.makeGetRequest = function ( controller ) { ... } this.makeSynchronousGetRequest = function ( controller ) { ... } this.makePostRequest = function ( controller , data ) { ... } //data would be an optional parameter// this.makeRequest ( `` friends '' , `` GET '' , true ) ; // this.makeRequest ( `` friends '' , `` PO... | When to use which - multiple methods , multiple parameters , or an options parameter |
JS | I read a lot about this topic and safari seems to have issues with that ( even filesaver.js ) . I still wonder , if any of you has an approach that makes it possible for a user to click a button and download a json file - with a file name - to his device.There are a lot of threads out there and safari seems to have had... | exportButton.addEventListener ( `` click '' , ( ) = > { const appState = databaseConnector.getApplicationStateAsString ( ) ; const blob = new Blob ( [ appState ] , { type : `` text/json '' } ) ; const fileName = ` backup_ $ { new Date ( ) .toISOString ( ) .split ( `` T '' ) [ 0 ] } .json ` ; const tempElement = documen... | How to download a JSON file with javascript on iOS Safari ? |
JS | I am new to jQuery so please excuse me ! I have a PHP function that returns me a blog from a MySQL database ; it returns headline , subtitle and content.There are three entries shown so far . I have a jQuery that hides the content and expands it when the headline is clicked using the nextUntill method and .slideToggle ... | $ result = getData ( ) ; while ( $ row = mysqli_fetch_array ( $ result ) ) { extract ( $ row ) ; ? > < div class= '' headline '' > < ? php echo $ headline ? > < /div > < div class= '' subtitle '' > < ? php echo $ subTitle ? > < /div > < div class= '' content '' > < ? php echo $ content ? > < /div > < ? php } $ ( `` .co... | Want to use jQuery .nextUntill but exclude a div inbetween |
JS | My task is to take the data from http : //services.swpc.noaa.gov/text/ace-swepam.txt and split/sort it into something useful . To start with , I 'm trying to split the data into categories , so that I can use in chart.js or something later on , but when I try and print a field , it just comes up as [ ] . | var options = { host : 'services.swpc.noaa.gov ' , path : '/text/ace-swepam.txt ' , port : 80 , method : 'POST ' } ; var req = http.request ( options , function ( res ) { res.on ( 'data ' , function ( chunk ) { // console.log ( 'BODY : ' + chunk ) ; results += chunk.toString ( ) ; //split results into an array by each ... | Using the data from an HTTP request in node.js |
JS | I 've noticed that the Javascript sort function is extremely slow in Internet Explorer versions below 9 ( often by an order of magnitude when compared to Firefox and others . I 'm implementing my own version to see if I can do better . Merge sort works decently , but it seems that most of the documentation for sorting ... | function mergeSort ( array , compareFunc ) { if ( array.length < = 1 ) { return ; } var mid = Math.floor ( array.length/2 ) ; var left = array.splice ( 0 , mid ) ; var right = array.splice ( 0 , array.length ) ; mergeSort ( left , compareFunc ) ; mergeSort ( right , compareFunc ) ; while ( ( left.length > 0 ) & & ( rig... | Sorting that is aware of the unique way Javascript represents arrays |
JS | So I thought I understood hoisting in JavaScript until I saw something like this : The code above outputs 5 , not undefined ! As per my understanding , the function looks like this to the interpreter : So what 's happening here ? | function hoist ( a ) { console.log ( a ) ; var a = 10 ; } hoist ( 5 ) ; function hoist ( a ) { var a ; // This should overshadow the parameter ' a ' and 'undefined ' should be assigned to it console.log ( a ) ; // so this should print undefined a = 10 ; // now a is assigned 10 } | Hoisting inside function having same variable name |
JS | I have a variable mutedUser which I would like to have persist to another function . I am having a bit of trouble with the variable persisting outside the click event . What would be the best way to have it so the `` return mutedUser '' would keep the `` muted '' string addition based on the conditions of the if statem... | this.isUserMuted = function isUserMuted ( payload ) { var mutedUser = `` ; // If mute button is clicked place them into muted users list // check for duplicates in list $ ( `` # messages-wrapper '' ) .off ( 'click ' , '.message button.muteButton ' ) ; $ ( `` # messages-wrapper '' ) .on ( 'click ' , '.message button.mut... | Issue with Javascript Variable Scope |
JS | Following this tutorial to get an api and client on google cloud platform : https : //www.freecodecamp.org/news/create-a-react-frontend-a-node-express-backend-and-connect-them-together-c5798926047c/I have a root dir with an /api and /client inside itthe /api package.json has the following scriptthe /client package.json... | `` scripts '' : { `` start '' : `` node ./bin/www '' } , `` scripts '' : { `` client-install '' : `` npm install -- prefix client '' , `` start '' : `` node server.js '' , `` server '' : `` nodemon server.js '' , `` client '' : `` npm start -- prefix client '' , `` dev '' : `` concurrently \ '' npm run server\ '' \ '' ... | Deploying app to google app engine and want to start api and client |
JS | I use mouseover to get the cursor type , i get different results in Chrome and in Firefox when mouse is over for some reason the cursor style in Chrome is `` auto '' and in Firefox is `` text '' . I need to know when the cursor is default in both browsers and when it 's auto ( as it 's suppose to be over text input ) o... | window.onmouseover=function ( event ) { var currentCursor = $ ( event.target ) .css ( 'cursor ' ) ; console.log ( currentCursor ) ; $ ( ' # pointer ' ) .html ( currentCursor ) ; } ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js '' > < /script > < input type= '' text '' width= '' 10... | Mouse event cursor difference between browsers |
JS | Code like this : gives me string as result . This means strings are not objects , then why do we have properties of a string str like str.substring , str.indexOf etc . ? Also when i set property to it asstr.property = `` custom property is set '' ; and trying to get this alert ( str.property ) , it gives me undefined .... | var str = `` Hello StackOverflow ! `` ; alert ( typeof str ) ; | Strings are not object then why do they have properties ? |
JS | I have a web application that has some interactions where the user is required to long press / hold on the screen to progress , this all works fine , however on WeChat in China , and similar browser/webviews like Tencent ( X5 ) , a context menu appears when holding the screen.I 've tried the following code ( and all va... | // Long press , then the following code executesdocument.addEventListener ( 'contextmenu ' , ( e ) = > { alert ( 'Right click ' ) ; e.preventDefault ( ) ; e.stopPropagation ( ) ; return false ; } ) ; // As soon as the alert is dismissed , the context menu still appears | How to disable context menu in Tencent / X5 / WeChat browser on Android |
JS | I 'm using Apache Cordova to develop mobile application . the problem is that I want to get mobile phone number and then send it via jQuery get function for authorization . all functions are OK but the function that get mobile phone number is slower than other and it get finished last.a summary of my code is this : I d... | document.addEventListener ( `` deviceready '' , onDeviceReady , false ) ; function onDeviceReady ( ) { devicePhoneNumber ( ) ; alert ( `` ALERT1 '' ) ; // ALERT1 } ; function devicePhoneNumber ( ) { var telephoneNumber = cordova.require ( `` telephonenumber '' ) ; telephoneNumber.get ( function ( result ) { alert ( res... | How to make a javascript function to run after another one get finished ? |
JS | I need to loop through a JavaScript object treating it as an array with custom keys.I know this is not fully supported , since properties have no instrinsic order , but since I always reorder the properties , I found this approach simple and reliable ... until now.The problem occurs when the keys are numbers , or strin... | var test1 = { 4294966222 : '' A '' ,4294966333 : '' A '' ,4294966111 : '' A '' } ; var test2 = { 4294968222 : '' A '' ,4294968333 : '' A '' ,4294968111 : '' A '' } ; for ( var k in test1 ) { console.log ( k ) ; } console.log ( `` -- - '' ) ; for ( var k in test2 ) { console.log ( k ) ; } 429496611142949662224294966333 ... | Sorting properties in Javascript is broken |
JS | I want to port the following JavaScript code to Haskell : http : //jsfiddle.net/mz68R/This is what I tried : It partly works as expected : it does n't produce an infinite list of Fibonacci numbers . It prints out varying numbers of Fibonacci numbers : I believe that the problem is due to concurrency in the getEvent fun... | import Control.Concurrentimport Data.IOReftype EventStream a = IORef [ MVar a ] newEventStream : : IO ( EventStream a ) newEventStream = newIORef [ ] setEvent : : EventStream a - > a - > IO ( ) setEvent stream event = readIORef stream > > = mapM_ ( ` putMVar ` event ) getEvent : : EventStream a - > ( a - > IO b ) - > I... | Implementing Event Streams in Haskell using MVars |
JS | I want to create somthing like that handle synchronous behavior and asynchronous behavior at the same time.For example I would like to be able something like that : Here i want to remove the promise that returned finishedTest from lunchedPromiseWhat I already tried : And it obviously does not work because ( finishedTes... | function timeout ( myJson ) { return new Promise ( function ( resolve , reject ) { setTimeout ( resolve , myJson.wait , myJson ) ; } ) ; } async function funct ( ) { try { let PromiseTolaunch = [ { `` wait '' : 10 , `` nextIndex '' : 2 , `` id '' : 1 } , { `` wait '' : 500 , `` nextIndex '' : -1 , `` id '' : 2 } , { ``... | It is possible to remove a promise from an array of promise ? |
JS | Update : It might be the jQuery 's trigger ( ) do some extra works in testings , I opened a issue on github.=====I 'm following learnQuery to build my simple jQuery . Now working on DOM event , implement on ( ) and off ( ) function . They provided some testings , I ca n't pass some of them.Here is my code : ( And you c... | `` use strict '' ; function isEmpty ( str ) { return ( ! str || 0 === str.length ) ; } // listener use to bind to DOM element , call corresponding functions when event firing.function geneEventListener ( event ) { console.log ( 'gene ' ) ; let type = Object.keys ( this.handlers ) .find ( type= > type===event.type ) ; i... | Selfmade jQuery can not handle event properly |
JS | While on the nodejs REPL I was trying to clean up an array defined as const array = [ ... ] and just found out that using array.forEach ( ( ) = > /pop|shift/ ( ) ) would not work . After such expression the array will still hold values in it.I 'm well aware of better methods to clean the array , like array.splice ( 0 )... | const a = [ 1 , 2 , 3 ] a.forEach ( ( ) = > { a.shift ( ) } ) console.log ( a ) // [ 3 ] const b = [ 1 , 2 , 3 ] b.forEach ( ( ) = > { b.pop ( ) } ) console.log ( b ) // prints [ 1 ] | Why array.forEach ( ( ) = > { array.pop ( ) } ) would not empty the array |
JS | I 'm new to JavaScript , and am having a problem understanding this code : This prints ( in v8/d8 ) a is 4 ; b is 5 . If I comment out the var value ; line , I get a is 5 ; b is 5 . Where is the 'value ' object , and why are there two of them ? Thanks . | function addProperty ( o ) { var value ; o [ `` get '' ] = function ( ) { return value ; } o [ `` set '' ] = function ( v ) { value = v ; } } var a = { } ; addProperty ( a ) ; var b = { } ; addProperty ( b ) ; a.set ( 4 ) ; b.set ( 5 ) ; print ( `` a is `` + a.get ( ) + `` ; b is `` + b.get ( ) ) ; | Misunderstanding of JavaScript closures |
JS | How do I shorten this ? I 'd like to write it without having to repeat Progress.bar.status twice . Something along the lines of : | if ( Progress.bar.status == 'finished ' || Progress.bar.status == 'uploading ' ) { //code here } Progress.bar.status == ( 'finished ' or 'uploading ' ) . | Shortcut to compare if statements |
JS | This does not work : Firefox throws me a nasty exception on line myElement.callMe ( ) . Apparently , `` myElement.callMe is not a function '' .I am confused why is that so ? To my understanding , as soon as I type const myElement = document.createElement ( 'my-element ' ) , I am receiving an object whose type is not a ... | < ! -- wtf.html -- > < ! DOCTYPE html > < html lang= '' en '' > < head > < meta charset= '' UTF-8 '' / > < title > < /title > < script type= '' module '' src= '' ./wtf.js '' > < /script > < /head > < body > < script > const myElement = document.createElement ( 'my-element ' ) document.body.appendChild ( myElement ) myE... | How do JS modules prevent custom elements defined inside from exposing their APIs ? |
JS | I have an object that looks something like this Which is read into my javascript with a $ .getJSON call.So I have the JS object `` reply '' that holds all this data.I need to append items such that `` entries '' becomes extended as follows : I have tried But that does not work ( I presume because nothing is an array ) ... | { `` _id '' : `` DEADBEEF '' , `` _rev '' : `` 2-FEEDME '' , `` name '' : `` Jimmy Strawson '' , `` link '' : `` placeholder.txt '' , `` entries '' : { `` Foo '' : 0 } } { `` _id '' : `` DEADBEEF '' , `` _rev '' : `` 2-FEEDME '' , `` name '' : `` Jimmy Strawson '' , `` link '' : `` placeholder.txt '' , `` entries '' : ... | Appending to a JS object that is not an array ? |
JS | Consider a situation where you have a class B extending from class A . You create an object of type B and call a method fooA defined in A and then a method fooB defined in B.When run , the code logs the following as expectedSo Javascript understands that new B ( ) .fooA ( ) is an object of class B . However Flow gives ... | class A { fooA ( ) { console.log ( 'fooA called ' ) return this } } class B extends A { fooB ( ) { console.log ( 'fooB called ' ) return this } } new B ( ) .fooA ( ) .fooB ( ) fooA calledfooB called Can not call new B ( ) .fooA ( ) .fooB because property fooB is missing in A | JS Flow : Is inheritance in Flow broken ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.