lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I have pasted all of my code to JSFIDDLEWhat my system should be able to do is create a house with a random ID and set a max capacity of inhabitants in the house . You can then create some people and and drag them on to the house . When 2 people are dragged on top of a house , the house will show a bounce effect and a ...
if ( this.aPeople.length == 2 ) { // TODO : Create a new Person setTimeout ( function ( ) { $ ( '.House ' ) .effect ( 'bounce ' ) ; } , 0 , function ( ) { } ) ; ( From line 212 ) var iDivHouseId = $ ( this ) .attr ( 'id ' ) ; $ ( ' # WindowDisplayHouseInfo ' ) .data ( 'current-elem-id ' , iDivHouseId ) ; ( on line 33 a...
How to target my randomly created ID
JS
I just posted this to a gist : https : //gist.github.com/2228570This behavior is odd , does anyone have an explanation ? This is a tough thing to google . It also makes no difference if you use out += or out = out +.EDIT : @ paislee made a JSFiddle that demonstrates how if doWhat is on a separate line , it behaves as e...
var out = `` ; function doWhat ( ) { out += ' < li > ' ; console.log ( out === ' < li > ' ) ; // at this point , out will equal ' < li > ' return `` ; } out += doWhat ( ) ; console.log ( out , out === ' < li > ' ) ; // I expect out to == ' < li > ' , but it 's actually an empty string ! ?
Can anyone explain this bizarre JS behavior concerning string concatenation ?
JS
I have a div as : Now within this div I want to place 20 elements , but dynamically it can grow upto 50 elements ( images ) also . I am using the following code to append these elements in a div , Now , the issue is , as the number of elements increase the elements are going out of div , and if I use the max-width and ...
< div id= '' div1 '' width= '' 100px '' height= '' 100px '' > < /div > var i = document.createElement ( `` img '' ) ; var d= document.getElementById ( `` div1 '' ) ; d.appendchild ( i ) ; i.setAttribute ( 'max-width ' , '100 % ' ) ; i.setAttribute ( 'max-height ' , '100 % ' ) ;
Appending the elements within div using appendchild attribute
JS
I 'm using the code of demo pie-basic ( Fiddle ) with the following values : and the problem is that it appears as 7.000000000000001 % instead of 7 % .How can I get a rounded value to appear ?
series : [ { type : 'pie ' , name : 'Browser share ' , data : [ [ 'Firefox ' , 34 ] , [ 'IE ' , 33 ] , [ 'Safari ' , 26 ] , [ 'Opera ' , 7 ] , ] } ]
Bug with highcharts pie-basic percent
JS
I have a very weird session issue - some odd cross session problem that has me baffled.Basically I have an express 3 app in which I have 2 , seemingly unrelated things - one is a standard contact form that someone can use to email me and the other is an API call to mailchimp to add subscribers when they place an order ...
var express = require ( `` express '' ) , flash = require ( `` connect-flash '' ) ; ... app.use ( flash ( ) ) ; ... app.use ( function ( req , res , next ) { var msgs ; msgs = req.session.messages || [ ] ; res.locals.messages = msgs ; res.locals.hasMessages = ! ! msgs.length ; req.session.messages = [ ] ; return next (...
Cross session issue with Express 3
JS
I 'm trying to create a reusable button directive which has a 'loading ' state . That is , when clicked it disables itself and shows an inline image to denote loading , which it then removes when complete . I do this by setting a scope variable in the click method and unsetting it , which changes the state of the butto...
< loading-button class= '' login '' data-ng-click= '' login ( ) '' text= '' Login '' toggle= '' loaded '' > < /loading-button > angular.module ( `` App.directives '' ) .directive ( `` loadingButton '' , function ( ) { return { restrict : `` E '' , replace : true , transclude : true , template : ' < button data-ng-click...
inheriting methods through directive expressions
JS
http : //jsperf.com/loops/67If you look , the following loop manages some insane benchmarks : It score ~700 million ops/sec in FF , ~20 mil in Chrome , and ~50mil in IE10 . The next fastest loop manages ~100k in FF , ~6k in IE10 and barely ~2k in Chrome.Why is it so fast ? I can see the obvious differences between the ...
var i=0 ; var v ; for ( i , v ; v = arr [ i++ ] ; ) { v ; }
Can anyone explain how this loop manages to benchmark so high ?
JS
I am using Angular JS ng-model to track the selected value of the select tag.here 's the example http : //jsfiddle.net/8853oxb1/3/If , I go to a dropdown by using a tab key and try to press `` I '' twice to select the second option starting with I , the dropdown value updates as expected , bu the ng-model just takes th...
function ControllerA ( $ scope ) { $ scope.optionsArray = [ 1,2,3,4,5 ] ; $ scope.optionsObject = { `` India '' : `` IN '' , `` Singapore '' : `` SG '' , `` Malaysia '' : `` MY '' , `` Indonesia '' : `` INDY '' } ; }
Angular JS ng-model not initiating properly for the first time
JS
I have one constructor function in my code . I have create instance of that constructor . In newly created instance I want to add value or function by using prototype method . But I getting error while doing this . Here is my code fiddle
function a ( ) { this.d=9 } a.prototype.one=1 ; a.prototype.two=2 ; var j= new a ( ) ; j.prototype.three=3 ; console.log ( j )
Add value using prototype in function instance
JS
Im using EsLint with VsCode.How can I have an error appear when trying to import a module that does n't exist ? for exampleShould underline in red.Does this require an eslint plugin ?
import foo from './this-path-doesnt-exist '
how can I get warnings when importing modules that do n't exist
JS
I 'm trying to find in the docs / understand this behavior for the following code : I saw this piece of code here : This is because ( from what i 've read ) : When the constructor returns an object , the new operator will yield the returned objectSo since f is a function - the new operator will yield the returned objec...
function f ( ) { return f ; } new f ( ) instanceof f ; //false var z = { a : 2 } ; function g ( ) { return z ; } var x = new g ( ) ; x === z ; //true
Constructor function returning object - documentation clarification ?
JS
Please check my code . The condition for checking the background color are not working.https : //jsfiddle.net/oL7tdL22/1/When we are alert background color , it 's working . But we can not match the colors .
$ ( function ( ) { $ ( `` .testing '' ) .each ( function ( ) { if ( $ ( this ) .css ( `` background-color '' ) == '' rgb ( 255,193,0 ) '' ) { alert ( `` found '' ) ; } else { alert ( `` not found '' ) ; } } ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js '' > < /script > < ...
Select an element with it 's background color is not working in jQuery
JS
It 's late in the evening here so I may not be functioning very well , but I found this piece of code and I ca n't seem to figure out why it 's used like this ( NOTE : I understand what it does , what I do n't understand is the meaning behind it ) .Self-executing anonymous functions are used to avoid pollution of the g...
( function ( ) { var narcissus = { options : { version : 185 , } , hostGlobal : this } ; Narcissus = narcissus ; } ) ( ) ;
Is there a meaning for this piece of code ?
JS
I convert user input urls to bbcode and append it to the textarea , but after you delete one of the lines I appended it wo n't append more ( but you could see the newly appended values in the firebug , really strange ) .Here 's my code : And here 's the jsfiddle : http : //jsfiddle.net/FpSsc/
$ ( function ( ) { $ ( `` .addUrl '' ) .click ( function ( ) { $ ( `` # addUrl '' ) .slideDown ( ) ; } ) $ ( ' # su ' ) .click ( function ( ) { if ( $ ( `` # u '' ) .val ( ) .length > 3 ) addUrl ( $ ( `` # u '' ) .val ( ) ) ; $ ( `` # u '' ) .val ( `` '' ) ; } ) $ ( `` input [ value=\ '' x\ '' ] '' ) .click ( function ...
append ( ) does n't work after previously appended contents deleted
JS
Is there any way to know if foo ( ) was called using a normal invoke or call/apply ? http : //jsfiddle.net/H4Awm/1/
function foo ( ) { console.log ( 'foo ' , this ) ; } foo ( ) ; foo.call ( { bar : 1 } ) ; foo.apply ( [ { bar : 1 } ] ) ;
How to check if a function is called using call/apply
JS
In order to access the data in an array I created an enum-like variable to have human readable identifiers to the fields.When I found out about Object.freeze I wanted to use this for the enum so that it can not be changed , and I expected the VM to use this info to its advantage.As it turns out , the tests get slower o...
var columns = { first : 0 , second : 1 } ; var array = [ 'first ' , 'second ' ] ; var data = array [ columns.first ] ; fixed Number : 12ms enum : 12ms frozenEnum : 85ms
Why is a frozen `` enum '' slower ?
JS
I have an update panel in a page for the users to specify an `` owner '' for an event . that owner would be a user in our active directory . The panel lets the user enter some text then click on a search button to find matching users in our Active Directory . When the user selects a user from the matching list , the ow...
< asp : UpdatePanel ID= '' OwnerUpdatePanel '' runat= '' server '' UpdateMode= '' Conditional '' ClientIDMode= '' Static '' > < ContentTemplate > < asp : TextBox id= '' OwnerNameTextbox '' runat= '' server '' class= '' form-control input-sm '' Width= '' 200 '' / > < asp : TextBox id= '' OwnerUsernameTextbox '' runat= '...
Javascript to blank textbox value wont work , but jquery does
JS
I searched and search on both SO and Google . But I can not find the rule to enforce this : NOT OKOKIt seems to not be object-property-newline or object-curly-newlineEdit : it also does n't seem to be brace-style .
const object = { methods : { } } const object = { methods : { } }
What is the ESLint rule to prevent newline after an object prop colon
JS
Right click menu correctly works with its functions.But the issue is sometimes it is not working properly.In my view if right clicked on the table row checked the checkbox correctly but after I unchecked and try checked again with right click its not working .
$ ( '.check ' ) .bind ( `` contextmenu '' , function ( event ) { event.preventDefault ( ) ; $ ( `` .custom-menu '' ) .finish ( ) .toggle ( 100 ) .css ( { top : event.pageY + `` px '' , left : event.pageX + `` px '' } ) ; } ) ; $ ( document ) .bind ( `` mousedown '' , function ( e ) { if ( ! $ ( e.target ) .parents ( ``...
Right click custom menu is not working properly
JS
Im kind of new to jquery and ajax and im wondering if someone could help me out ? I have php foreach loop that print out one input type = number and a button . The code below , creates a table with where each row show the item name , a box for the user to enter quantity and a button to sell the item.And this is my jque...
< div class=verktyg > < form action='sell_items.php ' method='POST ' id='ajax ' > < table class= '' inventory '' > < ? php foreach ( array_slice ( $ items , 2 ) as $ key = > $ value ) { if ( $ value > 0 ) { echo `` < tr > < td id='verktyg-first-td ' > '' . $ key . `` < /td > < td > '' . $ value . `` < /td > < td > < in...
Ca n't submit the right button for each input field [ multiple buttons and input fields in a single form ]
JS
I just did the funny regex crosswords at http : //regexcrossword.com/ - and found out I do n't understand what quantifying groups means , e.g . ( . ) + or ( . ) * Let me try at http : //ole.michelsen.dk/tools/regex.html , it offers the JavaScript and the PHP regex engine : The string to match against is `` Trololo ! ''...
JS , ( . ) + = > 0 : Trololo ! 1 : ! JS ' , ( . ) + = > 0 : Trololo ! PHP , ( . ) + = > 0 : Trololo ! 0 : ! JS , ( . ) * = > 0 : Trololo ! 1 : ! JS ' , ( . ) * = > 0 : Trololo ! PHP , ( . ) * = > 0 : Trololo ! 1 : 0 : ! 1 : JS , ( . ) { 5 } = > 0 : Trolo 1 : o JS ' , ( . ) { 5 } = > 0 : Trolo PHP , ( . ) { 5 } = > 0 : ...
Regex , group & quantifyer
JS
Is component an attribute of HTML5 or part of prototype.js ? I 'm not having any luck finding information online about this . I think component and attribute are too generic of terms to be searched well.Example ( from http : //flixster.rottentomatoes.com/ ) : Then take a look at the nav element and the li elements cont...
< li id= '' '' class= '' active '' component= '' NavigationButton '' > ... < /li >
Is component an attribute of HTML5 or a protoype.js thing ?
JS
So I have been struggling with how to test dynamic imports generally and in this case , especially in jest , I have been reading a lot on the internet but did not find anything concrete , so I thought about bringing the question up to centralize a decent solution.I have the following methods inside of a classMy questio...
class MyClass { successMethod ( ) { ... } errorMethod ( ) { ... } myMethod ( ) { return import ( './myFile.js ' ) .then ( ( ) = > this.successMethod ( ) ) .catch ( ( ) = > this.errorMethod ( ) ) ; } }
How to test dynamic imports ( then and catch ) with Jest
JS
I 'm from a C # background but am new to React and JS in general . I was wondering if there was a way to use lambda functions when declaring an array , for example : I 'm trying to make an array of React.Components with ascending values in index , and was hoping this would be a viable option .
this.state = { arr : Array ( 9 ) .fill ( ( i ) = > { < Foo index= { i } / > } ) , } ;
In ReactJS , can you use a loop in Array.fill ?
JS
Lets say I have object literal with a method : and the same object with metod defined in another way : What 's exactly a difference between in defining method field in two above examples ? I know about function hoisting and functions declarations can be used before they appear in code , but when defining function as ob...
const testObj = { method : function ( ) { console.log ( 'declaration ' ) ; } } const testObj = { method ( ) { console.log ( 'declaration ' ) ; } }
Difference between function declaration and function expression in object literal
JS
While doing a deep dive on array methods , I decided to take a look at the steps involved in the Array.sort method . Take a look at this code to reverse the order of an array in place : I get this output : The first two steps make sense , but look at the third : [ 2 , 1 , 1 , 4 , 5 ] .Why would this be the behavior whe...
let arr = [ ] ; for ( let i = 1 ; i < 6 ; i++ ) { arr.push ( i ) ; } arr.sort ( ( value1 , value2 ) = > { console.log ( arr ) ; console.log ( ` Comparing $ { value1 } : $ { value2 } ` ) ; return value2 - value1 ; } ) ; console.log ( arr ) ; [ 1 , 2 , 3 , 4 , 5 ] Comparing 1 : 2 [ 2 , 1 , 3 , 4 , 5 ] Comparing 1 : 3 [ 2...
What is going on in this intermediate stage of Array.sort ?
JS
I have two select controls.One is dependent on the other . For a simple example , let 's assume the first displays a list of cities , while the other displays a list of streets in each city.When the page initially loads , the select control displaying the streets is showing all the available streets . However , once th...
var ViewModel = function ( ) { var self = this ; var regionAndCityArray = [ { regionName : `` Europe '' , cities : [ { cityName : `` London '' , additionalUnimportantInformation : 100 } , { cityName : `` Paris '' , additionalUnimportantInformation : 200 } ] } , { regionName : `` North America '' , cities : [ { cityName...
Knockoutjs - lost two way binding to select value when using foreach instead of options
JS
I have just written this snippet of code.The first two expressions returns true but the 3rd expression returns false.I am not sure why it returns false , because as per the below image , it is supposed to return true.In the image you can notice Function.prototype 's __ proto __ property point to Object.prototype . Coul...
function Point ( x , y ) { this.x = x ; this.y = y ; } var myPoint = new Point ( 4,5 ) ; console.log ( myPoint.__proto__ === Point.prototype ) ; console.log ( Point.__proto__ === Function.prototype ) ; console.log ( Function.__proto__ === Object.prototype ) ;
What is the prototype of a Function object in Javascript ?
JS
I have an HTML table which have some data . I am converting that data into percentage to populate them into HTML table on UI.What I have done so far : Used the basic formula to calculate the percentage i.e ( no./total ) 100 it is giving me right result for header row i.e for one row.for second row I am applying the sam...
const data = [ { `` amount '' : 518212 , `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` JAYANAGAR '' } , { `` amount '' : 104801 , `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` MALLESHWARAM '' } , { `` amount '' : 138151 , `` billdate '' : `` 2018-08-04 '' , `` outlet '' : `` KOLAR '' } , { `` amount '' ...
Calculation of percentage giving wrong result
JS
I am not a really good JavaScript user but I can get things done with it . I am not proud of the code I have written in JavaScript , so I decided to change that . Here is my first step : I am trying create my own library for a project and the below is the initial structure.I used immediately invoked function expression...
window.fooLib = { } ; ( function ( foo ) { `` use strict '' ; foo.doSomeStuff = function ( param1 ) { console.log ( new AccommProperty ( param1 ) ) ; } //some internal function function AccommProperty ( nameValue ) { var _self = this ; _self.name = nameValue ; } } ( fooLib ) ) ;
The way of good scoping in JavaScript
JS
I tried the following in Chrome ’ s console : I do n't understand why it does that .
var r1 = new RegExp ( `` \\w '' ) ; // → /\w/var r2 = /\w/ ; // → /\w/r1 === r2 ; // → falser1 == r2 ; // → falser1.toString ( ) === r2.toString ( ) ; // → truer1.source === r2.source ; // → true
Why is ( new RegExp ( `` \\w '' ) === /\w/ ) false in JS ?
JS
Example : I want merge ( array1 , array2 ) to give me : Is there an easy way to do this ? EDIT : several people have answered without looking too closely at my problem , please be note that I want to match similar objects in each array and combine their properties into my final array . Keys are unique and there will on...
var array1 = [ { 'key':1 , 'property1 ' : ' x ' } , { 'key':2 , 'property1 ' : ' y ' } ] var array2 = [ { 'key':2 , 'property2 ' : ' a ' } , { 'key':1 , 'property2 ' : ' b ' } ] [ { 'key':1 , 'property1 ' : ' x ' , 'property2 ' : ' b ' } , { 'key':2 , 'property1 ' : ' y ' , 'property2 ' : ' a ' } ]
How do I merge an array of objects in Javascript ?
JS
I have a Rx.Observable.webSocket Subject . My server endpoint can not handle messages receiving the same time ( < 25ms ) . Now I need a way to stretch the next ( ) calls of my websocket subject.I have created another Subject requestSubject and subscribe to this.Then calling next of the websocket inside the subscription...
requestSubject.delay ( 1000 ) .subscribe ( ( request ) = > { console.log ( ` SENDING : $ { JSON.stringify ( request ) } ` ) ; socketServer.next ( JSON.stringify ( request ) ) ; } ) ; Stream 1 | -- -1 -- -- -- -2-3-4-5 -- -- -- -- -6 -- -- after some operation ... Stream 2 | -- -1 -- -- -- -2 -- -- 3 -- -- 4 -- -- 5 -- ...
RXJS Observable stretch
JS
I have got a Vue component where i can zoom in on an image and then move it around the container . When zoomed there is also a small viewport to show what part of the image is visible . However when moving the image around it is moving faster than the mouse , i 'm guessing this is due to using the scale transform.I als...
Vue.component ( 'test ' , { template : ' # template ' , data : function ( ) { return { loading : true , loop : true , speed : 8 , speedController : 0 , zoomEnabled : true , zoomLevels : [ 1 , 1.5 , 2 , 2.5 , 3 ] , zoomLevel : 1 , frame : 1 , images : [ ] , imagesPreloaded : 0 , reverse : false , viewportScale : 0.3 , v...
Drag image within container , not moving with mouse , slightly quicker
JS
I am trying to split the d attribute on a path tag in an svg file into tokens.This one is relatively easy : But this is also a valid d attribute : The tricky parts are letters and numbers are no longer separated and negative numbers use only the negative sign as the separator . How can I create a regex that handles thi...
d = `` M 2 -12 C 5 15 21 19 27 -2 C 17 12 -3 40 5 7 '' tokens = d.split ( / [ \s , ] / ) d = `` M2-12C5,15,21,19,27-2C17,12-3,40,5,7 '' tokens = pathdef.split ( / ( ? < =\d ) ( ? =\D ) | ( ? < =\D ) ( ? =\d ) / ) [ 'M ' , ' 2 ' , '-12 ' , ' C ' , ' 5 ' , '15 ' , '21 ' , '19 ' , '27 ' , '-2 ' , ' C ' , '17 ' , '12 ' , '...
What is the regex that properly splits SVG 'd ' attributes into tokens ?
JS
How does this code work ? The result is ‘ 1 2 4 3 ’
new Promise ( resolve = > { new Promise ( resolve1 = > { console.log ( 1 ) resolve1 ( ) } ) .then ( ( ) = > { console.log ( 2 ) } ) .then ( ( ) = > { console.log ( 3 ) } ) resolve ( ) } ) .then ( ( ) = > { console.log ( 4 ) } )
The javascript Promise problem that has bothered me all day
JS
I have a plugin extending an original module.It should only modify the module , when explicitly required.Problem : As soon as it is required once , the original module is modified forever , also for cases where the plugin is not a dependency.The order does n't matter here , it 's enough to require the plugin once.Examp...
define ( `` main '' , [ ] , function ( ) { return { opt : `` A '' } ; } ) ; define ( `` plugin '' , [ `` main '' ] , function ( obj ) { obj.opt = `` B '' ; } ) ; require ( [ `` main '' , `` plugin '' ] , function ( obj ) { console.log ( obj.opt ) ; // should log B } ) ; require ( [ `` main '' ] , function ( obj ) { con...
How to implement a plugin , that modifies the original module only when required ?
JS
Can anybody explain , why next js code rises two alert windows with 'string1 ' text rather than to rise the second with 'undefined ' text inside ? ? If both variables are described in the same scope..http : //jsfiddle.net/FdRSZ/1/Thanks
var a = 'string1 ' ; alert ( a ) ; var a ; alert ( a ) ; ​
Variables defined in global scope with identical names
JS
String.raw is very useful . For example : However , when the last character of the template string is \ , it becomes an syntax error . Uncaught SyntaxError : Unterminated template literalTentatively , I use this method.Can I write template string which last character is \ using String.raw ?
let path = String.raw ` C : \path\to\file.html ` let path = String.raw ` C : \path\to\directory\ ` let path = String.raw ` C : \path\to\directory\ ` .trimRight ( )
` String.raw ` when last character is ` \ `
JS
I would like to ask you to find the point , why the site -I 'm working on- is slow.the conditions of the problem : large row count ( so I think maybe the problem is related to this . ) there is ajaxing event ( I have tired to comment it out and the problem disappeared ) using not Mozilla ( this freeze effect appear in ...
$ ( ' # cikkek , # magic_bar ' ) .on ( `` change '' , '' select , textarea , input [ type ! =hidden ] '' , function ( event_object ) { if ( $ ( this ) .attr ( 'name ' ) == `` kijelolve '' & & ! $ ( this ) .parents ( ' # magic_bar ' ) .length ) return true ; var cikk_id = $ ( this ) .parents ( '.cikk ' ) .attr ( 'id ' )...
How is it possible , that ajaxing is much more slower in Chrome and IE than Mozilla ?
JS
I keep receiving the eslint error import/no-unresolved and am unsure as to how I fix it . I know this is related to babel , but I ’ m not sure how to get babel and eslint to play nice.My babel.config.js file : … and my .eslintrc.js fileThe issue occurs for every type of import : Any suggestions ? EDITI ’ ve created a r...
module.exports = { presets : [ [ ' @ babel/preset-env ' , { targets : { node : 'current ' } } ] , ' @ babel/preset-react ' ] , plugins : [ 'babel-plugin-macros ' , ' @ babel/plugin-syntax-dynamic-import ' , ' @ babel/plugin-transform-destructuring ' , [ ' @ babel/plugin-proposal-class-properties ' , { loose : true , } ...
eslint complaining about resolving paths
JS
Considering I am going to work with a larger team in the future , I 'm trying to teach myself some basic annotation and documentation principles for front-end languages . Currently I 'm working on JS.For the most part , I 'm using Google 's Style Guide as a go-to , but I still have some questions.Let 's say I have an a...
function initFunction ( src , wrapper ) { $ .getJSON ( src , { format : `` json '' } ) .done ( function ( data ) { var wrapper = $ ( wrapper ) , contents = callAnotherFunction ( $ ( data ) [ 0 ] ) ; // Populates the wrapper element . wrapper.append ( contents ) ; } ) .fail ( function ( jqXHR , textStatus , errorThrown ...
Questions on documenting JavaScript : JS types
JS
I 'm making a simple quiz ( in a style of one question at a time ) , this is the JS code : And it works but only once ! for the first question/answers . When I click on any of the button answers from the second question , nothing happens ! It does n't fade out and the third question never appears . What 's the matter ?...
$ ( document ) .ready ( function ( ) { var item1 = document.getElementById ( 'questionarea ' ) ; var item2 = document.getElementById ( 'answers ' ) ; var totalQuestions = $ ( '.questionarea ' ) .size ( ) ; var currentQuestion = 0 ; $ questions = $ ( '.questionarea ' ) ; $ questions.hide ( ) ; $ ( `` .btn-lg '' ) .click...
Jquery click method only works once in my Quiz
JS
I ca n't figure out how can I extract the value of an attribute in my objects and then calculate them.So I have as follow : Now I should get 3 objects . From here I want to get the value of each one like [ 200 , 18 , 100 ] and add them together so my const totalSpending will be 318 .
const data = [ { topUp : true , value : 200 } , { topUp : true , value : 18 } , { topUp : false , value : 20 } , { topUp : true , value : 100 } , ] const totalSpending = data.filter ( transaction = > transaction.topUp == true ) ;
How to extract the value of objects and calculate them ?
JS
I 've seen that in many cases inheritance in js can be implemented like soMy question is if someone can explain in detail why Object.create ( Organism ) is necessary and simply doing thisis not enough.Respectively the prototype chain looks likewithout object.create : Human.__proto__ - > Organism __proto__- > Objectwith...
function Organism ( age ) { this.age = age ; } Organism.prototype.growOlder = function ( ) { this.age = this.age + 1 } var org = new Organism ( `` 1000 '' ) ; function Human ( name , age ) { Organism.call ( this , age ) ; //this sets up the properties on the human object this.name = name ; } Human.prototype = Object.cr...
Different ways of inheriting
JS
There is a function in JavaScript which calculates the sum of some digits , however I do n't understand what this part ( [ ] . $ ) means : [ ] . $ - what is it ?
const sum = d = > d ! = [ ] . $ ? ` $ { d = [ ... ` $ { d } ` ] .join ` + ` } = $ { eval ( d ) } ` : `` [ ] . $
What does [ ] . $ mean in JavaScript ?
JS
I saw here the Array.prototype.forEach ( ) 's polyfill and I have a question about its implementation : Looking at line # 10 : why did they use Object ( this ) ? As I searched its usages I saw this : The Object constructor creates an object wrapper for the given value . If the value is null or undefined , it will creat...
/*1*/ if ( ! Array.prototype.forEach ) /*2*/ { /*3*/ Array.prototype.forEach = function ( fun /* , thisArg */ ) /*4*/ { /*5*/ `` use strict '' ; /*6*/ /*7*/ if ( this === void 0 || this === null ) /*8*/ throw new TypeError ( ) ; /*9*/ /*10*/ var t = Object ( this ) ; /*11*/ var len = t.length > > > 0 ; /*12*/ if ( type...
Javascript 's Object ( this ) usages in polyfills ?
JS
When you select a specific item in the dropdown , custom selection is hidden . Why ? In my options I have closeOnSelect : false ; Warning ! I use $ .fn.select2.amd.require . 'select2/dropdown/closeOnSelect ' Can not be deleted .
$ ( function ( ) { $ .fn.select2.amd.require ( [ `` select2/utils '' , `` select2/dropdown '' , `` select2/dropdown/attachContainer '' , 'select2/dropdown/closeOnSelect ' ] , function ( Utils , DropdownAdapter , AttachContainer , closeOnSelect ) { $ ( 'select ' ) .select2 ( { dropdownAdapter : Utils.Decorate ( Utils.De...
closeOnSelect : false not working in Select2 when using dropdownAdapter
JS
What 's an elegent way - purely functional , ideally - to transform ( reduce ? ) this array : Into this : The logic is that all elements should be joined based on their a property , and all b and c properties denote key/value pairs respectively that should be merged into the single object based on their shared a value ...
var in = [ { a : 1 , b : ' x ' , c : 'foo ' } , { a : 1 , b : ' y ' , c : 'goo ' } , { a : 2 , b : ' x ' , c : 'hoo ' } , { a : 2 , b : ' y ' , c : 'joo ' } ] var out = [ { a : 1 , x : 'foo ' , y : 'goo ' } , { a : 2 , x : 'hoo ' , y : 'joo ' } ]
Elegant array transformation in Javascript
JS
I have a form inside a modal that I use to edit a review on an item ( a perfume ) . A perfume can have multiple reviews , and the reviews live in an array of nested documents , each one with its own _id.I 'm editing each particular review ( in case an user wants to edit their review on the perfume once it 's been submi...
@ reviews.route ( `` /review '' , methods= [ `` GET '' , `` POST '' ] ) @ login_requireddef edit_review ( ) : form = EditReviewForm ( ) review_id = request.form.get ( `` review_id '' ) perfume_id = request.form.get ( `` perfume_id '' ) if form.validate_on_submit ( ) : mongo.db.perfumes.update ( { `` _id '' : ObjectId (...
Pre-populate current value of WTForms field in order to edit it
JS
I need to change the text color to red if the answer is ' 7 ' and to green if it 's '13 ' or '24 ' . I 've tried several different things but I ca n't seem to get it to work . I do n't know if someone knows what I 'm doing wrong , but any help would be appreciated .
do { var luckyNumber = prompt ( 'What is your lucky number ? ' , `` '' ) ; luckyNumber = parseInt ( luckyNumber , 10 ) ; } while ( isNaN ( luckyNumber ) ) ; if ( luckyNumber == 7 ) { document.write ( `` < p > Hey , 7 is my lucky number too ! < /p > '' ) .style.color = `` red '' ; } elseif ( luckyNumber == 13 || luckyNu...
Changing the text color with Javascript depending on the number
JS
Edit : I did n't realize the error messages are not even coming from ESLint but from something called [ js ] in Visual Studio Code . I 'd delete the question but it might help others also mistaking the [ js ] output for ESLint . Still curious to learn what sort of process this [ js ] thing is.I have been presented with...
The property `` parentNode '' does not exist for the type `` EventTarget '' . window.addEventListener ( 'keydown ' , event = > { const currentTag = event.target.parentNode.tagName ; /* ... */ } ) document.activeElement.click ( ) ; The property `` click '' does not exist for the type `` Element '' . const rows = this.ch...
How to configure ESLint for using e.g . event.target and element.parentNode ?
JS
I understand what this is doing , returning all the ' y ' items that are not the current one ... But , what is the concept called here with the brackets ? I would like to read up on what this is , syntax , etc .
myColl.y = [ y for each ( y in myColl.y ) if ( y ! = myThing.getY ( ) ) ] ;
What is this JavaScript construct : `` = [ y for each ... ] ''
JS
Please forgive me , I 'll do my best to describe what I am looking for . I do n't have a name for it , so it makes it that much more difficult.Looking at libraries such as Folktale and monet.js , I like being able to chain operations with map without null-checking or if statements , using e.g . Maybe , Either , Task.I ...
var result1 = function1 ( input ) ; if ( result1 ) { return result1 ; } var result2 = function2 ( input ) ; if ( result2 ) { return result2 ; } // and so on . Something ( input ) .map ( function1 ) .map ( function2 ) .result ( ) compose ( result , map ( compose ( function2 , function1 ) ) ( Something ( input ) ) import...
Name and existence of functor or monad to chain and terminate sequence of operations
JS
I am using Angular-Messages with Angular-Material v1.0.9 . I have an md-dialog inside which I have a form with fields created with ng-repeat : Angular-Messages are used to display form errors . The problem is that when I use both required and pattern messages , they are sometimes shown and sometimes not . It worked pro...
< form name= '' modal.dynamicForm '' flex= '' 80 '' layout= '' column '' > < md-input-container ng-repeat= '' field in modal.model.fields '' > < ng-form name= '' innerForm '' > < label > { { field.label } } * < /label > < input type= '' text '' ng-model= '' field.value '' name= '' { { field.name } } '' ng-pattern= '' f...
Angular-Messages sometimes are n't shown when used with Angular-Material
JS
With the release of Typescript 3.7 there is now support for Nullish Coalescing . However it seems like I am using it wrongly.. I have the following structure : Why does the ? ? operator behave differently when the index of index1 is 1 while the index of index0 is 0 . Both should return false since it 's ! == -1Playgrou...
type myType = { [ `` myKeys '' ] ? : Array < string > } let data : myType ; data = { } ; data [ `` myKeys '' ] = [ `` index0 '' ] ; console.log ( data ? . [ `` myKeys '' ] ? .indexOf ( `` index0 '' ) ) // 0 if ( data ? . [ `` myKeys '' ] ? .indexOf ( `` index0 '' ) ? ? -1 === -1 ) { // returns false } else { console.lo...
How to use Nullish Coalescing in Typescript
JS
In JavaScript , I can goI guess that raku has some chops in functional - and I wonder if someone can clarify the equivalent code ( see https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions )
const materials = [ 'Hydrogen ' , 'Helium ' , 'Lithium ' , 'Beryllium ' ] ; console.log ( materials.map ( material = > material.length ) ) ; // expected output : Array [ 8 , 6 , 7 , 9 ]
What is the raku equivalent of the JavaScript arrow function ?
JS
While testing some JavaScrpt code in IE8 I 'm experiencing some strange behaviour when doing a simple for..in loop : Outputs : Which includes the Array prototype functions , right ? That 's definitely not the way it should work . Why is that ? Btw , it works of course when changing the loop to for ( var key=0 ; key < c...
var categories = [ 'for ' , 'bar ' , 'steam ' ] ; for ( var key in categories ) { console.log ( key ) ; } 012forEachmapfilterreduceindexOfend
Why does for ... in loop iterate through function names
JS
I 'm trying to get https : //codepen.io/SpacecaseArtist/project/editor/DQWYxo onto my local machine to play around with it . I clicked export at the bottom right , and downloaded the zip . I extracted the zip into a folder , and then opened index.html on my browser . When I open it , I 'm greeted with a scrollable , bl...
< script src= '' //s3-us-west-2.amazonaws.com/s.cdpn.io/138941/draggble.min.js '' > < /script > < script src= '' //s3-us-west-2.amazonaws.com/s.cdpn.io/138941/teenmax.min.js '' > < /script > < script src= '' //s3-us-west-2.amazonaws.com/s.cdpn.io/138941/waypoints.min.js '' > < /script > < script src= '' //s3-us-west-2....
Problems running codepen project on local machine
JS
I 'm new to programming and I wanted to develop my skills by working on a small project.I am creating a Sudoku app , using HTML/JavaScript . I have a large number ( 81 ) of 'div ' elements in HTML , and I want to assign content to them using by changing their innerHTML . Using the two for loops , I go through all 81 va...
function assign_cell ( flag , arr1 , arr2 ) { if ( flag === 1 ) { arr1.innerHTML = puzzle_inc [ arr2 ] ; } else if ( flag === 2 ) { arr1.innerHTML = null ; } else { alert ( `` Error in function assign_cell ( ) '' ) ; } } for ( var i = 0 ; i < 9 ; i++ ) { for ( var k = 0 ; k < 9 ; k++ ) { var a = counter ( ) ; var x = `...
How do I convert a string to an object
JS
Ill just awnser the first question ... Why IE5 you wonder , Because its on a Windows CE device that im working with so im limited to use IE5 . The application that i 've made uses a webpage with a couple of elements . I have two textfields and one list or < select > I want to transfer the value of one textbox to the li...
< tr > < td > Locatie : < /td > < td > < input type= '' text '' id= '' one '' onkeyup= '' CheckOne ( ) '' name= '' locatie '' value= '' { locatie } '' / > < /td > < /tr > < tr > < td > Bonregel : < /td > < td > < input type= '' text '' name= '' bonregel '' id= '' two '' onkeyup= '' CheckTwo ( event ) '' / > < /td > < /...
adding items to < select > in IE5
JS
thanks for your time.I was learning an Fibonacci function and one of the answer is below : As the arguments.callee is forbidden in strict mode after ES5 , so I replace it with a function name . After which , I saw the i + 1 part , and I replace it with an i++ , which turns out too much recursion.After a few debug , I f...
function fibonacci ( n ) { return ( function ( a , b , i ) { return ( i < n ) ? arguments.callee ( b , a + b , i + 1 ) : a ; } ) ( 1 , 1 , 1 ) ; } console.log ( fibonacci ( 51 ) ) function x ( n ) { return ( function y ( a , b , i ) { return ( i < n ) ? y ( b , a + b , i++ ) : a ; } ) ( 1,1,1 ) } console.log ( x ( 51 )...
Javascript i++ too much recursion , i+1 ok in tail recursion
JS
What is the difference betweenandin JavaScript ? Both convert a string to number ( int or float ) . They behave differently from parseInt and parseFloat . But is there any difference between these two lines ?
a *= 1 ; a = +a ;
What is the difference between a *= 1 and a = +a ?
JS
I have strange error that sometimes occurs on my WinJS app on the Windows Phone 8.1 512MB RAM Emulator . I could n't reproduce it on other Emulator instances or on device.The execution runs through the promise chain and finishes the following return statement : After that nothing happens.I set breakpoints at all three ...
return ( currentUpload = uploadOperation.startAsync ( ) ) ; var currentUpload ; // global function uploadFile ( localFullPath , headers , serverUrl ) { var fileUri = new Windows.Foundation.Uri ( 'ms-appdata : ///local ' + localFullPath ) , uploader = false ; try { uploader = new Windows.Networking.BackgroundTransfer.Ba...
WinJS : Promise chain sometimes sticks after usage of BackgroundUploader class on 512MB WinPhone8.1 Emu
JS
I hope you can help me with my problem , because it seems quite odd to me.On my website I 'm using some Bootstrap alerts to inform the users in case of success or errors.After some time the alert is hidden : My problem is that , because of the alert being hidden , all buttons that are behind the alert are still not cli...
setTimeout ( function ( ) { $ ( `` # alertLogged '' ) .removeClass ( `` show '' ) ; } , 5000 ) ; < div class= '' hide fade text-center '' role= '' alert '' id= '' alertLogged '' > < /div > .alert : not ( .show ) { pointer-events : none ; } alert ( `` TEST '' ) ; $ ( `` # alertLogged '' ) .fadeIn ( 1000 ) .delay ( 5000 ...
Hidden Bootstrap notification blocks buttons
JS
I have the next array : What I want to do is to remove an element from the array where two values match , for example , if id = 24 and tipo = school , the array at the position 2 , must be removed , I have this function to find the array key by the values : The function does not work correctly , in some cases it return...
0 : { id : `` 10 '' , tipo : `` work '' } 1 : { id : `` 11 '' , tipo : `` work '' } 2 : { id : `` 24 '' , tipo : `` school '' } 3 : { id : `` 9 '' , tipo : `` work '' } 4 : { id : `` 25 '' , tipo : `` school '' } function eliminarElementoArray ( array , val1 , val2 ) { for ( var i=0 ; i < array.length ; i++ ) { if ( ar...
Remove an element from an array by field names
JS
Having a weird issue , I am testing webfontshere is my cssI am using the font throughout my application and have no issue expect on one page.I have a fair amount of JS on this page , the JS is positioning the elements and setting the height of the right div.On some requests the webfont is not loading ( at all ) e.g.I c...
@ font-face { font-family : 'Open Sans ' ; font-style : normal ; font-weight : 400 ; src : local ( 'Open Sans ' ) , local ( 'OpenSans ' ) , url ( /assets/opensans.woff ) format ( 'woff ' ) ; }
@ font-face fails to load on some requests , due to javascript ?
JS
I want to implement the following : First , put a link.When clicked , this link should trigger an action in my current route ( i.e . collapsing a panel or something like that ) BUTWhen user right clicks and selects `` new tab '' , this same link should open a separate route ( and also not trigger any action in current ...
< span { { action 'collapsePanel ' } } > { { # link-to 'otherRoute ' } } Some text { { /link-to } } < /span >
Having a link trigger only an action on click , but opening a different route on new tab click
JS
Is there a more explicit way of checking whether a function was called from within Window than if ( typeof this.value == `` undefined '' ) in the code below ? So that it is apparent that I am checking against Window , something like : if this.name === `` Window '' .
function get_caller ( ) { if ( typeof this.value == `` undefined '' ) { console.log ( 'function get_caller called from window ' ) } else { console.log ( 'function get_caller called by button press ' ) } } btn.addEventListener ( 'click ' , get_caller ) get_caller ( ) < button id= '' btn '' > Get caller < /button >
Explicit way to check whether a function was called from within the Window
JS
If I set the css animation to `` element '' , it 's fine . If the Css animation is not available , how does it function fire like a zero seconds animation in the ES5 ? Reply for @ Anurag Srivastava , Am I wrong idea or do I have the following code wrong ? Either way , the return value is `` '' .
function run ( ) { ... } element.addEventListener ( 'animationend ' , run ) ; var el1 = document.getElementById ( `` notAnimation '' ) ; console.log ( el1.style.animation ) ; var el2 = document.getElementById ( `` onAnimation '' ) ; console.log ( el2.style.animation ) ; div { padding : 10px ; margin : 20px ; } # notAni...
How fire `` animationend '' event , when I ca n't set a CSS animation ?
JS
I am new in angular2 . So , please bear with me . I know this is a noob question for some.component.tsWhat I have tried so farIn angular1 , we can get the value of those using $ scope . Any help would be appreciated . Thanks .
< form > < label class= '' input-group '' > < p > View By < /p > < select [ ( ngModel ) ] = '' balance.viewBy '' name= '' viewBy '' > < option > 1 < /option > < option > 2 < /option > < option > 3 < /option > < option > 4 < /option > < option > 5 < /option > < /select > < /label > < label class= '' input-group '' > < p...
How to get form input , select value using Angular Binding ?
JS
So I have a problem and it 's most likely because I still do n't get JavaScript ... Cytoscape has their own 'this ' and Polymer has their 'this'But in order to update my < div > { { node.label } } < /div > I have to be able to do this.node.label = `` N42 '' // Polymer but I ca n't do it in the cy.on ( 'click ' , 'node ...
< div id= '' labelFld '' > { { node.label } } < /div > < div id= '' measureFld '' > { { node.measure } } < /div > < div id= '' timesignatureFld '' > { { node.time_signature } } < /div > < div id= '' voiceFld '' > { { node.voice } } < /div > < div id= '' beatFld '' > { { node.beat } } < /div > < div id= '' meventFld '' ...
Polymer this and Cytoscape this
JS
I was reading this article HERE , which speaks about how can you use reduce with promises and in the end the following snippet is shown : So without changing much of the code , i made the following demo : But i still do n't understand , since reduce is simplistically just a forEach loop and inside reduce we are relying...
const tasks = getTaskArray ( ) ; return tasks.reduce ( ( promiseChain , currentTask ) = > { return promiseChain.then ( chainResults = > currentTask.then ( currentResult = > [ ... chainResults , currentResult ] ) ) ; } , Promise.resolve ( [ ] ) ) .then ( arrayOfResults = > { // Do something with all results } ) ; const ...
How does an array of promises work exactly with reduce ?
JS
I am having strange issue in my rich pin save button . Its truncating title and tags while creating new PINs into Pinterest.I have used same OG data given in pinterest developer site.Reference : https : //developers.pinterest.com/docs/rich-pins/articles/ ? Any suggestion or help on this will be much appreciated . Thank...
< head > < meta name= '' p : domain_verify '' content= '' SITE_VERIFICATION_CODE '' / > < meta property= '' og : type '' content= '' article '' / > < meta property= '' og : title '' content= '' sample title '' / > < meta property= '' og : description '' content= '' sample content '' / > < meta property= '' og : url '' ...
Pinterest Rich Pins Save : Truncating Title and tags
JS
I 'm having trouble figuring out scoping within ng-repeat . I want to create chained selects , and I want to keep each row in the ng-repeat to exist separately in separate scopes . Currently changing the first select in any of the rows will change the second selects in all of the rows . ( Real life example : I have a f...
< div ng-controller= '' MyCtrl '' > < div ng-repeat= '' row in rows '' > < select ng-options= '' option.value as option.title for option in options1 '' ng-model= '' row.select1 '' ng-change= '' updateSelect2 ( row.select1 ) '' > < /select > < select ng-options= '' option.value as option.title for option in options2 '' ...
chained select within ng-repeat
JS
I 'm doing a tutorial on lexical scope handling by Typescript and I 've come across the use of a function which I have never seen before . Which looks like an empty function in a forEach statement . In typescript it looks like this : In javascript it looks like : I 've never seen a function used like this . Can someone...
fns.forEach ( fn= > fn ( ) ) ; fns.forEach ( function ( fn ) { return fn ( ) ; } ) ; var fns = [ ] ; for ( var i=0 ; i < 5 ; i+=1 ) { fns.push ( function ( ) { console.log ( i ) ; } ) } fns.forEach ( fn= > fn ( ) ) ; var fns = [ ] ; for ( var i = 0 ; i < 5 ; i += 1 ) { fns.push ( function ( ) { console.log ( i ) ; } ) ...
Typescript/JavaScript forEach
JS
I 'm trying to create a loading circle from an image in HTML5 canvas.Here 's the result I expect when percentage is at 50 % : here 's what I 've done after a lot of tests : ( the blue stroke is just to see the circle , it 'll be removed after ) as you can see , the result here is n't as exceptedWhat is wrong ?
var img = new Image ( ) ; img.onload = draw ; img.src = `` http : //i.imgur.com/HVJBZ1L.png '' ; var canvas = document.getElementsByTagName ( `` canvas '' ) [ 0 ] ; canvas.width = 500 ; canvas.height = 500 ; var ctx = canvas.getContext ( `` 2d '' ) ; function draw ( ) { ctx.globalAlpha = 0.5 ctx.drawImage ( img , 0 , 0...
html5 canvas loading circle image
JS
I am using bluebird library over memcached.this function does not call success callback in second parameter so seems like .then ( res ) function does not getting called . is there any way for me to handle uncalled success event ?
memcached.set ( 'foo ' , 'bar ' , 10 , function ( err ) { /* stuff */ } ) ; Promise.promisifyAll ( memcached ) ; memcached.setAsync ( hashedCacheKey , obj ) .then ( function ( res ) { resolve ( res ) ; } ) .catch ( function ( err ) { reject ( err , null ) ; } ) ;
using bluebird with undefined success callback function
JS
When using splice or push methods the array passed to a function is being modified . So I am trying to understand what is happening when using assignment operator , why it 's not changing the array ? is it creating the local var of the passed array ? Any help will be appreciated !
var arrN = [ 1 , 2 , 3 ] ; function init ( arr ) { arr = [ ] ; console.log ( arrN ) //output [ 1 , 2 , 3 ] , expect [ ] } init ( arrN ) ;
Assign value to the array passed to a function
JS
I have next link that lets users navigate through a list of URL ( stored in array ) . When a user clicks next , I want the link href and anchor to be updated for the next website in my array . The way I 've tried so far , it link skips one URL each time , and I have and idea why , it has to do with the previous click e...
< ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd '' > < html > < head > < script type= '' text/javascript '' src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { var item...
How do I make a link update itself when its clicked ?
JS
I was answering a question related to Array.reduce by using Math.max in my example and I found something that I do n't understand : This works : But if I try something like this : It returns NaN.I thought that the context was the reason , so I wrote the following : But it worked as expected ! What am I missing ? MDN sa...
let values= [ 4,5,6,77,8,12,0,9 ] ; let max=values.reduce ( ( acc , curr ) = > Math.max ( acc , curr ) ,0 ) ; console.log ( max ) ; let values= [ 4,5,6,77,8,12,0,9 ] ; let max=values.reduce ( Math.max,0 ) ; console.log ( max ) ; let max=Math.max ; console.log ( max ( 2,5 ) ) ;
Why using Math.max as a parameter does not work on this scenario ?
JS
I know you can do the following in javascript to toggle a boolean in a one liner . but is this also possible with a string ? i know it can be done by some if statements . But is it possible to do it in a oneliner ? something like this : If it is not clear what i am asking let me know so i can improve the question .
var toggle = false ; if ( true ) toggle ! = toggle ; var string_toggle = `` CAT '' ; if ( true ) `` CAT '' = `` ESP '' || `` ESP '' = `` CAT '' ;
toggle boolean value equivalent for strings
JS
I 'm trying to make a little menu , that opens when you click on it , and closes when you click outside it . I managed to do that , mostly . The button I press to open the menu has some padding , and when I click specifically on the padding the menu that opens has all it 's text selected , which is weird , and I do n't...
function outside_function ( event ) { var outside = event.target ; outside.classList.remove ( `` outside '' ) ; var menu_list = document.getElementById ( `` menu-list '' ) ; menu_list.classList.remove ( `` menu-list-open '' ) ; event.stopPropagation ( ) ; } var outside = document.getElementById ( `` outside '' ) ; outs...
I 'm having trouble understanding why a single click in my code is selecting text
JS
Consider this python codeit prints 1 2 3 -- - 4 5 , because the iterator it remembers its state across the loops . When I do seemingly the same thing in JS , all I get is 1 2 3 -- - . What am I missing ?
it = iter ( [ 1 , 2 , 3 , 4 , 5 ] ) for x in it : print x if x == 3 : breakprint ' -- -'for x in it : print x function* iter ( a ) { yield* a ; } it = iter ( [ 1 , 2 , 3 , 4 , 5 ] ) for ( let x of it ) { console.log ( x ) if ( x === 3 ) break } console.log ( ' -- - ' ) for ( let x of it ) { console.log ( x ) }
for..of and the iterator state
JS
In Stoyan Stefanov 's book Object-Oriented javascript , on page 103 he has the following . However when I try this , I get a different result with h instanceof Object . Am I missing something , has something in JS changed since or is this an error in the book .
> > > function Hero ( ) { } > > > var h = new Hero ( ) ; > > > var o = { } ; > > > h instanceof Hero ; true > > > h instanceof Object ; false //true in Google Chrome > > > o instanceof Object ; true
instanceof - javascript inconsistency in Object-Oriented javascript by Stoyan Stefanov
JS
The simple version of this question is : Why is there an undefined error in the 3rd example from the snippet below ? Intuition why it should workThe default value should , it seems , be taken from the `` outer '' a variable , ie , the one whose value is 1 . The first test shows that `` shadowing '' works with lexical s...
var a = 1 ; var b = 100 ; function defaultParamTest1 ( a ) { console.log ( a + 1 ) ; } function defaultParamTest2 ( a = b ) { console.log ( a + 1 ) ; } function defaultParamTest3 ( a = a ) { console.log ( a + 1 ) ; } defaultParamTest1 ( ) ; // WORKS ! = > NaN , since function a `` shadows '' outer a.defaultParamTest2 (...
Why ca n't a default parameter and function parameter have the same name ?
JS
I discovered that ES2015 classes prevent setting ( redefining ) their prototype.It is often claimed that ES2015 classes are just `` syntactic sugar '' on top of ES5 constructor functions and prototype based inheritance.But this is a difference in behavior ... Is this behavior part of the ES2015 specification ? I did no...
function Pet ( ) { } Pet.prototype.eat = ( ) = > { console.log ( 'Pet is eating ... ' ) ; } Pet.prototype = { eat : function ( ) { console.log ( 'Pet is REALLY eating ... ' ) } } ; const pet = new Pet ( ) ; pet.eat ( ) ; // - > Pet is REALLY eating ... console.log ( Object.getOwnPropertyDescriptor ( Pet , 'prototype ' ...
ES2015 Classes prevent setting the prototype
JS
I have simple controller code : JS HTMLFrom snippets of code you can see that I try to change $ scope.showErrorAlert value.However it does n't work , value changes but not showErrorAlert.Can anybody tell me why and how to make it work , please ? Thank you
$ scope.showErrorAlert = false ; $ scope.switchBool = function ( value ) { value = ! value ; } ; < div class= '' alert alert-error '' ng-show= '' showErrorAlert '' > < button type= '' button '' class= '' close '' data-ng-click= '' switchBool ( showErrorAlert ) '' > × < /button > < strong > Error ! < /strong > { { error...
Why scope value ca n't be changed from HTML by using `` switch '' technique ?
JS
I have a nested loop that will work most of the time , but for one particular case it does not run at all.Here is the value that is failing : 1 , 3-5 , 7-10 , 22 JS code : When the failing value is entered , this is the result : I ca n't figure out why the 7-10 part is being skipped . Any help or explanation is greatly...
document.getElementById ( `` myButton '' ) .addEventListener ( `` click '' , function ( ) { document.getElementById ( `` msg '' ) .innerHTML = `` '' ; // Get the short list var list = document.getElementById ( `` myIn '' ) .value ; var sublists = list.split ( `` , `` ) ; var Range = [ ] ; var result = `` '' ; var start...
Why is this js loop being skipped in one instance ?
JS
Here is my Task implementation ( i.e . a sort of Promise but complying with the monad laws and cancelable ) . It works rock solid : However , I have no idea how to implement awaitAll , which should have the following traits : it either resolves with an array of results of the individual Tasksor it rejects immediately w...
const Task = k = > ( { runTask : ( res , rej ) = > k ( res , rej ) } ) ; const tAp = tf = > tk = > Task ( ( res , rej ) = > tf.runTask ( f = > tk.runTask ( x = > res ( f ( x ) ) , rej ) , rej ) ) ; const tOf = x = > Task ( ( res , rej ) = > res ( x ) ) ; const tMap = f = > tk = > Task ( ( res , rej ) = > tk.runTask ( x...
How to implement the equivalent of Promise.all for my Task implementation ?
JS
Let 's say I want to detect support for notifications ( http : //notifications.spec.whatwg.org/ ) in a JavaScript library.I can use window.Notification ! == undefined . But what if the users of the library ( or another library ) also have some kind of global Notification object defined for completely different purpose ...
ret [ toString ] = function ( ) { return 'function Notification ( ) { [ native code ] } ' ; } ;
What is the most reliable approach to detecting browser feature support ?
JS
JavaScript only has function scope . Thus , variables declared in for loops are visible for the entire function.For example , When we have multiple for-loops , this opens the question of how we handle the variables in these other for loops.Do we use a different variable ? Or do we use the same variable but just assign ...
function foo ( ) { for ( var i = 0 ; i < n ; i++ ) { // Do something } // i is still in scope here } for ( var i = 0 ; i < n ; i++ ) { } for ( var j = 0 ; j < n ; j++ ) { } for ( var i = 0 ; i < n ; i++ ) { } for ( i = 0 ; i < n ; i++ ) { } var i ; for ( i = 0 ; i < n ; i++ ) { } for ( i = 0 ; i < n ; i++ ) { } for ( v...
What is the most idiomatic way to handle variables declared in multiple for loops ?
JS
Just tried this in my browser 's console : What 's going on here ! ? Edit : I 'm talking about { } + [ ] ( object first ) which is different from [ ] + { } ( array first ) , the latter always returns 0 . Spacing ( { } + [ ] vs { } + [ ] ) does n't seem to matter
! ! 0 //= > false { } + [ ] //= > 0 ! ! ( { } + [ ] ) //= > true
Why is it that ! ! 0 is false and { } + [ ] is 0 but ! ! ( { } + [ ] ) is true ?
JS
Hi can someone explain why in backbone example app ( http : //backbonejs.org/examples/todos/index.html ) in remaining ( ) function , is called using apply ( this.without.apply ( this , this.done ( ) ) ; ) and not this.without ( this.done ( ) ) Thank You ! # UpdateDebugger output
// Filter down the list of all todo items that are finished.done : function ( ) { return this.where ( { done : true } ) ; } , // Filter down the list to only todo items that are still not finished.remaining : function ( ) { return this.without.apply ( this , this.done ( ) ) ; } , this.without ( this.done ( ) ) [ child ...
Backbone example app and javascript apply
JS
In my javascript objects i found myself writing this : It seems it 's the only way to pass member variables to external functions ... That does n't work , I have to copy the object into a member variable and pass the new object ( and replace all this with this_object ) This feels ugly . Is there a `` better '' or `` cl...
this_object = this ; google.maps.event.addListener ( this.marker , 'click ' , function ( ) { this.info_window.setContent ( 'Chicago marker ' ) ; this.info_window.open ( this.map , this.marker ) ; } ) ;
Is there a better method than setting a variable to this ?
JS
This works perfectly fine , but for future reference I would like to know if there is a better way to do this.I 'm open to using jQuery if it would help .
document.getElementsByTagName ( 'h1 ' ) [ 0 ] .style.display = 'none ' ; document.getElementsByTagName ( `` p '' ) [ 0 ] .style.display = 'none ' ; document.getElementsByTagName ( `` p '' ) [ 1 ] .style.display = 'none ' ; document.getElementsByTagName ( `` ul '' ) [ 0 ] .style.display = 'none ' ; document.getElementsB...
Any better way to hide multiple elements at once ?
JS
I noticed in some legacy code the following pattern : After some research , this appears to be a very old technique for hiding the contents of script elements from the DOM when the browser did not support the < script > element . More information can be found here . My concern is this : why does < ! -- not throw a Synt...
< script > < ! -- // code // -- > < /script >
Why does < ! -- Not Throw a Syntax Error ?
JS
Is there a way to determine if a function is running in document ready ? I mean something like this : ( It is also possible my ( very beginner ) concept is not optimal , so I write what I am trying to achieve : I would like to create a reusable object , what can instantiated in multiple instances within a page ( hopefu...
function myfunction ( ) { var isinside = // ... what to write here ? if ( isinside ) { } }
Is there a way to determine if a function is running in document ready or not ?
JS
Hi I seem to be having a little issue with some jQuery code but I cant seem to get it to work , I want to add CSS style based on the content starting with 1.6 : jQuery as follows : based on the code it should just style the 'strong ' element only .
< p > < strong > 1.6.1 < /strong > this is some content < /p > $ ( ' p strong : starts-with ( 1.6 ) ' ) .css ( 'background-color ' , ' # 3c763d ' ) ;
Target element which content starts-with
JS
Are there any issues in having a large number ( say 50 ) of script tags in an html file . Does it cause any performance issues in page rendering times ? I have a section on my page that 's pulling a geolocation point and putting this into an array for use on a google map . I could create a separate query for just the g...
< script type= '' text/javascript '' > points [ { count } ] = [ { job_latitude } , { job_longitude } , ' { title } ' ] ; < /script >
Are there any performance issues in having a large number of script tags in your html ?