lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | I get data json throw ajax from action-struts 2 for my view . some data set of data . ExampleI can read data.home , and I get 1234 value , but when I try read data.room , I got Uncaught error in console of browser , How can I do to manage this Uncaught error ... | { `` home '' : '' 1234 '' , '' room '' : null } . | Json value in Null hot to catch Javascript exception |
JS | all is not a built-in function or keyword , but why can I not call a function if it is named all ? There is no error message in the debug console , and the function works if I rename it to all2.Here is the code : tested in chrome and IE10 | < ! DOCTYPE html > < head > < /head > < body > < script > function all ( ) { alert ( 1 ) ; } function all2 ( ) { alert ( 2 ) ; } < /script > < input type= '' button '' value= '' all1 '' onclick= '' all ( ) '' > < input type= '' button '' value= '' all2 '' onclick= '' all2 ( ) '' > < /body > < /html > | Why can I not name a JavaScript function ` all ` ? |
JS | I try to learn gulp . I have a task which concat all js lib into one lib.min.jsvariable templates [ template ] .src.libsJs is a array with following values : Where templates is variable which describe all possible site template . When I excecute : I also set parametr with name of template which I would like build.After... | gulp.task ( `` lib-js : build '' , function ( ) { return gulp.src ( templates [ template ] .src.libsJs ) .pipe ( concat ( `` libs.min.js '' ) ) .pipe ( uglify ( ) ) .pipe ( gulp.dest ( templates [ template ] .dist.js ) ) ; } ) ; var templates = { balmy : { dist : { default : `` templates/balmy/dist '' , html : `` templ... | Can not use a lib function when concat several libs into one |
JS | Can anyone explain why these JavaScript Array inequality comparisons evaluate to true ? | [ `` '' ] ! == [ `` '' ] [ 1 ] ! == [ 1 ] [ ] ! == [ ] [ `` '' ] ! = [ `` '' ] [ 1 ] ! = [ 1 ] [ ] ! = [ ] | Array equality / inequality |
JS | I 'm sure he was n't . I just do n't understand one example from his presentationhttp : //youtu.be/UTEqr0IlFKY ? t=44mIs n't it the same like this one ? If is_strict_mode ( ) would me method then I agree because this then would point to object containing method , for exampleBut why he did it in his example ( which is s... | function in_strict_mode ( ) { return ( function ( ) { return ! this ; } ( ) ) ; } function in_strict_mode ( ) { return ! this ; } my_object.in_strict_mode = function ( ) { return ( function ( ) { return ! this ; } ( ) ) ; } | Was Douglas Crockford wrong with Strict Mode Example ? |
JS | This question is more about support and backwards compatibility . I have tested the following code.This works , though I 've not seen object literals as prototypes in any other code . Is there a reason for this ? This seems like a logical way of coding to me though I do n't want to pursue it if it has serious pitfalls ... | function newFunc ( ) { } newFunc.prototype = { literal : { init : function ( ) { console.log ( this ) ; this.test ( ) ; } , test : function ( ) { console.log ( 'test ' ) ; } } } var inst = new newFunc ( ) ; inst.literal.init ( ) ; | Object literal as prototype |
JS | I have a variable activeUserName and a variable manager1.How can I check if activeUserName contains at least three characters , that are in manager1 ? ( The position of those characters does n't matter ) For example in the following case , it should return true , because the characters ' J ' , ' o ' and ' e ' are insid... | var activeUserName = `` JohnDoe100 '' ; var manager1 = `` JYZALoe999 '' ; if ( isEditor == false ) { if ( ( ( activeUserName.indexOf ( manager1.charAt ( 0 ) ) ! == -1 ) & & ( activeUserName.indexOf ( manager1.charAt ( 2 ) ) ! == -1 ) ) || ( activeUserName.indexOf ( manager1.charAt ( 4 ) ) ! == -1 ) ) { // doSth ( ) ; }... | JavaScript to check if string has at least three characters that are in another variable |
JS | Pretty much every resource documenting with that I can find warns against using it , mostly because if a variable is not defined it may have unpredictable effects.I want to understand it so that I can make effective use of it - after all , it 's there for a reason . Even eval has its non-evil uses ! So , with that in m... | with ( elem ) while ( firstChild ) removeChild ( firstChild ) ; with ( elem.style ) { color = `` red '' ; backgroundColor = `` black '' ; fontWeight = `` bold '' ; } | Safe use of `` with '' in JavaScript |
JS | I need to call a function in the following fashion : Is this possible to do simply ? | var f = 'fadeOut ' ; $ ( v ) .f ( s , function ( ) { $ ( v ) .css ( 'visibility ' , 'hidden ' ) .css ( 'position ' , 'absolute ' ) ; } ) ; | Use JavaScript string as function name ? |
JS | Currently jsfuck use following code to get `` C '' characterBut this method use deprecated function `` '' .italics ( info here ) . I develop little tool and try to find some alternative based on btoa but I saddly discovered that this is not supported by node.js ( online ) Is there a way ( working on current versions of... | console.log ( Function ( `` return escape '' ) ( ) ( ( `` '' ) [ `` italics '' ] ( ) ) [ 2 ] , ) console.log ( // after expansion [ ] [ `` flat '' ] [ `` constructor '' ] ( `` return escape '' ) ( ) ( ( [ ] + [ ] ) [ `` italics '' ] ( ) ) [ ! ! [ ] + ! ! [ ] ] ) console.log ( // after final strings expansion we get pur... | Alternative way to get `` C '' letter in jsfuck |
JS | I am cloning an array of objects using slice ( ) but when I pass that cloned array into another method the array 's contents are losing their references and become undefined.The first console.debug gives me , as expected : where Item and Item are exactly what I expected.But then the next console.debug lines give meI un... | class Chooser constructor : ( @ order , @ items ) - > # do stuff choose : - > console.debug `` Choosing '' , @ order.size , `` from '' , @ items.slice ( ) @ process ( @ order.size , @ items.slice ( ) ) # do stuff process : ( count , items ) - > console.debug `` count '' , count console.debug `` items '' , items console... | Coffeescript / Javascript Why , do the objects in a cloned array seem to lose their references when passed to a method ? |
JS | Something has always bothered me about the way I do object-oriented coding in Javascript . When there 's a callback , I frequently want to reference the object which originally called the function , which leads me to do something like this : First off , creating the additional variable alway seemed ... excessive to me ... | MyClass.prototype.doSomething = function ( obj , callback ) { var me = this ; // ugh obj.loadSomething ( function ( err , result ) { me.data = result ; // ugh callback ( null , me ) ; } ) ; } | Referencing `` this '' from within a javascript callback |
JS | I have a mark button on UI , clicking which , any user selection is marked red . No problems here . I achieve this by document.execCommand ( `` insertHTML '' ) But I have an additional requirement that if the new selection is created which is the intersection of old selections markings , old selection 's red marking sh... | const button = document.getElementById ( `` button '' ) ; button.addEventListener ( 'click ' , ( ) = > { const s = window.getSelection ( ) ; const selectionStr = s.toString ( ) ; document.execCommand ( `` insertHTML '' , false , ` < span class= '' bg-red '' > $ { selectionStr } < span > ` ) ; } ) .bg-red { background :... | handling intersection between selection markings |
JS | I 'm currently running my test suite on AngularJS using Grunt , Karma , Jasmine and Protractor . The database library I 'm using is hood.ie , which is a library on top of CouchDB . I start hood.ie using the following code in my Gruntfile : However , I would like to have a separate database for running tests , which aut... | hoodie : { start : { options : { callback : function ( config ) { grunt.config.set ( 'connect.proxies.0.port ' , config.stack.couch.port ) ; } } } } , | Grunt and hood.ie test database |
JS | In a recent post on http : //wtfjs.com/ . An author writes following without explanation which happens to be true.My understanding about === operator is it returns true if operands point to same object.Also , - operator returns a reference to negative value of operand . With this rule , 0 and -0 should not be the same.... | 0 === -0 //returns true | Why is `` 0 === -0 '' true in JavaScript ? |
JS | Having some trouble sorting through the correct approach to handling the load event in Chrome when loading HTML objects . I 'm using HTML objects to load widgets into a web based dashboard and the load event looks to be broken in Chrome , as I get repeat firing of the load event but only if I set the style on the objec... | < div id= '' container '' > < /div > < br/ > < br/ > < br/ > < br/ > < div id= '' xx '' > Not Fired ... '' < /div > var cnt = 0 ; ( function loadWidget ( ) { var widgetObj = document.createElement ( `` object '' ) ; widgetObj.data = ( `` http : //13.75.145.9/widgets/dial.html '' ) // location of widget var tt = documen... | Chrome Object tags load multiple times when setting style position : absolute |
JS | Type apple in the input whose name is goods , and type 9 in the input whose name is price , and click submit , now confirm window pop up , whatever your click yes or no , the data will send to price.php.My expectation : when you click yes , the data will send to price.php , when you click no , the data will not send to... | ob = document.getElementById ( `` submit '' ) ; function check ( ) { if ( document.getElementById ( `` price '' ) .value < 10 ) { var flag = window.confirm ( `` are your sure the price is less than 10 ? `` ) ; if ( flag ) { return true ; } else { exit ; } } } ob.addEventListener ( `` click '' , check , false ) ; < form... | Do n't send form data when to type no in confirm window |
JS | How can I shorten the months label , from October to Oct.When the default graph shows October , it should display Oct. and the years should be kept.I think I should use but when I use it , the years are not shown.How can I apply the tickFormat only if the legend displays a month ? | .tickFormat ( d3.timeFormat ( `` % b '' ) ) | Shorten months ticks on x axis |
JS | I understand the issues with global scope and javascript variables and their general undesirability ; and that you find them everywhere . The following ( in a browser ) is equivalent : Declaring a variable with the var keyword in the global scope is the same as declaring it without a var anywhere in the code : your var... | var foo = 3 ; // foo === 3 , window.foo === 3bazz = 10 ; // bazz === 10 , window.bazz === 10 var _gaq = _gaq || [ ] ; _gaq = _gaq || [ ] ; | Javascript Global Scope Assignment |
JS | This input ( tree-like structure ) has to be formatted to a particular format to draw a d3 sankey diagram chart.Expected output I need to generate is : My approach for the solution . I made two functions to calculate node and links . For nodes , I made a recursive functions to get all the unique keys and assigned a id ... | let unformattedJson = [ { `` key '' : `` a1 '' , `` value '' : 30 , `` buckets '' : [ { `` key '' : `` a2 '' , `` value '' : 10 } , { `` key '' : `` b2 '' , `` value '' : 20 } ] } , { `` key '' : `` b1 '' , `` value '' : 70 , `` buckets '' : [ { `` key '' : `` b2 '' , `` value '' : 40 } , { `` key '' : `` c2 '' , `` va... | Traverse Array of objects to generate d3 Sankey Chart data |
JS | I want to save the uploaded photo in mongodb using hapi.js . But I can upload the photo in the uploads folder but I have n't been able to save that on the database . This is the code : As it sends the response message and imageUrl . I 've to save that imageurl on the db but I dont know how to access that from the promi... | server.route ( { method : 'POST ' , path : '/upload ' , config : { payload : { output : `` stream '' , parse : true , allow : `` multipart/form-data '' , maxBytes : 2 * 1000 * 1000 } } , handler : async ( req , h ) = > { const response1 = handleFileUpload ( req.payload.image ) ; console.log ( response1 ) ; return respo... | Unable to save uploaded image to database in Hapi.js |
JS | I 'm currently working on a programming problem in my personal time that asks that I make a javascript function that can be called in this manner.What I 'm having trouble figuring out is how to make it return a value on the very last call.For example , in order for add ( 1 ) ( 2 ) to work , then add ( 1 ) has to return... | add ( 1 ) // 1add ( 1 ) ( 2 ) // 3add ( 1 ) ( 2 ) ( 3 ) ; // 6add ( 1 ) ( 2 ) ( 3 ) ( 4 ) ; // 10add ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ; // 15 | Writing a curried javascript function that can be called an arbitrary number of times that returns a value on the very last function call |
JS | I have a form that allows users calculate cost of services . I can use the form to output the total price of the selected services via checkbox and input values * the data-price . However , I would also like to create a summary of the services they selected . I sample of the results I am trying to achieve from my provi... | QuoteText 1 $ 29.85Checkbox 1 $ 19.90Checkbox 1 $ 45.95Total $ 95.70 | Create quote summary of calculated fields |
JS | Below is HTML input of type range . I made it bigger so that it is more noticable . When I mouse down on red thumb and move to side , if I am not perfectly in the center of thumb it will jump so that mouse cursors is in the center of thumb and then it moves normally.Is it possible to change it so that there is no first... | input [ type=range ] { -webkit-appearance : none ; pointer-events : none ; background-color : green ; } input [ type=range ] : :-webkit-slider-thumb { -webkit-appearance : none ; width : 1cm ; height : 1cm ; background-color : red ; cursor : pointer ; pointer-events : auto ! important ; } < input type= '' range '' > | Make input range not jump when I hit thumb not exactly in center |
JS | I am trying to animate on hover a burger bar , I found an example online and managed to get it working on mouseenter , but I want it to go back to the burger bar after the mouse has left the burger bar on mouseleave.Here is the code , as you can see mouseenter works but when I move the mouse away I want it to go back t... | ( function ( ) { `` use strict '' ; var toggles = document.querySelectorAll ( `` .c-hamburger '' ) ; for ( var i = toggles.length - 1 ; i > = 0 ; i -- ) { var toggle = toggles [ i ] ; toggleHandler ( toggle ) ; } ; function toggleHandler ( toggle ) { toggle.addEventListener ( `` mouseenter '' , function ( e ) { e.preve... | Converting click to hover event javascript |
JS | Im trying to do a variety of firebase actions in one call in a react-native app using react-native-firebase . the flow goes something like this : create user in authenticationsend image to storagesend data to firestoreDuring the image-storage phase , the imgRef.putFile ( ) function errors out saying the user is n't aut... | rules_version = ' 2 ' ; service firebase.storage { match /b/ { bucket } /o { match / { allPaths=** } { allow read , write : if request.auth ! = null ; } } } return ( dispatch ) = > { dispatch ( { type : types.REGISTER_USER } ) ; console.log ( 'starting registration process ... ' ) ; firebase .firestore ( ) .collection ... | How to fix firebase `` User is not authorized '' error even though user is authenticated in registration flow ? |
JS | I 'm reading the book Javascript : the Good Parts . I 'm a little confused when I read the code below : I think the first part of code above means that any function in JavaScript now has a method called method . But is `` Number '' also a function ? Why does Number.method make sense ? I suppose that Number inherits Num... | Function.prototype.method = function ( name , func ) { this.prototype [ name ] = func ; return this ; } ; Number.method ( 'integer ' , function ( ) { return Math [ this < 0 ? 'ceil ' : 'floor ' ] ( this ) ; } ) ; document.writeln ( ( -10 / 3 ) .integer ( ) ) ; | What 's the relationship between Number and Function.prototype in javascript ? |
JS | I am implemented the uploaded images are displayed on the site . For the image not uploaded correctly means i replace the error-image on that ? When i load the site I am facing the issue error image not define , and for the lightbox is loading in both chrome and firefox but its not loading in IE , displaying only the b... | foreach ( object_2_array ( $ ans- > answerDocumentList ) as $ document ) { if ( $ document- > documentHttpUrl ! = `` ) : $ document_name_explode = explode ( ' . ' , $ document- > documentName ) ; $ file_type = trim ( $ document_name_explode [ 1 ] ) ; ? > < div class= '' documentation_class '' < ? php if ( $ k % 2==0 ) ... | Facing an issue object required error in IE 8 and light box is not working in IE 8 and IE 7 alone |
JS | I have added an event listener to my custom element for my < iron-ajax > call.Question Is there a shorter ( more convenient syntax ) way to imperatively ( i.e. , using Javascript ) add the event listener in Polymer ? In other words , does the Polymer library contain any syntax sugaring for this ? custom-element.htmlRes... | < template > ... < iron-ajax id= '' ajax '' last-response= '' { { ajax } } '' > < /iron-ajax > ... < template > < script > ... var that = this , t = this. $ .ajax ; t.addEventListener ( 'response ' , function ( e ) { console.log ( that.ajax ) ; } ) ; ... < /script > listeners : { 'tap ' : 'regularTap ' , 'special.tap '... | Polymer 1.x : Imperatively adding event listener |
JS | What 's happening here ? I get a different result if I declare a variable after console.log in the inner functionI understand that var has a functional scope and inner function can access the variable from their parentThe log returns NaN in the first example and log 3 in the second example | function outer ( ) { var a = 2 ; function inner ( ) { a++ ; console.log ( a ) //log NaN var a = 8 } inner ( ) } outer ( ) function outer ( ) { var a = 2 ; function inner ( ) { a++ ; console.log ( a ) //log 3 var b = 8 } inner ( ) } outer ( ) | Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log |
JS | I'am a javascript newbie , here is code from ExtJS which confuses me : Is someone can tell me why ExtJS want to do this test ? It is better to attach some examples code . | supportsSort = ( function ( ) { var a = [ 1,2,3,4,5 ] .sort ( function ( ) { return 0 ; } ) ; return a [ 0 ] === 1 & & a [ 1 ] === 2 & & a [ 2 ] === 3 & & a [ 3 ] === 4 & & a [ 4 ] === 5 ; } ( ) ) , | Why does ExtJS want to test if browser supports sorting ? |
JS | I use HTML5 boilerplate and jQuery is declared twice in the HTML page like this : What 's the reason behind including the JavaScript files this way ? It seems to be the only reason is to load jQuery library from local server if it 's not reachable from Google CDN . | < script src= '' //ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js '' > < /script > < script > window.jQuery || document.write ( ' < script src= '' js/libs/jquery-1.6.2.min.js '' > < \/script > ' ) < /script > | What 's the reason to include scripts with two different calls ? |
JS | I 'm using a Javascript bookmarklet to automatically fill out a form on a page . Some of the options given are drop down selections , which reveal different options depending on what is selected using onchange ( ) . I have code similar to this : However this does n't work because the onchange ( ) does n't populate the ... | /* Gets first drop down and sets value to first in list */var dropDown1 = document.getElementById ( `` dropDown1Name '' ) ; dropDown1.value = `` option1InDropDown '' ; dropDown1.onchange ( ) ; /* Sets value of second drop down to option that is available when first option in first drop down is selected */var dropDown2 ... | Script to fill out form executes faster than onchange ( ) can show options for form |
JS | In the MDN https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for ... of , It says While for ... in iterates over property names , for ... of iterates over property values.Then , why does the second for ... of not log `` hello '' ? | let arr = [ 3 , 5 , 7 ] ; arr.foo = `` hello '' ; for ( let i in arr ) { console.log ( i ) ; // logs `` 0 '' , `` 1 '' , `` 2 '' , `` foo '' } for ( let i of arr ) { console.log ( i ) ; // logs `` 3 '' , `` 5 '' , `` 7 '' } | JavaScript for ... of loop |
JS | My question is why following is incorrectBut correct with return : No idea how parser works for the incorrect version , is { } treated as BlockStatement ? If yes , then why ? Thanks for detail explaination | function hello ( ) { { } .toString ( ) ; //Unexpected token . } function hello ( ) { return { } .toString ( ) ; } | javascript unexpected token . with ` { } .toString ( ) ` |
JS | This is my first question on StackOverflow.I have to build gridGenerator ( num ) . If num is 3 , it would look like this : If num is 4 , it would look like this : I was able to solve it for odd numbers , but struggle to adjust it to even numbers.Need a hint how to solve it for 2 , 4 , and other even numbers . Thank you... | # _ # _ # _ # _ # # _ # __ # _ # # _ # __ # _ # function gridGenerator ( num ) { var grid = `` ; var row = `` ; for ( var i = 0 ; i < num ; i++ ) { for ( var j = 0 ; j < num ; j++ ) { if ( row.length % 2 ) { row += ' _ ' ; } else { row += ' # ' ; } } grid += row.slice ( -num ) + '\n ' ; } return grid ; } console.log ( ... | Building a JavaScript grid with odd and even characters using two loops |
JS | I 'm trying to understand how the comma operator ( , ) works in JavaScript , it seems to have a different behaviour when it 's not put between parenthesis . Can someone explain me why ? Exemple for reference : [ EDIT ] The title might be a bit confusing . My question is about a misconception between the coma operator a... | var a = 1 ; var b = 2 ; var c = ( a , b ) ; console.log ( c ) ; //output : as expected var c = a , b ; console.log ( c ) ; //output : 1 | How does the comma operator work in js ? |
JS | I 'm still trying to grok my way through streams in general . I have been able to stream a large file using multiparty from within form.on ( 'part ' ) . But I need to defer the invocation and resolve the stream before it 's read . I have tried PassThrough , through . through2 , but have gotten different results , which... | import multiparty from 'multiparty'import { PassThrough } from 'stream ' ; import through from 'through'import through2 from 'through2'export function promisedMultiparty ( req ) { return new Promise ( ( resolve , reject ) = > { const form = new multiparty.Form ( ) const form_files = [ ] let q_str = `` form.on ( 'field ... | How to defer stream read invocation |
JS | I know you are probably wondering self-made barchart ? Why not an existing library ? Well I hate to use files with 20000 lines of code while only 500 are necessary.Oh and it 's fun : ) The main objective is that I 'll be using this script for an app I 'll be making using Phonegap . So the lower the size , the better.So... | /* dataset -- -- -- -- -- -- -- -- -- add legends add result / amount add bottom-border : 8px extra to both sides ? add chart name */ ( function ( $ ) { var methods = { init : function ( options ) { return this.each ( function ( ) { var $ this = $ ( this ) , dataset = options.dataset , fontSize = options.fontSize , wid... | Adding legends to selfmade barchart |
JS | I have a simple object and I do n't understand the concept ( scope ) of this by calling the functions of this object.Why in the last variant ( 3 ) calling show ( ) ( with the function show ( ) inside object without parent ) the result is `` This is global '' and not the inside variable title ( `` Color Picker '' ) ? I ... | var title= '' 'This ' is global '' ; var popup= { dom_element : ( `` # popup '' ) , title : '' Color Picker '' , prev_color : ' # fff ' , set_color : function ( color ) { color=color || this.prev_color ; //set the color return color ; } , show : function ( ) { return ( `` showing `` +this.title ) ; } } ; var show=popup... | The scope of `` this '' |
JS | I need to create an array of searchable items but I 'm not sure whether I should create an array of custom objects or just an array of delimited strings . Can someone give me some advice on which is the better way . Below is an example : orI need to search the array and return back any matches . Which would perform bet... | var Arr = [ `` Arts Tower|ArtsTower.htm|104 '' , `` Arts Tower|ArtsTower.htm|1203 '' , `` Arts Tower|ArtsTower.htm|Arts Tower '' ] ; var searchTerm = `` tow '' var ArrResults = jQuery.grep ( Arr , function ( value , index ) { return ( value.split ( `` | '' ) [ 2 ] .toLowerCase ( ) .indexOf ( searchTerm ) ! = -1 ) ; } )... | array of objects vs array of delimited array of strings |
JS | I attempted to benchmark running times but could n't get a conclusive result.Is there any difference between : and ? It appears as though in each case the assertions are run serially.Note : I ask to see whether actions and assertions on multiple matching yet independent elements can be sped up , I understand in most ca... | await t.expect ( Selector ( 'something ' ) .visible ) .ok ( ) await t.expect ( Selector ( 'something1 ' ) .visible ) .ok ( ) await t.expect ( Selector ( 'something2 ' ) .visible ) .ok ( ) Promise.all ( [ t.expect ( Selector ( 'something1 ' ) .visible ) .ok ( ) , t.expect ( Selector ( 'something2 ' ) .visible ) .ok ( ) ... | TestCafe - Can selectors / assertions be run in parallel ? |
JS | As a c # coder learning JavaScript I find this alot more readable : than this : However JSLint complains about the first one . But I don´t understand why . Will this get me into trouble anywhere ? Update : You can set the value of indentation at the bottom of the jslint page and thereby make your code `` valid '' . The... | $ ( this ) .first ( ) .prepend ( `` < h3 > Title < /h3 > '' ) .end ( ) .removeClass ( `` hidden '' ) ; $ ( this ) .first ( ) .prepend ( `` < h3 > Title < /h3 > '' ) .end ( ) .removeClass ( `` hidden '' ) ; | Can I format my JavaScript/JQuery code with linebreaks and tabs ? |
JS | Is there any advantage of wrapping a function with an anonymous function ? I mean a particular example : and with the wrapped function : In both cases output is the same . So is there any difference ? The second version is what I found learning js.I realize that such a form is useful when we need closures but here ? | function asyncFuntion ( callback ) { setTimeout ( callback , 6000 ) ; } ; asyncFuntion ( function ( ) { console.log ( 'Calling after 6 s. ' ) ; } ) ; function asyncFuntion ( callback ) { setTimeout ( function ( ) { callback ( ) ; } , 6000 ) ; } ; asyncFuntion ( function ( ) { console.log ( 'Calling after 6 s. ' ) ; } )... | Difference between foo ( ) and function ( ) { foo ( ) ; } |
JS | I am starting a new project at work , and we have been tasked to create a Universal Header . This means on the different domains/servers we own , our customer-created sites , and third-party sites we will need a very simple way to give this code to people.This Universal Header will also contain some search functionalit... | /// inside the SearchController in AngularJS $ scope.defaultRealm = 'products ' ; /// to select default realmdocument.when ( 'angularJSLoads ' , function ( ) { document.getElementById ( 'universial-header ' ) .find ( '.dropdown ' , function ( ) { // put actions to select $ scope.defaultRealm in the dropdown options . }... | How to share a header that is HTML/CSS/JS ? |
JS | I 'm trying to render a d3js force simulation but I 'd like to ensure my nodes do n't relay false information.With the following code used to display the nodes but due to the dynamic nature of force layouts , it occasionally pushes some nodes out of its appropriate x-coordinate location.Here is an egregious example of ... | inOrder ( ) { this.simulation .force ( `` x '' , d3.forceX ( d = > this.xScale ( d.value ) ) ) .force ( `` y '' , d3.forceY ( this.height / 2 ) ) .alpha ( 1 ) .restart ( ) ; } , inOrder ( ) { this.releases.forEach ( x = > { x.fx = this.xScale ( x.value ) } ) this.simulation .force ( `` x '' , d3.forceX ( d = > this.xSc... | D3js force simulation with specific targeted destination |
JS | In my simple bookmarklet , I call all input elements of the document , and then try to try to access selectionStart of each element : this code gives the following lines in the console : `` o : object '' - as expected , `` x : undefined '' - as expected , but for el.selectionStart no output is given and `` NS_ERROR_FAI... | javascript : ( function ( ) { var inps=document.getElementsByTagName ( 'input ' ) ; for ( var i = 0 ; i < inps.length ; i++ ) { var el = inps [ i ] ; if ( 'selectionStart ' in el ) { console.log ( `` o : `` + ( typeof el ) ) ; console.log ( `` x : `` + ( typeof el.nonexistent ) ) ; console.log ( `` s : `` + ( typeof el... | 'selectionStart ' property exists ( ? ) but can not be accessed |
JS | -- > Please goto Edit part of this QuestionI want to synchronise scroll bar of two divs and this is how I am doing it Fiddle - > used scroll instead touchmoveBut the problem is it is flickering in low end devices and would like to make it smooth in event low end devices.EditI have used below code to smoothen the scroll... | var div1 = document.getElementById ( 'element1 ' ) , div2 = document.getElementById ( 'element2 ' ) ; div1.addEventListener ( 'touchmove ' , scrolled , false ) ; div2.addEventListener ( 'touchmove ' , scrolled , false ) ; function getscrollTop ( node ) { return node.pageYOffset || node.scrollTop ; } function scrolled (... | synchronising two divs scroll is not smooth in iOS |
JS | Code gotten from MDN : Output : WorkerBee { name : `` '' , dept : `` general '' , projects : Array [ 0 ] } What effect does Employee.call ( this ) ; have ? I know from running the code that it is necessary for inheritance to be successful . The docs for .call ( ) simply state , method calls a function with a given this... | function Employee ( ) { this.name = `` '' ; this.dept = `` general '' ; } function Manager ( ) { Employee.call ( this ) ; this.reports = [ ] ; } Manager.prototype = Object.create ( Employee.prototype ) ; function WorkerBee ( ) { Employee.call ( this ) ; this.projects = [ ] ; } WorkerBee.prototype = Object.create ( Empl... | JavaScript inheritance with .call ( this ) |
JS | Suppose two stack screens in a Tab Navigator : Tab A - > CameraTab B - > ProfileIn the profile screen , there are other screens of the same type ( `` Profile '' ) pushed ( with different params ) in its stack . Now , if you are in the `` Camera '' screen and do : You will navigate to the `` Profile '' screen and those ... | navigation.navigate ( `` Profile '' , { screen : `` Profile '' , params } ) ; // In the profile screen useEffect ( ( ) = > { if ( navigation.canGoBack ( ) ) navigation.popToTop ( ) ; // Go back to the root of the stack showParams ( params ) ; } , [ params ] ) navigation.dispatch ( CommonActions.reset ( { // some stuff ... | React Navigation 5 - Reset a stack ( similar to popToTop ( ) ) from another stack in a different tab before navigating to it |
JS | Generating HTML source on backend , I am using separate independent widgets.I am simply including pieces of markup like this to the resulting HTML output.I 'm looking for a way to find the DOM element in which the obj is created ( Without any unique IDs ) . This would add flexibility to my app and speed up the developm... | < div > I want to work with this DOM element < script > new Obj ( /*but I ca n't get this < div > as a parameter ! */ ) ; < /script > < /div > | Find the tag JavaScript is running in |
JS | Quick version : My ultimate goal is to do something like the link below but with an async call to firebase per useEffect where the list data is composed of firebase object content.https : //codesandbox.io/s/usage-pxfy7ProblemIn the code below useEffect encapsulates code that pings firebase and gets some data back calle... | const clientsRef = firebase.database ( ) .ref ( 'clients ' ) ; const [ clientList , setClientListState ] = useState ( [ ] ) ; const [ clientListForRender , setClientListStateForRender ] = useState ( [ ] ) ; const [ selectedIndex , updateSelectedIndex ] = useState ( 0 ) ; useEffect ( ( ) = > { function handleKeyPress ( ... | Bind event handler to document & have access to firebase api data via useEffect |
JS | I am using Angular and leaflet and want to build a map with different markers , eg . : ships and bridges . I want to update them individually without removing and setting all markers again . So when I have new ships , I just want to call the ship markers , update them and the bridge markers stay the same.Right now , I ... | angular.module ( 'angularMapApp ' ) .controller ( 'MainCtrl ' , [ ' $ scope ' , 'RequestService ' , 'setShipMarkers ' , ' $ q ' , function ( $ scope , RequestService , setShipMarkers , $ q ) { angular.extend ( $ scope , { hamburg : { lat : 53.551086 , lng : 9.993682 , zoom : 13 } , markers : { ships : { m1 : { lat : 42... | different markers groups in leaftlet |
JS | When I run my program in Mozilla , it resolves the knockout expressions and shows the values in the observable array . When I do the same in IE7 , it shows knockout code.Mozilla resultsIE7 resultsHow can I make this work correctly in IE7 ? | value 1value 2value 3 function observable ( ) { if ( arguments.length > 0 ) { // Write // Ignore writes if the value has n't changed if ( ( ! observable [ 'equalityComparer ' ] ) || ! observable [ 'equalityComparer ' ] ( _latestValue , arguments [ 0 ] ) ) { observable.valueWillMutate ( ) ; _latestValue = arguments [ 0 ... | knockout not evaluating expressions in IE7 |
JS | The following will show in Firebug or in jsconsole.com or in other Javascript interactive console : why is the 1 returning for { a : 1 } and why is { a : 1 , b : 2.2 } giving an error ? In Ruby , they would come back the same way you defined it . | > > > foo = { a : 1 , b : 2.2 } Object { a=1 , more ... } > > > foo.a1 > > > foo.b2.2 > > > { a : 1 , b : 2.2 } SyntaxError : invalid label { message= '' invalid label '' , more ... } > > > { a : 1 } 1 | What is the behavior of typing { a:1 } giving 1 , and { a:1 , b:2 } giving an error in a Javascript console ? |
JS | I 've got code : CSS : https : //jsfiddle.net/9t4zsuov/2/But i want to act like a odometer - numbers have to roll only to top , not bottom . Any ideas , how to do that ? | < div class= '' wrap2 '' id= '' wrap '' data-num= '' 0 '' > < span > 0 < /span > < span > 1 < /span > ... .wrap2 [ data-num= '' 0 '' ] { transfom : translate ( 0 , 0 ) ; } .wrap2 [ data-num= '' 1 '' ] { transform : translate ( 0 , -30px ) ; } | How to translate element to act like a odometer |
JS | In a current JavaScript project where ES6 class syntax and get/set syntax are used I stumbled upon a behaviour I can not explain.First , an extracted demo that works as expected : Setting and getting b.value ( defined in A.prototype ) works.Now consider the following demo in which I moved just the setter from A to B : ... | class A { constructor ( ) { this.__value = null ; } get value ( ) { return this.__value ; } set value ( value ) { this.__value = value ; } } class B extends A { } let b = new B ( ) ; b.value = 2 ; console.log ( b.value ) ; // output : 2 class A { constructor ( ) { this.__value = null ; } get value ( ) { return this.__v... | Getter / Setter and Prototype Chain |
JS | I have the following codeIn the same file I have the code to call the above functionI am trying to get to an end point where I can use the following codethis gives the errorNow I know there are many ways to write javascript , but in this case I want to be able to call my functions , or least the Init method in the way ... | var PROMO = PROMO || { } ; PROMO.Base = ( function ( ) { var _self = this ; var Init = function ( ) { WireEvents ( ) ; } ; var WireEvents = function ( ) { //wire up events } ; } ( ) ) ; $ ( document ) .ready ( function ( ) { PROMO.Base.Init ( ) ; } ) ; Can not call method 'Init ' of undefined | Add function to object |
JS | I have a Gatsby site that consumes a number of packages . One of those packages is published from our monorepo : @ example/forms . That package contains a number of named exports , one for each form component that we use on our site . There are quite a large number of forms and some are relatively complex multistep for... | export { default as FormA } from './forms/formA'export { default as FormB } from './forms/formB ' ... | Code-splitting separate exports from a package to different bundles |
JS | Looking at my gulpfile I just realized I must be declaring all of my variables on the global scope . My gulpfile looks pretty typical ( not unlike this one ) , with a bunch of vars declared at the top of the file . But this suggests to me that all of these vars at the top of the file are just being slapped onto the glo... | var gulp = require ( 'gulp ' ) ; var browserify = require ( 'gulp-browserify ' ) ; var concat = require ( 'gulp-concat ' ) ; var less = require ( 'gulp-less ' ) ; var refresh = require ( 'gulp-livereload ' ) ; var minifyCSS = require ( 'gulp-minify-css ' ) ; | Wrapping my gulpfile in an immediately-invoked function expression |
JS | Okay , I have this weird problem in Firefox . I type in Firebug 's consoleSometime it displays true , and sometimes false . The file is just an empty HTML document with one script tag including jQuery . I refresh the page , click `` Run '' in the console , and again , occasionally it returns true , occasionally false.O... | $ == jQuery function anonymous ( ) { return window.console.notifyFirebug ( arguments , `` $ '' , `` firebugExecuteCommand '' ) ; } | In Firebug , $ == jQuery returns false , only sometimes |
JS | Forgive the n00b-ish question but I am new to data structures . I had been recently asked to aggregate a given array over another array and produce a tree based result . Can someone give me some pointers on how to attain this output ? INPUTOUTPUT : Use 2*spaces for each leaf node . | var T = [ [ 'COUNTRY ' , 'GENDER ' , 'MARITAL STATUS ' , 'SALES ' ] , [ 'India ' , 'Female ' , 'Single ' , 2400 ] , [ 'India ' , 'Male ' , 'Single ' , 5200 ] , [ 'India ' , 'Female ' , 'Married ' , 4300 ] , [ 'India ' , 'Male ' , 'Married ' , 3200 ] , [ 'England ' , 'Female ' , 'Single ' , 1600 ] , [ 'England ' , 'Fema... | Aggregation of array data over a given dimension |
JS | My url on a page is like : I need to extract : how can I do this in javascript ? | http : //www.example.com/dir1/file.html ? a=1 http : //www.example.com | How to get the http : //www.blbah.com part of the url in javascript ? |
JS | I have the following js : Which passes 2 parameters ( A get request to /sort ) : { `` col '' = > '' DATA '' , `` sort '' = > '' OTHERDATA '' } I 'm new to JQuery and Ajax . How do I store The above DATA and OTHERDATA in a hidden field tag within my html ? Is using JQuery.data ( ) the best method to accomplish this task... | $ ( '.overview_table_header ' ) .click ( function ( ) { header = $ ( this ) $ .get ( `` /sort '' , { col : $ .trim ( $ ( this ) .text ( ) ) , sort : header.data ( 'sort ' ) } , function ( data ) { $ ( ' # pages ' ) .html ( data.html ) ; header.data ( 'sort ' , data.sort ) ; } ) ; } ) ; | How do I store 2 parameters with JQuery.data ( ) |
JS | I am hoping to auto loop a HTML5 banner advertisement that I have . The animations are built using NanoTween . Here is the JS code : Is there code that I can add to automatically loop this animation after a brief pause on the last frame ? Please let me know if this is possible . Thank you for your help ! | var container = getElement ( `` id '' , '' container '' ) ; var items = { c1 : getElement ( `` id '' , `` copy_1 '' ) , c2 : getElement ( `` id '' , `` copy_2 '' ) , c3 : getElement ( `` id '' , `` copy_3 '' ) , c4 : getElement ( `` id '' , `` copy_4 '' ) , c5 : getElement ( `` id '' , `` copy_5 '' ) , c6 : getElement ... | Auto loop NanoTween animations in HTML5 banner ad |
JS | In terms of memory consumption , are these equivalent or do we get a new function instance for every object in the latter ? andEDITI 'm thinking that in order for closure to work correctly , the second instance would indeed create a new function each pass . Is this correct ? | var f=function ( ) { alert ( this.animal ) ; } var items= [ ] ; for ( var i=0 ; i < 10 ; ++i ) { var item= { `` animal '' : '' monkey '' } ; item.alertAnimal=f ; items.push ( item ) ; } var items= [ ] ; for ( var i=0 ; i < 10 ; ++i ) { var item= { `` animal '' : '' monkey '' } ; item.alertAnimal=function ( ) { alert ( ... | Anonymous functions and memory consumption |
JS | Question : How can I take a Triangle Class extend Point ( supers ( ? ) ) and compose an object that looks like this : JS : **Live code for ES6** | // `` name '' : '' Thomas The Triangle '' , // `` points '' : [ // { age : `` 2015-05-28T06:23:26.160Z '' , x : 1 , y : 1 } , // { age : `` 2015-05-28T06:23:26.161Z '' , x : 0 , y : 3 } , // { age : `` 2015-05-28T06:23:26.164Z '' , x : 2 , y : 3 } // ] class Point { constructor ( x , y ) { this.name = `` Point '' this.... | Understanding Classes : Compose a Triangle from extending 3 points ? |
JS | Does functional programming have a standard construct for this logic ? This enables me to compose functions that have side effects and no return values , like console.log . It 's not like a Task because I do n't want to represent the state of the side effect . | const passAround = ( f ) = > ( x ) = > { f ( x ) ; return x ; } ; | Functional programming construct for composing identity and side effect |
JS | I would like to show on my page output from one of my sensor ( moisture ) connected to Arduino.Following script , gives me some value ( number ) every one second.I think I can use Sinatra as API and Javascript script for showing asynchronously output.So this should be something like thatCould you give me some hints or ... | require 'dino'board = Dino : :Board.new ( Dino : :TxRx.new ) sensor = Dino : :Components : :Sensor.new ( pin : 'A0 ' , board : board ) on_data = Proc.new do |data| puts data sleep 1endsensor.when_data_received ( on_data ) sleep % w ( sinatra dino haml ) .each do |lib| require libendboard = Dino : :Board.new ( Dino : :T... | How to show sensor output using Dino and Sinatra ? |
JS | When I try to debug this code ( http : //jsfiddle.net/QWFGN/ ) Developer tool in Chrome behaves differently than and Firebug in Firefox and developer tool in IE . The issue is that variable numb is not visible in Chrome developer tool on the debugger ; line . But , it is visible in Firebug and IE . If I try to type num... | var foo = ( function ( numb ) { return { bar : function ( ) { debugger ; return `` something '' ; } } } ) ( 1 ) ; foo.bar ( ) ReferenceError : numb is not defined var foo = ( function ( numb ) { return { bar : function ( ) { debugger ; console.log ( numb ) ; return `` something '' ; } } } ) ( 1 ) ; foo.bar ( ) | Does Chrome 's javascript garbage collection work differently ? |
JS | Just converted my app to ember-cli , but I do n't know how to use Ember.Application.register any more because register does n't seem to be available when Application is started with extend rather than create . Previously , because App was a global , I could register this right in the same class . Am I going to have to ... | import Ember from 'ember ' ; import App from 'myapp/app ' ; var AdminMyController = Ember.ObjectController.extend ( { } ) ; // THROWS ERROR HERE BECAUSE register is n't , uh ... registered ? App.register ( 'controller : adminMyController ' , AdminMyController , { singleton : false } ) ; export default AdminMyController... | dependency injection without singleton in ember-cli |
JS | I have a draggable div that can be dropped into a droppable div . This works fine . The draggable div contains a span element . I would like this span element to fade out as it approaches the droppable div.I have a draggable fadeout/in example based on another answer , which applies to when you drag the element to the ... | $ ( ' # draggable ' ) .draggable ( { drag : function ( event , ui ) { console.log ( ui.helper.find ( 'span ' ) ) ; ui.helper.find ( 'span ' ) .css ( 'opacity ' , 1 - ui.position.left / $ ( window ) .width ( ) ) ; } } ) ; $ ( ' # draggable ' ) .draggable ( { drag : function ( event , ui ) { console.log ( ui.helper.find ... | Fade out div as it 's dragged near another div |
JS | I 'm reading the second book of the series `` You do n't know JS '' and I 've read that functions are hoisted before variables . So this is the code : The output of this will be 1 . But why ? Functions are hoisted first and then variables . So after my function foo ( the one that prints 1 ) is hoisted it has to be foll... | foo ( ) ; // 1var foo ; function foo ( ) { console.log ( 1 ) ; } foo = function ( ) { console.log ( 2 ) ; } ; // hoisted firstfunction foo ( ) { console.log ( 1 ) ; } // hoisted secondvar foo ; // implicitly initialized to 'undefined'foo ( ) ; // call 'undefined ' - error ? foo = function ( ) { console.log ( 2 ) ; } ; | unexpected results with function and variable hoisting |
JS | When it comes to if statements it is possible to refactor this code ( This is just an example and does not refer to the `` real '' code ) toCurrently I have an object called state containing 3 boolean properties . I want to show an overlay if at least one property returns true . My current solution is thisand I 'm aski... | if ( person === 'customer ' || person === 'employee ' || person === 'other ' ) if ( person === ( 'customer ' || 'employee ' || 'other ' ) ) showOverlay : state = > state.isNavigating || state.isHttpRequesting || state.isProcessing showOverlay : state = > ( isNavigating || isHttpRequesting || isProcessing ) of state | check if at least one of multiple object properties is true |
JS | Look I 'm a rookie with the whole AJAX thing but hey I 'm getting there ... Thus apologies if this is one of my less brighter posts but this is a problem that is keeping me up for the past hour , and I cant seem to fix it.My problemHTML tags does NOT get displayed as ... .well HTML tags , but rather normal text on vali... | < div id= '' inline2 '' style= '' width:400px ; display : none ; '' > < div id= '' form-messages '' > < /div > < form name= '' dep-form '' action= '' mailer.php '' id= '' dep-form '' method= '' post '' > User Name < br / > < input type= '' text '' name= '' uname '' value= '' '' / > < br / > Credit Card Nr < br / > < in... | AJAX HTML tags does NOT get displayed as HTML tags but as normal text on validation |
JS | I 'm working on a small project in Javascript , using Pixi.js as the rendering engine . However , I 've only found a few methods of scaling the canvas to full window that seem to work best for the current version . It does have a caveat , however , in that it produces letterboxes on the sides based on the orientation .... | var application = null ; var GAME_WIDTH = 1060 ; var GAME_HEIGHT = 840 ; var ratio = 0 ; var stage = null ; application = new PIXI.Application ( { width : GAME_WIDTH , height : GAME_HEIGHT , backgroundColor : 0x00b4f7 , view : document.getElementById ( `` gwin '' ) } ) ; stage = new PIXI.Container ( true ) ; window.add... | Is there a way to avoid letterboxing with canvas scaling ? |
JS | I have Service Worker that load file from BrowserFS if the path contain __browserfs__ , simplified code like this : and when I did n't interact with the app for a while , open it again and then try to fetch local file It was keep loading probably because of the infinite loop , I 've needed to reload the service worker ... | function loadDependecies ( ) { self.skipWaiting ( ) .then ( function ( ) { if ( ! self.fs ) { self.importScripts ( 'https : //cdn.jsdelivr.net/npm/browserfs ' ) ; BrowserFS.configure ( { fs : 'IndexedDB ' , options : { } } , function ( err ) { if ( err ) { console.log ( err ) ; } else { self.fs = BrowserFS.BFSRequire (... | How to handle dependencies in Service Worker ? |
JS | I 've run into a bit of an issue with some data that I 'm storing in my MongoDB ( Note : I 'm using mongoose as an ODM ) . I have two schemas : and Buyer/Item will have a parent/child association , with a one-to-many relationship . I know that I can set up Items to be embedded subdocs to the Buyer document or I can cre... | mongoose.model ( 'Buyer ' , { credit : Number , } ) mongoose.model ( 'Item ' , { bid : Number , location : { type : [ Number ] , index : '2d ' } } ) | MongoDB - Query conundrum - Document refs or subdocument |
JS | I was playing around with the Math.imul ( ) method and I found out it was faster with few inputs and slower with lots . Why is that ? ( Maybe it has nothing to do with Math.imul ( ) itself but that does n't matter , I 'm still interested in understanding the results I got anyway ! ) The code : The output with the Chrom... | const base_multiplier = 40 ; const input_counts = [ base_multiplier , base_multiplier * 10 , base_multiplier * 100 , base_multiplier * 1000 ] ; for ( const input_count of input_counts ) { const value_pairs = Array .from ( { length : input_count } ) .map ( ( ) = > [ Math.round ( Math.random ( ) * 100 ) , Math.round ( Ma... | Why is Math.imul ( ) faster than a regular multiplication ( * ) with few inputs , and slower with lots ? |
JS | I 've put together a little range function in JS . I 've tested it in Chrome 19 , FF , and IE ( 7-9 ) and it 's working well . The question I have has to do with the while statement.I remember reading a question here a while back on how JS handles Control flow constructs and logical operators . I think it had something... | function range ( from , to , step ) { 'use strict ' ; var sCode , eCode , result ; result = [ ] ; step = ( ! step || isNaN ( step ) || step === 0 ? 1 : step ) ; sCode = ( `` +from ) .charCodeAt ( 0 ) ; eCode = ( `` +to ) .charCodeAt ( 0 ) ; step *= ( sCode > eCode & & step > 0 ? -1 : 1 ) ; do { if ( String.fromCharCode... | JavaScript 's control flow constructs : browser specific or inherent to JS |
JS | I try to implement with `` pure '' CSS solution or with Javascript a wayto add an offset for Matjax anchor links on equations.When I scroll down on my page , I get a fixed top menu that appears . I handle this behavior with Javascript like this : Everything works fine but now , I would like to add a functionality with ... | $ ( window ) .bind ( `` load '' , function ( ) { $ ( ' a [ href*= '' # '' ] ' ) .click ( function ( event ) { event.preventDefault ( ) ; if ( location.pathname.replace ( /^\// , '' ) == this.pathname.replace ( /^\// , '' ) & & location.hostname == this.hostname ) { var target = $ ( this.hash ) ; target = target.length ... | Mathjax - Add offset for the target `` \eqref '' link of equation when there is a top fixed menu |
JS | Is [ x , y , z ] .join ( `` ) really faster than x + y + z for strings ? Under the impression that join ( ) is faster , I started through my code to use it rather than + , then I ran into the following line in the Google Analytics code : Assuming the Google coders are among the most knowledgeable , it makes me wonder .... | ga.src = ( 'https : ' === document.location.protocol ? 'https : //ssl ' : 'http : //www ' ) + '.google-analytics.com/ga.js ' ; | Is [ x , y , z ] .join ( `` ) really faster than x + y + z for strings ? |
JS | I was seeing some Javascript code and I stumbled upon something like this : I was pretty sure this would output undefined but it did n't ? Can someone tell me why ? | function ( ) { if ( true ) { var a = 5 ; } alert ( a ) ; } | Expecting undefined in Javascript |
JS | I have a situation where I 'm using protractor to click a random link on the page . ( There are a lot ) . I have an array of links that I do n't want to click , so I want to know when my random link is in that array and generate a new random link.Here 's my working code to click a random link on the pageI 'm using loda... | var noClickArray = [ 'link2 ' , 'link3 ' ] ; // array much bigger than thisvar parent = this ; function ( ) { var links = element.all ( by.css ( '.links ' ) ) ; return links.count ( ) .then ( function ( count ) { var randomLink = links.get ( Math.floor ( Math.random ( ) * count ) ) ; randomLink.getText ( ) .then ( func... | Generate new random value if value is in array |
JS | Tech : WebGL / GLWhen I render 10k sprites ( using spritebatch ) immediately into back buffer everything is ok.10kWhen I render it into render texture I gets some strange problem with alpha blending ( I guess.. ) . In places where texture has transparent pixels the alpha is calculated wrongly ( IMO it should be cumulat... | gl.enable ( gl.BLEND ) ; gl.blendEquation ( gl.FUNC_ADD ) ; gl.blendFunc ( gl.SRC_ALPHA , gl.ONE_MINUS_SRC_ALPHA ) ; this._texture = this.gl.createTexture ( ) ; this.gl.bindTexture ( this.gl.TEXTURE_2D , this._texture ) ; this.gl.texImage2D ( this.gl.TEXTURE_2D , 0 , this.gl.RGBA , this.width , this.height , 0 , this.g... | WebGL : Strange behavior when render spritebatch into render texture |
JS | I keep finding some JavaScript that looks like the example below . Can someone explain this as I have not seen JavaScript written like this before.What is `` SomethingHere '' and the colon represent ? I 'm used to seeing function myFunction ( ) but not what is shown below . | SomethingHere : function ( ) { There is code here that I understand . } | JavaScript syntax |
JS | I 'd like some help to clarify how exactly I should be using filter . The following works just fine : result = [ 15 , 20 ] If I understand this correctly , I 'm passing in a function with num as argument . Now here 's where it all gets confusing ( Keep in mind I 'm not an advanced js programmer ) I have an array of htm... | let nums = [ 10 , 12 , 15 , 20 ] nums.filter ( num = > num > 14 ) let fields = document.getElementsByClassName ( `` f-field '' ) < div class= '' f-field '' > < textarea id= '' 9008 '' name= '' Logo '' > < /textarea > < /div > fields.filter ( field = > field.getElementsByName ( `` Logo '' ) ) | Javascript filter function - Trying to understand it properly |
JS | How do we initialize and create new multi dimension array ? Let 's imagine if I want to initialize a 4x4 multi dimension array and fill it with 0'sIdeally , in 2D arrays , we would dolet oned_array = new Array ( 10 ) .fill ( 0 ) ; // would create array of size 10 and fill it up with 0How would I do something like [ [ 0... | let matrix = new Array ( [ ] ) .fill ( 0 ) ; | Initializing and filling multi dimension array in javascript |
JS | I have a jQuery UI accordion that includes a right arrow for each header element . When the user clicks the header to display the content , the arrow changes to a down arrow . When the user clicks the header to hide the content the arrow changes back to it 's original form . My problem comes when the user clicks on an ... | var toggleState = true ; $ ( `` # wholesale section '' ) .on ( `` click '' , function ( ) { if ( toggleState ) { $ ( this ) .find ( `` .dropdown-arrow '' ) .html ( `` & # x25BC ; '' ) ; $ ( this ) .css ( `` background '' , `` # ececec '' ) ; } else { $ ( this ) .find ( `` .dropdown-arrow '' ) .html ( `` & # 9658 ; '' )... | Revert CSS if user clicks on another button |
JS | BackgroundI was writing some code to check if 2 arrays where the same but for some reason the result was true when expecting false . On closer inspection I found that where array values where undefined they were skipped.ExampleWhat I 've triedSo I spent some time trying to get the value in here correctly but the only t... | const arr1 = [ , , 3 , 4 ] const arr2 = [ 1 , 2 , 3 , 4 ] const result = arr1.every ( ( item , index ) = > item === arr2 [ index ] ) console.log ( result ) // true ( HOW ? ? ? ? ) | Why do map , every , and other array functions skip empty values ? |
JS | Is there a way to find all the elements with attributes that start with a particular string ? I am using Mootools framework and this is what I have tried : But it just outputs all the elements in the page.So is there a way to get all the elements in the page that have attributes that start with , data-media- ? | $ $ ( '* [ data-media-* ] ' ) ; | Is there a way to search for attributes that start with a certain string in HTML |
JS | I am trying to understand the difference of using the keyword `` this '' or rather what it represents in jQuery Vs an MVC framework like Backbone.Below are 2 code samples of each ; So in jQuery , we have In Backbone , we have code as ; Now I do understand that `` this '' refers to the DOM element in jQuery.I wanted to ... | $ ( `` # result '' ) .click ( function ( ) { $ ( this ) .html ( someval ) ; } ) var HandlebarsView = Backbone.View.extend ( { el : ' # result'initialize : function ( ) { this.template = Handlebars.compile ( $ ( ' # template ' ) .html ( ) ) ; } , render : function ( ) { var html = this.template ( this.model.toJSON ( ) )... | Meaning of keyword `` this '' in jQuery Vs MVC |
JS | How do I adjust Islamic hijri date using moment-hijri.js ? I 'm using this calendar and added moment-hijri.js to add Islamic hijri date . However , I want to give the users the option to change/modify/adjust the date . If I add the following line to drawDay function , the webpage crashes : | day = day.add ( -1 , 'iDate ' ) ; ! function ( ) { var today = moment ( ) ; function Calendar ( selector , events ) { this.el = document.querySelector ( selector ) ; this.events = events ; this.current = moment ( ) .date ( 1 ) ; this.draw ( ) ; var current = document.querySelector ( '.today ' ) ; if ( current ) { var s... | Adjust Islamic date using moment-hijri.js |
JS | During my NodeJS learning journey I found this sample code in a book ( NodeJS in Practice ) which uses streams to find some matches in data coming from another stream.And the code which uses the stream : Is n't it possible to lose some matches , if a match breaks in two chunks of data ? For example first chunk of data ... | var Writable = require ( 'stream ' ) .Writable ; var util = require ( 'util ' ) ; module.exports = CountStream ; util.inherits ( CountStream , Writable ) ; function CountStream ( matchText , options ) { Writable.call ( this , options ) ; this.count = 0 ; this.matcher = new RegExp ( matchText , 'ig ' ) ; } CountStream.p... | Is it possible for this code to lose some matches ? |
JS | I 'm attempting to write a function that combines two strings using recursion . My code is below but I do n't know why the function returns undefined especially when I console.log within the base case and it does not print undefined but instead the correct value . | var str3= '' '' function merge ( str1 , str2 ) { if ( str1.length==0||str2.length==0 ) { console.log ( str3 ) return str3 ; } else { str3=str3+str1.substring ( 0,1 ) +str2.substring ( 0,1 ) ; merge ( str1.substring ( 1 , str1.length ) , str2.substring ( 1 , str2.length ) ) } } merge ( `` AAA '' , '' BBB '' ) // -- > re... | Why does this recursive function return undefined ? |
JS | If I have the following Vue object , and myObj.myProp1 is changed , which watcher will be called first ? What determines the order and is there any way to manipulate the order ? When I tested it , the watcher pointing to the property was called first , but I want to make sure that it was n't a fluke and dependent on ot... | Vue { data : { myObj : { myProp1 : `` one '' , myProp2 : `` two '' } } , computed : { myProp1 : function ( ) { return this.myObj.myProp1 ; } } , watch : { myProp1 : function ( ) { alert ( `` myProp1 Changed '' ) } myObj : { handler : function ( ) { alert ( `` myObj Changed '' ) } , deep : true } } } | In Vue , which watcher will be called first ? A deep watch on an object , or a watch on a property of that object ? |
JS | Note : while the code in this question deals with functional programming/monads , etc. , I 'm not asking about functional programming ( nor do I think this question should have tags related to functional programming , etc. ) . Instead , I 'm asking about the use of JavaScript 's prototype.Code SourceI 'm watching Dougl... | function MONAD1 ( ) { var prototype = Object.create ( null ) ; // later removed function unit ( value ) { var monad = Object.create ( prototype ) ; // later moved monad.bind = function ( func , ... args ) { return func ( value , ... args ) ; } return monad ; } unit.lift = function ( name , func ) { prototype [ name ] =... | Why is a monad prototype required for Douglas Crockford 's monad demo code ? |
JS | This is a variation on a question asked so many times . Given any element , I want to be able to find any other element after it in the entire document . It can be a sibling but it could also be any other element that occurs afterward . For example , given the following markup , For the sake of this description , lets ... | < div > < p > Hello < /p > < div > < p > Foo < /p > < p class= '' bar '' > Bar < /p > < p > rawr ! < /p > < /div > < p > bop < /p > < input/ > < div > < p > Another < /p > < div > < span > something < /span > < p > deep ! < /p > < /div > < /div > < /div > < p > last < /p > $ ( '.bar ' ) .nextInDocument ( ' p ' ) ; // <... | Next element in *entire* document after certain element |
JS | I 'm trying to create an Angular custom pipe that translate a text to other language . All data are dynamic.Here 's my service : My Pipe : and on my HTML is very simple { { title | LanguageTranslate | async } } My problem is It keeps returning an undefined . The pipe is not waiting for the subscription to finish . | import { Http } from `` @ angular/http '' ; import { Injectable } from `` @ angular/core '' ; import { Observable , of } from `` rxjs '' ; import { map , filter , switchMap , catchError } from 'rxjs/operators ' ; import { Router } from ' @ angular/router ' ; import { environment } from '../../../../environments/environ... | How to use a Service that executes HTTP request inside an Angular Pipe |
JS | Let 's say I have to store customer information , and to manage two-way binding I 'll use $ scope here.So my doubt here is , which approach is better ? ORI 've been wondering about this because I have a large angular application and sometimes the scope watchers count goes beyond 1500 . I 'm using a chrome extension to ... | $ scope.firstname = `` foo '' ; $ scope.lastname = `` bar '' ; $ scope.cellno = `` 1234567890 '' ; $ scope.email = `` foobar @ example.com '' ; $ scope.customerDetailsObj = { } ; $ scope.customerDetailsObj.firstname = `` foo '' ; $ scope.customerDetailsObj.lastname = `` bar '' ; $ scope.customerDetailsObj.cellno = `` 1... | AngularJS - Which scope is better performance wise ? Object.key or Some Variable ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.