lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I 've been broadening my horizons learning javascript and I have a quick question about style . I used to use a literal notation when making my code like this.but I would have problems accessing certain variables within the object , it would claim a few did n't exist nomatter what . So I started using this , cause it w...
var foo = { bar : function ( ) { /*something*/ } } ; var foo = { } ; foo.bar = function ( ) { /*something*/ } ;
Good Javascript code
JS
I 've created a simple JavaScript application using AngularJS.I 'm using npm and Bower to manage my dependencies , Gulp to automatise my tasks and I want to use the CommonJS ' module.exports/require ( ) to tie everything up together : I decided to go for Browserify to bundle this all up . There 's my very empty and cle...
`` browser '' : { `` angular '' : `` ./bower_components/angular/angular.min.js '' } , '' browserify '' : { `` transform '' : [ `` browserify-shim '' ] } , '' browserify-shim '' : { `` angular '' : { `` exports '' : `` angular '' } } 'use strict ' ; var angular = require ( 'angular ' ) ; angular.module ( 'MyApp ' , [ ] ...
Browserify overrides its own configuration when browsing a folder that contains a package.json ?
JS
In a simple HTML page , I used the following vueJs code . I need to click on the button which will insert a checkbox and a text into the DOM.My code follows : And the javascript part is : When I run the page , I find the following error message in console : [ Vue warn ] : Invalid handler for event `` click '' : got und...
< template id= '' add-item-template '' > < div class= '' input-group '' > < input v-model= '' newItem '' placeholder= '' add shopping list item '' type= '' text '' class= '' form-control '' > < span class= '' input-group-btn '' > < button @ click= '' addItem '' class= '' btn btn-default '' type= '' button '' > Add ! < ...
VueJs : use method from root element inside a component
JS
I 've lately browsed js code and the following syntax keeps coming up : This is unfamiliar syntax to me . Is it only to define two names for the same function ? If so , why not only define it as bar.bi = function ( ) ?
var foo = bar.bi = function ( ) { ... }
Purpose of var a = b.c = function ( ) { } syntax
JS
The problem : I have a jQuery heavy page that has a built in admin interface . The admin functions only trigger when an admin variable is set . These functions require a second library to work properly and the second file is only included if the user is an admin when the page is first created . The functions will never...
< script type= '' text/javascript '' src= '' script.js '' > < /script > < script type= '' text/javascript '' src= '' user.js '' > < /script > admin = false ; // Assume this $ ( `` .something '' ) .dblclick ( function ( ) { if ( admin ) adminstuff ( ) ; // Implemented in admin.js ( not included ) else userstuff ( ) ; } ...
A question about referencing functions in Javascript
JS
Is it possible to use es6 constructor instructions on another instance by changing the `` this '' context ( call , apply or other ) ? This is possible using es5 `` classes '' . Here is a small example of what I mean : Edit : My question has nothing to do with the new keyword . The answer I 'm looking for is how to run ...
function ES5 ( ) { this.foo = 'foo ' ; } class ES6 { constructor ( ) { this.bar = 'bar ' ; } } var a = new ES6 ( ) ; ES5.call ( a ) ; console.log ( a.foo + a.bar ) ; //foobarvar b = new ES5 ( ) ; //Reflect.construct ( ES6 ) ; ? ? ES6.call ( b ) ; //TypeError : Class constructor ES6 can not be invoked without 'new'conso...
How to use es6 constructor instructions with a different context
JS
I am trying to make my own custom input autocomplete API using Jquery and bootstrap 4.I want to show a preview of the list items text in the input filed whenever they are selected . I was able to do that by changing the value . However it was not what I wanted .My AutocomleteWhat I wantI want a preview of the text in t...
< ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' stylesheet '' href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css '' > < ! -- jQuery library -- > < scrip...
How do I add a preview text to my custom built autocomplete ?
JS
I have promise objects which need to work synchronize . For example second promise should n't work before first one is done . If first one rejects first one has to be executed again.I have implemented some examples.This one works well.call getVal , wait 2000ms , return , i++ , again call getVal ... ..But I need to cont...
getVal ( ) { return new Promise ( function ( resolve , reject ) { setTimeout ( function ( ) { resolve ( 19 ) } , 2000 ) ; } ) ; } async promiseController ( ) { for ( var i =0 ; i < 5 ; i++ ) { var _val = await this.getVal ( ) console.log ( _val+'prom ' ) ; } } getVal ( ) { return new Promise ( function ( resolve , reje...
How To Synchronise Promise Objects ?
JS
I 'm not sure if there is a simple way of doing this , but is there a way to find multiple instances in an unknown string ? For example : Without knowing the value of the above string , can I return something that will tell me that there are 3 instances of `` hello '' and 3 instances of `` bye '' ( I 'm not worried abo...
hellohellohellobyebyebyehello
Algorithm ( or regular expression ) needed to find multiple instances of anything
JS
I made a simple web UI with JSFiddle and I am wondering if the same UI can be made without using JavaScript.A Fiddle says more than 1000 words.So the question is ( because it seems unclear for some people ) : How can I achieve the same results without using any JavaScript ? PS : I do n't want to use JavaScript to re-ca...
< div class= '' A '' > < div class= '' B '' > B < /div > < div class= '' C '' > This stays fixed when scrolling horizontally , but scrolls along when scrolling down the parent . < /div > < /div > .A { background-color : yellow ; height : 400px ; width : 700px ; overflow : scroll ; position : relative ; } .B { backgroun...
Is this possible without using javascript ?
JS
I 'm having trouble understanding javaScript promises . I wrote the following code : I immediately see this in my Chrome developer console : But after I wait 5 seconds , the message automatically changes to black like this image : I 've never seen this behaviour before between my javaScript code and a developer console...
var p = new Promise ( function ( resolve , reject ) { reject ( Error ( `` hello world '' ) ) ; } ) ; setTimeout ( ( ) = > p.catch ( e= > console.log ( e ) ) ,5000 ) ; var p = new Promise ( function ( resolve , reject ) { resolve ( `` hello world '' ) ; } ) ; setTimeout ( ( ) = > p.then ( e= > console.log ( e ) ) ,5000 ...
With a Promise , why do browsers return a reject twice but not a resolve twice ?
JS
This is driving me nuts ! I have got an axios call returning an json array object in console - Check ! Now I need to do 2 things with this result : when fully expanded this response is large - and there are thousands of them . Rather than store 1000s of giant json reponses in a vuex state - I want to first only extract...
> ( 100 ) [ { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … } , { … ...
How can I extract specific values from all items in axios response object to a a vuex state
JS
let 's say I have this code in javascript : and let the code in the servlet be : Will xhr1 still wait for new changes in readystate ? Or it is closed as soon as it gets the first response ? If it remains open , will it lead to memory leaks/slower browser after a while and accumulating a few of those ? Should I always c...
function doAnAjaxCall ( ) { var xhr1 = new XMLHttpRequest ( ) ; xhr1.open ( 'GET ' , '/mylink ' , true ) ; xhr1.onreadystatechange = function ( ) { if ( this.readyState == 4 & & this.status==200 ) { alert ( `` Hey ! I got a response ! `` ) ; } } ; xhr1.send ( null ) ; } public class RootServlet extends HttpServlet { pu...
What is the life span of an ajax call ?
JS
So I really prefer using unobtrusive javascript to inline javascript . I find it much easier to work with.The problem that I keep running into , is that I do n't know how to get data for each specific element that I want to work with.For example : I have a list , and I generate the following HTML ( this is pseudo-code ...
< % for e in list % > < a href= '' # '' class= '' delete '' > < % =e % > < /a > < ! -- < % = e.id % > ? ? -- > < % end % > $ ( ' a.delete ' ) .click ( function ( ) { // Ajax request using `` e.id '' } ) ;
Ajax requests with unobtrusive javascript over lists of elements
JS
colorbox v1.3.15 from colorpowered.com has this javascript in it 's minified code : this seems to run perfectly , should it ?
c.name=i+ +new Date ;
javascript odd syntax : c.name=i+ +new Date ;
JS
First of all , you can find an example of my code in JS Fiddle and also below the question.I 'm working on a personal training webapp and basically you can hit play and then you get five minutes to do a series of tasks in a random order . The program creates the sessionTasks array in which are put in a random order tas...
mainMenu ( ) ; var totalSessionTasks , taskIterator , selectedTimeInSecs = 300 ; var taskTimer = new Timer ( `` # taskTimer '' , nextTask ) ; var globalTimer = new Timer ( `` # globalTimer '' , function ( ) { } ) ; var tasks = [ [ `` First task '' , 0 , 30 ] , [ `` Second task '' , 0 , 15 ] , [ `` Third task '' , 0 , 1...
Timer function not working correctly when stopped and started multiple times
JS
I 'm trying to get a handle on web workers when I came across a very peculior behaviour . For some reason it 's terminated after a few seconds , even though I have code in it that 's running.Here 's my code ; Main JavaScript-file : Worker file : As stated , the worker just stops functioning after a few seconds , 10-20s...
$ ( document ) .ready ( function ( ) { var worker = new Worker ( `` js/TestWorker.js '' ) ; worker.addEventListener ( 'message ' , function ( event ) { console.log ( event.data ) ; } ) ; worker.addEventListener ( 'error ' , function ( event ) { console.log ( event ) ; } ) ; } ) ; ( function ( ) { var updateCounter = 0 ...
Why is my Web Worker terminated ?
JS
ObjectiveOnce the maximum number of players ( two goalies , six defensemen , twelve forwards ) in each of their categories have been chosen , the remaining players picked with the class is-inactive should been set to cursor : defaultClarification of the problemAll the players have the class is-inactive as a default , a...
.player { display : inline-block ; margin-top : 15px ; margin-right : 20px ; vertical-align : top ; cursor : pointer ; position : relative ; } < div class= '' player player -- goalie year -- 1990 '' > < div class= '' tooltip tooltip -- tall '' > < p class= '' tooltip__name '' > Brian Elder < /p > < p class= '' tooltip_...
Setting cursor to default for elements with is-inactive class
JS
Before I get yelled at for trying something so reckless , let me tell you that I would n't do this in real life and it 's an academic question.Suppose I 'm writing a library and I want my object to be able to make up methods as they are needed.For example if you wanted to call a .slice ( ) method , and I did n't have o...
window.onerror = function ( e ) { var method = / ' ( . * ) ' $ /.exec ( e ) [ 1 ] ; console.log ( method ) ; // slice return Array.prototype [ method ] .call ( this , arguments ) ; // not even almost gon na work } ; var myLib = function ( a , b , c ) { if ( this == window ) return new myLib ( a , b , c ) ; this [ 1 ] =...
Resume from an error
JS
I 'm working on a little jQuery widget to add to my portfolio/knowledge base . The widget works , and cycles through 5 slides , however , it does not loop back around to slide 1 as it should . It only advances to a blank slide , and the page requires refreshing to move back or forward again . I am a Javascript/jQuery b...
// ( document ) .ready ( ) ; makes sure that all elements on the page are //loaded before loading the script $ ( document ) .ready ( function ( ) { //alert ( 'Doc is loaded ' ) ; //specifies speed to change from image to image , in ms var speed = 500 ; //specifies auto slider option var autoswitch = true ; //Autoslider...
jQuery slider not going to beginning
JS
I 'm using a node.js server , the Spotify API , and the spotify-web-api-js node module to create a web application where the user can enter an artist 's name , see a list of songs from related artists , and then optionally save that playlist to their own Spotify account . However , i 'm still having trouble with the la...
if ( params.access_token ) { s.setAccessToken ( params.access_token ) ; s.getMe ( ) .then ( function ( data ) { console.log ( data ) ; console.log ( data.id ) ; user_id = data.id ; async.times ( counter , function ( n , next ) { s.getArtistTopTracks ( relatedArtists [ n ] .id , `` US '' , function ( err , data2 ) { rel...
How to pick an event listener that will let me wait until async.times is finished to run a function
JS
Does going from to really speed things up ? I am thinking it does because php can fetch and embed a file 's contents faster than the client 's browser can make a full request for the file , because php is n't going over the network . Is the main difference that the traditional method can be cached ?
< script type= '' text/javascript '' src= '' jquery.js '' > < /script > < script type= '' text/javascript '' > < ? php echo file_get_contents ( 'jquery.js ' ) ; ? > < /script >
Is this an optimization ?
JS
Look edits below ! I am currently looking for a way to overload the toString method of one specific function that is generated dynamically ( returned by function ) . I know I can overload the toString function of Function.prototype , but this will overload all toString functions of all functions , I want to avoid this....
var obj = { callme : function ( ) { return function ( ) { // Dynamically fetch correct string from translations map return `` call me , maybe '' ; } } } // Binding callme to func , allowing easier accessvar func = obj.callme.bind ( obj ) ; console.log ( func , func ( ) ) func.toString = function ( ) { return this ( ) ;...
Overwrite toString for specific function
JS
I 'm checking the number of digits in a string using the match and length properties . Here is the codepen with my function http : //codepen.io/PiotrBerebecki/pen/redMLEInitially when returning numberOfDigits.length I was getting an error message ( Can not read property 'length ' of null ) . I 've solved this issue by ...
function checkLength ( str ) { let numberOfDigits = str.match ( /\d/g ) ; return ( numberOfDigits & & numberOfDigits.length ) ; } console.log ( checkLength ( 'T3xt w1th sOme numb3rs ' ) ) ; console.log ( checkLength ( 'Text with some numbers ' ) ) ;
Why I 'm not getting an error when checking the length of null
JS
Is there a faster way of writing this ? I 'm thinking of something like :
if ( $ ( ' # id ' ) .val ( ) ==7 || $ ( ' # id ' ) .val ( ) ==8 || $ ( ' # id ' ) .val ( ) ==9 ) { console.log ( 'value of # id is 7 , 8 , or 9 ! ' ) } ; if ( $ ( ' # id ' ) .val ( ) == 7||8||9 ) { console.log ( 'value of # id is 7 , 8 , or 9 ! ' ) } ;
Is there a faster way of writing OR operator ?
JS
I have recently added a HasValue function to our internal javascript library : A during a convorsation with a coworker , we came up with the idea of also adding another function that would basically just be the inverse : perhaps HasNoValue , or IsNothingIf we ended up doing that we would have : However , we 're not sur...
function HasValue ( item ) { return ( item ! == undefined & & item ! == null ) ; } function HasNoValue ( item ) { return ( item === undefined || item === null ) ; } function HasValue ( item ) { return ! HasNoValue ( item ) ; } if ( HasValue ( x ) & & ! HasValue ( y ) ) if ( HasValue ( x ) & & HasNoValue ( y ) )
Is it worth the effort to have a function that returns the inverse of another function ?
JS
I have simple code here.The intention of it is to verify the user with the user who wrote the post and allow the verified user to edit the post.The console says : Which means they are equal in value and also equal in types.I tried with == too , but that also does n't work.I am suspecting there needs to be something don...
exports.edit = function ( req , res ) { Post.findById ( req.params.post_id , function ( err , post ) { if ( err ) { return res.json ( { type : false , message : '' error ! '' } ) ; } else if ( ! post ) { return res.json ( { type : false , message : '' no post with the id '' } ) } else { console.log ( req.user._id , typ...
why does Javascript comparison not work with objects ?
JS
I thought this was an easy task but it is getting really complex . See the Code.It is throwing error , can not read split of undefined . How to fix this ?
// Convert `` rgb ( 255 , 255 , 255 ) '' to ( 255 , 255 , 255 ) and then to Hex code var data = { color : '' rgb ( 165,199,72 ) '' , color : '' rgb ( 229,121,74 ) '' , color : '' rgb ( 105,177,222 ) '' } // rgb To Hex Conversion var componentToHex = function ( c ) { var hex = c.toString ( 16 ) ; return hex.length == 1 ...
Substring , Split , String to Number and RGB to HEX
JS
I have a npm package of React components which are using flow for type-checking.It would be useful for the users of my components to have access to my flow types . However at the moment I am compiling my code using Babel which strips all type information.My project structure is as follows : For example one of my types ...
||- flowdecls myTypes.js| -components - Component1 Component1.js| - lib - Component1.js ( compiled using Babel ) - Component1.js.flow ( created using flow-copy-source ) declare type DataItemIconType = { iconElement : React $ Element < React $ ElementType > , color ? : string , hoverColor ? : string } iconList : Array <...
Exporting my own Flow type with npm package ?
JS
I think I understand prototypical inheritance in JS but am having trouble writing code to demonstrate a particular idea I have . Consider this extremely simple scenario , where Manager objects derive from Employee objects : The output is : Oddly enough , it seems to me that we 've succeeded in demonstrating prototypica...
function Employee ( ) { this.name = `` Axel '' ; this.dept = `` R & D '' ; } function Manager ( ) { Employee.call ( this ) ; this.reports = [ `` Report 1 '' , `` Report 2 '' , `` Report 3 '' ] ; } console.log ( new Manager ( ) ) ; Manager { name : `` Axel '' , dept : `` R & D '' , reports : Array [ 3 ] }
Prototypical inheritance without prototype ?
JS
I have a timer in Javascript that fires once per second to update some text in the page ( HTML5 ) like this : This works fine except that if this code runs while the user is dragging a scrollbar handle the drag is aborted . This is a very annoying user interface behavior which I have not been able to resolve . If I com...
document.getElementById ( 'CountDown ' ) .innerHTML = `` some string '' ;
Setting HTM5 text kills scrollbar drag in Chrome
JS
I wrote a simple input field with a button in it . Code is as given below . As you can see , when I click in input field , button disappears . When I click outside that form , it reappears . But I do n't want it to disappear when clicked on input field . How can I do that ?
form { width : 50 % ; } /* Style the search field */.add-on { position : relative ; } .add-on input { width : 100 % ; border-radius : 0 ; } .add-on button { position : absolute ; border-radius : 0 ; top : 2px ; right : 3px ; height : 33px ; width : 60px ; z-index : 2 ; font-size : 14px ; padding : 5px ; } < link href= ...
Disappearing button in HTML
JS
What 's the best way to find out whether a variable is a string or not ( and , likewise , a number , a boolean , etc . ) ? Usually you will find : But people forget that one can also create string objects directly using var foo = new String ( `` bar '' ) ; - whether that is a good idea or not is an entirely different m...
function isString ( value ) { return typeof value === 'string ' ; } // option 1function isString ( value ) { return ( typeof value === 'string ' ) || /^function String\ ( \ ) /.test ( value.constructor + `` ) ; } // option 2function isString ( value ) { return ( typeof value === 'string ' ) || ( value.constructor === S...
Checking the type of a variable
JS
I am trying to make a timer which indirectly syncs with the video . When starttimer is clicked , it should starts my timer and tickle each second.Here is the process : But my timer , is not functioning properly . It works fine , when I start the timer but when I forward by n seconds , it sometimes goes by n and sometim...
1 . Start the video2 . At a certain time in video , click to start the timer3 . Timer starts from 00:00:00 and should tickle each second.4 . If the video is forwarded by ` n ` seconds timer should be 'timer+n ` seconds . Same for the case , when video is rewinded - ` timer-n ' var mtimer = 0 ; $ ( ' # starttimer ' ) .c...
How to make the timer tickle each second and make it jump when video is forwarded or rewinded ?
JS
I would like to provide Gamepad support for my Vue app . I would like to listen to the events from the Gamepad API.I do n't want to attach those listeners to a component because I have to deal with them globally . So where should I attach those listeners ? Should I add each event to the App.vue component , because it '...
export default { on_browser_gamepadconnected : ( { commit } , e ) = > { // do something } , } ;
listening to browser events from the Vuex store
JS
What is the purpose of using // in the following code . If old browsers doesnt support javascript then the symbols < ! -- -- > will ignore js code . In case browsers support JS , these symbols < ! -- -- > will be ignored . Then wats the use of // symbols .
< html > < body > < script type= '' text/javascript '' > < ! -- document.getElementById ( `` demo '' ) .innerHTML=Date ( ) ; // -- > < /script > < /body > < /html >
Commenting in JavaScript
JS
Take a look at the following code : As I execute this code , the following result is displayed : As Node.js documentation explains , the setImmediate is executed after I/O callbacks , but in this example setImmediate is being executed before I/O callbacks , am I missing something ?
var fs = require ( 'fs ' ) ; var pos = 0 ; fs.stat ( __filename , function ( ) { console.log ( ++pos + `` FIRST STAT '' ) ; } ) ; fs.stat ( __filename , function ( ) { console.log ( ++pos + `` LAST STAT '' ) ; } ) ; setImmediate ( function ( ) { console.log ( ++pos + `` IMMEDIATE '' ) } )
Node.js setImmediate executed before I/O callbacks ( Event Loop )
JS
Have problem with submiting information via ajax.Have for example 20 rows . Click on row and it opens all information about services.Here html : Then its div with infoI 'm saving class in localStorage . And then user edits value in field and hes out off that field , I update that information with ajaxThe problem is tha...
$ ( 'tr ' ) .click ( function ( ) { var servicesUpdateId = $ ( this ) .attr ( 'data ' ) ; $ ( `` # '' +servicesUpdateId ) .css ( { `` display '' : '' block '' , 'opacity ' : ' 0 ' } ) .animate ( { left : ' 0 ' , opacity : ' 1 ' , } ) ; // save form class for ajax submit localStorage.setItem ( `` formId '' , servicesUpd...
Ajax issue with input , textarea blur
JS
I have this code of Javascript that i got from a forum for my html page : My question is how can i make it reload when the time is up . so if seconds and minuets = 0 , it would reload.Or if you have a better simple times , please show me how : )
< html > < head > < title > Countdown < /title > < script type= '' text/javascript '' > // set minutesvar mins = 0.1 ; // calculate the seconds ( do n't change this ! unless time progresses at a different speed for you ... ) var secs = mins * 60 ; function countdown ( ) { setTimeout ( 'Decrement ( ) ',1000 ) ; } functi...
How to make javascript timer reload
JS
I can not figure out the best way to dynamically generate a multidimensional array with 2 different sizes.We have a UI that requires a row of 4 items , then 3 . This pattern would repeat until the content in the array has been spent.This is essentially what I need to do : This is what I currently have , it is only conv...
// Convertconst array = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 ] ; // toconst rows [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 ] ] ; const buildRows = ( arr , length ) = > arr.reduce ( ( rows , val , i ) = > ( i % length == 0 ? rows.push ( [ val ] ) : rows [ rows.len...
Javascript Generate Multidimensional array of 2 sizes
JS
From React DOCS : https : //reactjs.org/docs/state-and-lifecycle.htmlState Updates May Be AsynchronousReact may batch multiple setState ( ) calls into a single update for performance.This makes total sense . If you have something like the function below , it would be very inefficient to re-render on every setState call...
const [ state1 , setState1 ] = useState ( false ) ; const [ state2 , setState2 ] = useState ( false ) ; const [ state3 , setState3 ] = useState ( false ) ; function handleClick ( ) { setState1 ( true ) ; setState2 ( true ) ; setState3 ( true ) ; } function App ( ) { console.log ( `` App rendering ... '' ) ; const [ cou...
When does React re-render after a setState call made inside an event handler
JS
I just found that if I use new Date ( '2015-1-1 ' ) , the time is no timezone effect , but If I use new Date ( '2015-01-01 ' ) the time has timezone effect in Node.js.I output 4 Date ( ) : the output is you can see the last time is 08:00:00 because I 'm in +8 timezone.I think the output depends on the digit of the mont...
console.log ( new Date ( '2015-1-1 ' ) ) ; console.log ( new Date ( '2015-01-1 ' ) ) ; console.log ( new Date ( '2015-1-01 ' ) ) ; console.log ( new Date ( '2015-01-01 ' ) ) ; Thu Jan 01 2015 00:00:00 GMT+0800 ( CST ) Thu Jan 01 2015 00:00:00 GMT+0800 ( CST ) Thu Jan 01 2015 00:00:00 GMT+0800 ( CST ) Thu Jan 01 2015 08...
Date ( '2015-1-1 ' ) outputs different from Date ( 2015-01-01 )
JS
Here is the fiddle : http : //jsfiddle.net/7txt3/29/I want to have the record needle on the record like you see in my image below rotate on to the record when the user clicks the play button ( see the fiddle ) The needle placement is not necessarily final and I might want it to be in the top right corner . ( I 've incl...
$ ( function ( ) { var station = $ ( '.player-station ' ) , record = $ ( '.record2 : first ' ) , playBtns = $ ( '.play ' ) , info = $ ( '.nprecinfo ' ) ; var isPlaying = false ; playBtns.click ( function ( ) { var btn = $ ( this ) ; if ( btn.text ( ) == 'STOP ' ) { btn.text ( 'PLAY ' ) ; record.css ( { '-webkit-animati...
Need help to add/modify to my script to include some rotation using jquery and css
JS
I have a live ( ) function in my jquery below : Now some people say that the live ( ) function is slowing fading away and that is better to use the on ( ) function . If this is true then how do I change the code above to on ( ) function rather than a live ( ) function ? Is it important I do n't use live ( ) or does it ...
$ ( `` # qandatbl td.weight input '' ) .live ( `` change '' , calculateTotal ) ; function calculateTotal ( ) { var totalweight = hundred ; $ ( `` # qandatbl td.weight input '' ) .each ( function ( i , elm ) { totalweight = totalweight - parseInt ( $ ( elm ) .val ( ) , 10 ) ; } ) ; $ ( `` # total-weight '' ) .text ( tot...
How to change my code from a .live ( ) to .on ( )
JS
I execute the following javascript code in iOS using JavaScriptCore framework . The javascript code is browserified . printFunc is a method implemented in Swift that just prints something to console . Here is the implementation : The problem is that I am receiving the following error : Even more strange is that if I re...
var myCallback = undefined ; *browserify logic* { 1 : [ function ( require , module , exports ) { var q = require ( './user ' ) ; var p = new Promise ( function ( resolved , reject ) { myCallback = function ( ) { resolved ( 'test ' ) ; } } ) ; p.then ( function ( x ) { printFunc ( 'test ' ) ; } ) .catch ( function ( e ...
'Error compiling builtin ' while executing JavaScript code in JavaScriptCore
JS
Every time I create some class , I need to do the same boring procedure : Is there any way to make it more elegant and shorter ? I use Babel , so some ES7 experimental features are allowed . Maybe decorators can help ?
class Something { constructor ( param1 , param2 , param3 , ... ) { this.param1 = param1 ; this.param2 = param2 ; this.param3 = param3 ; ... } }
A shorter class initialisation in ECMAScript 6
JS
I have a wizard form with four steps which is for ordering Parts , the first step user provide details ( Stock Type and Approver who will approve the order ) which are validated correctly . Second step user will select which parts to order from the table . On the table , a user is allowed to enter quantity which is les...
`` use strict '' ; function scroll_to_class ( element_class , removed_height ) { var scroll_to = $ ( element_class ) .offset ( ) .top - removed_height ; if ( $ ( window ) .scrollTop ( ) ! = scroll_to ) { $ ( '.form-wizard ' ) .stop ( ) .animate ( { scrollTop : scroll_to } , 0 ) ; } } function bar_progress ( progress_li...
Moving line items from one table to another table and validating data entered on the first table before adding selected line items to second table
JS
I want to draw a line on screen from the top of the page to the bottom when the user scrolls the page and have an arrow at the bottom of it . I do n't want to use fixed position so that its always in the same spot , I want it to indicate where they are on the page by determining the page length etc . I have the followi...
//Draw dotted line on scroll - works to certain extent but scrolls off page $ ( window ) .scroll ( function ( ) { if ( $ .windowScrollTop ( ) > 10 ) { var pos = $ .windowScrollTop ( ) ; var scrollHeight = $ ( window ) .innerHeight ( ) ; var element = $ ( ' # dashes ' ) ; $ ( ' # line ' ) .css ( 'height ' , pos - scroll...
calculate positioning of image to follow scroller
JS
I 've successfully ssh 'd into Google Cloud Compute via CLI with a command like the following : But using the ssh2 module is n't giving any output , including errors.I 'm tailing /var/log/secure as I 'm debugging the node script and I can see log entries when I ssh in and close the session from CLI , but nothing at all...
ssh -i ~/.ssh/my-ssh-key me @ ipnumber var fs = require ( 'fs ' ) ; var Client = require ( 'ssh2 ' ) .Client ; var connSettings = { host : IP , // 'XXX.XXX.XXX.XX ' port : PORT , // XXXX username : ME , privateKey : privateKey , //fs.readFileSync ( location , 'utf8 ' ) passphrase : passphrase , password : password } ; ...
ssh2 module fails silently with creds that succeed from CLI
JS
Can you explain me why does the second call of fn gives an error ? The code is below.Here 's a JSfiddle that reproduces the error http : //jsfiddle.net/KjkQ2/
function Test ( n ) { this.test = n ; var bob = function ( n ) { this.test = n ; } ; this.fn = function ( n ) { bob ( n ) ; console.log ( this.test ) ; } ; } var test = new Test ( 5 ) ; test.fn ( 1 ) ; // returns 5test.fn ( 2 ) ; // returns TypeError : 'undefined ' is not a function
Javascript 'this '
JS
I have a script which allows to replace undesired HTML tags and escape quotes to `` improve '' security and prevent mainly script tag and onload injection , etc ... . This script is used to `` texturize '' content retrieved from innerHTML.However , it multiples near by 3 my execution time ( in a loop ) . I would like t...
function safe_content ( text ) { text = text.replace ( / < script [ ^ > ] * > . * ? < \/script > /gi , `` ) ; text = text.replace ( / ( < p [ ^ > ] * > | < \/p > ) /g , `` ) ; text = text.replace ( /'/g , ' & # 8217 ; ' ) .replace ( / & # 039 ; /g , ' & # 8217 ; ' ) .replace ( / [ \u2019 ] /g , ' & # 8217 ; ' ) ; text ...
Javascript - Regex/replace optimization
JS
I want communicate between java and typescript with encrypted AES-GCM data ( PBKDF2 hash used for password ) .I used random bytes for pbkdf2 : This is my java PBKDF2 Code : and this is typescript code : Result in java and typescript : Why i have difference result ? What part of code has wrong ? UPDATEInteresting , I tr...
randomBytes ( Base64 ) : wqzowTahVBaxuxcN8vKAEUBEo0wOfcg4e6u4M9tPDFk= private String salt = `` 1234 '' ; private static final String KEY_ALGORITHM = `` AES '' ; private Key generateKey ( byte [ ] randomBytes ) throws Exception { var randomPassword = new String ( randomBytes ) ; KeySpec keySpec = new PBEKeySpec ( random...
Java and typescript generate difference PBKDF2 hash
JS
I am not able to populate my form with data that I have received from a method called getbyId ( ) from a service , in my console I see that errors : can not read truckId of undefined , Every solution i have found is saying my form is rendered faster than the object that i want to get with a getById ( ) method and the s...
getTruckById ( id : number ) : Observable < Truck > { const url = ` $ { this.baseUrl } / $ { id } ` ; return this.http.get ( url , { headers : this.headers } ) .pipe ( map ( this.extractData ) , tap ( data = > console.log ( JSON.stringify ( data ) ) ) , catchError ( this.handleError ) ) ; } export class EditTruckCompon...
Can not read value of undefined , when components share data ?
JS
JSFiddle exampleI 've noticed that when updating positions of svg elements in a d3-force diagram , updating the positions of elements using ( in the case of circles ) the cx and cy attributes is much smoother than using the transform attribute.In the example JSFiddle , there are two separate force simulations side-by-s...
sim_transform.on ( 'tick ' , function ( ) { circles_transform.attr ( 'transform ' , function ( d ) { return 'translate ( ' + d.x + ' , ' + d.y + ' ) ' ; } ) ; } ) ; sim_position.on ( 'tick ' , function ( ) { circles_position .attr ( 'cx ' , function ( d ) { return d.x ; } ) .attr ( 'cy ' , function ( d ) { return d.y ;...
Force simulation is jittery when using svg transforms to update position
JS
I noticed something weird with timezones and Javascript Date object.Trying this on a Linux box : I found it impossible to get an object that represents the 21th of october 2012 . Every attemps to get a Date between 00:00 and 01:00 that day results in a date the day before between 11:00 PM and 00:00 . ( Windows user may...
$ TZ='America/Sao_Paulo ' js js > new Date ( 2012 , 9 , 21 , 0 , 0 , 0 ) .toString ( ) `` Sat Oct 20 2012 23:00:00 GMT-0300 ( BRST ) ''
Is there a way to represent the 21 october 2012 in a Javascript ` Date ` object ?
JS
In JavaScript , the NaN value can be represented by a wide range of 64-bit doubles internally . Specifically , any double with the following bitwise representation : Is interpreted as a NaN . My question is : suppose I cast two 32-bit uints to a JS Number using ArrayBuffers , pass it around , then cast it back to two 3...
x111 1111 1111 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
Are JS engines allowed to change the bits of a NaN ?
JS
There is such a construction : When you click on one item , all are toggled together . How to fix it ?
$ ( 'ul li ' ) .click ( function ( ) { $ ( '.hide ' ) .slideToggle ( 300 ) ; $ ( this ) .toggleClass ( `` hide-open '' ) ; } ) ; < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js '' > < /script > < ul > < li > Пункт < div class= '' hide '' > Это скрыто < /div > < /li > < li > Пункт < ...
How to show an element only in this block ?
JS
I 'd like to add different child elements to my nodes depending on the node type . Therefore the node has an attribute called type . All nodes should consist of a g element with the dependent child elements.I tried this by using D3s filter functionality but i 'm stuck as my code does n't add the child elements only onc...
self.domNodes = this.svg.append ( ' g ' ) .attr ( 'class ' , 'nodes ' ) .selectAll ( '.node ' ) function draw ( ) { self.domNodes = self.domNodes.data ( self.nodes , ( node ) = > node.id ) self.domNodes.exit ( ) .remove ( ) // all nodes self.domNodes.enter ( ) .append ( ' g ' ) .attr ( 'class ' , ( node ) = > ` node $ ...
Adding child elements to specific nodes in a force-directed graph using d3js
JS
Rails version : 5.2.2Chrome version : 78.0.3904.87While testing my website on Chrome today , I noticed that it scrolls to the top of the page whenever I submit an AJAX request . This behavior is undesirable and does not happen on other browsers , such as Firefox . I 've tried debugging the issue but could n't figure ou...
< div id= '' container '' > < % = form_for ( obj , method : : post , url : url , remote : true ) do |f| % > < button id= '' obj- < % = obj.id % > -btn '' type= '' button '' class= '' btn btn-primary obj-btn '' title= '' Add '' data-toggle= '' tooltip '' data-placement= '' left '' > Add < /button > < % end % > < /div > ...
Chrome scrolling to the top of the page after a remote form request
JS
I 'm trying to grasp how the functions in Donut3D.js - > http : //plnkr.co/edit/g5kgAPCHMlFWKjljUc3j ? p=preview handle the inserted data : Above all , where is it set that the data 's startAngle is set at 0 degrees ? I want to change it to 45º , then to 135º , 225º and 315º ( look at the image above ) .I 've located t...
Donut3D.draw = function ( id , data , x /*center x*/ , y/*center y*/ , rx/*radius x*/ , ry/*radius y*/ , h/*height*/ , ir/*inner radius*/ ) { var _data = d3.layout.pie ( ) .sort ( null ) .value ( function ( d ) { return d.value ; } ) ( data ) ; var slices = d3.select ( `` # '' +id ) .append ( `` g '' ) .attr ( `` trans...
How is data parsed in this 3D piechart ?
JS
I am building a jQuery plugin to manage form collections . The plugin aims to add add , remove , move up and move down buttons to alter that collection . A collection 's root node always contains a selector , such as .collection.A button can be anything as soon as it has the .add classI implemented min and max options ...
< div class= '' collection '' > < div > something < /div > < div > something < /div > < div > < div class= '' add '' > + < /div > < /div > < div > something < /div > < div class= '' collection '' > < div > something < /div > < div > something < /div > < div > < div class= '' add '' > + < /div > < /div > < div > somethi...
How to find elements that are not deeper than a selector ?
JS
I am able to change design of the title attribute inside anchor tag , even though the default one is coming along with changed one.I 'm wondering if it 's possible to remove default title tooltip as shown below ? Here 's my code so far : Thanks in advance .
< a title= '' Edit '' > < img alt= '' '' src= '' dist/img/edit.png '' > < /a > a : hover { color : red ; position : relative ; } a [ title ] : hover : after { content : attr ( title ) ; padding : 2px 4px ; color : # 333 ; position : absolute ; left : 0 ; top : 100 % ; white-space : nowrap ; z-index : 20px ; -moz-border...
Remove the old design title of an anchor tag after applying CSS on it
JS
There is an open-source application which visually displays a difference between two BPMN diagrams.I want to see what the application looks like when it runs.How can I start it under Ubuntu ? I tried to run node app.js in the directory bpmn-js-diffing/app but got the errorI looked at the Gruntfile in search of a `` run...
module.js:341 throw err ; ^Error : Can not find module 'jquery ' at Function.Module._resolveFilename ( module.js:339:15 ) at Function.Module._load ( module.js:290:25 ) at Module.require ( module.js:367:17 ) at require ( internal/module.js:16:19 ) at bpmn-js-diffing/app/app.js:6:11 at Object. < anonymous > ( bpmn-js-dif...
How can I start this Node.JS application ?
JS
The issue I 'm seeing is that when you load Stripe Checkout into a page using their canonical `` Custom '' guide , configure it , and then open and close it a few times , the browser memory usage continually jumps . It sometimes , sorta gets released a little , but the residual always grows . And on a long lived page/S...
performance.memory.usedJSHeapSize
Is Stripe Checkout leaking memory ?
JS
I 'm a new developer at my company and I do mostly front-end web development . Our team is frequently asked by our Sales and Marketing people to incorporate 3rd party javascripts on our site . `` Here 's a 'little code snippet ' . Our vendor asked if you could put this in our home page '' This makes me very nervous . I...
< script src= '' http : //www.mycompany.com/js/vendor-file.js '' type= '' text/javascript '' > < script src= '' http : //www.vendor.com/js/file.js '' type= '' text/javascript '' > var a = document.createElement ( `` script '' ) ; a.type = `` text/javascript '' ... etc .
What are the risks associated with Hosting 3rd party Javascripts ?
JS
In JavaScript when you define an array using the literal syntax , array elements may be omitted by using additional commas : I noticed that when accessing the values that the omitted values were not `` own properties '' In contrast , if you define an array explicitly setting undefined , it will be set as an `` own prop...
a = [ 1 , 2 , 3 ] ; // 1 , 2 , 3b = [ 1 , , 2 , 3 ] ; // 1 , undefined , 2 , 3 b.hasOwnProperty ( 1 ) ; //false c = [ 1 , undefined , 2 , 3 ] ; c.hasOwnProperty ( 1 ) ; //true
Do elided array elements ever produce an own property ?
JS
I often need to map a list of functions ( processors ) to several arrays ( channels ) of float data ) so I have written a helper function ... This reads OK ( to me at least ! ) but mapping an array of functions over another array seems like such a generic thing I ca n't help but wonder if it IS `` a thing '' already i....
const mapMany = function ( processors , channels ) { processors.forEach ( function ( processor ) { channels = channels.map ( ( channel ) = > channel.map ( processor ) ) ; } ) ; return channels ; } ;
Mapping an array of functions over an array in Javascript
JS
Suppose there are many < select > elements in a form . I need a selector that selects a < select > element whose selected option has certain text . To explain , let 's say there are 5 < select > elements of class `` color '' . Each of them have 3 < option > with texts `` white '' , `` black '' , `` green '' . Now I nee...
< select class= '' color '' > < option value= '' '' > < /option > < option value= '' 1 '' > white < /option > < option value= '' 2 '' > black < /option > < option value= '' 2 '' > green < /option > < /select >
How to select a < select > element on the basis of selected option text ?
JS
I currently have a Web Application that runs off a global Javascript-based API , and it is initialized like this : This API is shared across many `` Widgets '' that live in the Web Application , and they should all run off this single Api instance so they can pass data to each other.AJAX is currently used to load these...
var Api = { someVar : `` test '' , someFunction : function ( ) { return `` foo '' ; } } Api.myExtension = { myNewFunction : function ( ) { return `` bar '' ; } } Api.foo = { test : `` bar '' } // allowedApi.someVar = `` changing the existing someVar '' ; // not allowed var Api = { Debug : { Messages = new Array , Write...
Protecting a Global Javascript `` API '' Object
JS
Self explanatory fiddle : http : //jsfiddle.net/5FG2n/1/Say I have a view with two controllers , one containing the other . The outer controller is static , but I need to set the inner controller based on a scope variable from the outer . The scope variable will be the inner controller 's name as a string ( eg . 'Inner...
< div ng-app='app ' ng-controller='OuterCtrl ' > < div ng-controller='dynamicCtrl ' > { { result } } < /div > < /div > angular.module ( 'app ' , [ ] ) .controller ( 'OuterCtrl ' , [ ' $ scope ' , function ( $ scope ) { // Instead of hard coding the controller here , // how do I resolve the string 'InnerCtrl ' to the //...
How do I resolve and assign an inner controller from the outer 's scope ?
JS
Take a look at the following code : Why is it that when it 's a variable , the code works correctly yet when it is a number literal , it fails ? And also , strangely enough , why does the following line work ? In the above line , I basically enclosed the literal in parenthesis .
Number.prototype.isIn = function ( ) { for ( var i = 0 , j = arguments.length ; i < j ; ++i ) { if ( parseInt ( this , 10 ) === arguments [ i ] ) { return true ; } } return false ; } ; var x = 2 ; console.log ( x.isIn ( 1,2,3,4,5 ) ) ; // < = 'true'console.log ( 2.isIn ( 1,2,3,4,5 ) ) ; // < = Error : 'missing ) after ...
Strange syntax of Number methods in JavaScript
JS
Is this possible or am I barking up the wrong tree here ? Update : The object which fnc is supposed to represent is actually a Sarissa dom document . Here is a more elaborate version of fnc ( ) , dom_doc ( ) . The accepted answer below has been integrated into the function below.Demo : JSFIDDLE
var data = 'one ' ; function fnc ( ) { this.out = function ( ) { return data ; } } var instance = new fnc ( ) ; alert ( instance.out ) ; data = 'two ' ; alert ( instance.out ) ; // I know that this would achieve that , but that 's not what I would like to know.alert ( instance.out ( ) ) ; data = 'two ' ; alert ( instan...
Is it possible to make a JavasScript function act as if it was a string , no ( )
JS
I 've decided to learn node , an so I 'm following , to begin with , The Node Beginner Book . As in I guess a lot of other resources , there is the `` simple HTTP server '' , first step , something like : As I understand it , when someone , in this case me though localhost:8888 , makes a request , an event is triggered...
var http = require ( `` http '' ) ; http.createServer ( function ( request , response ) { response.writeHead ( 200 , { `` Content-Type '' : `` text/plain '' } ) ; response.write ( `` Hello World '' ) ; response.end ( ) ; } ) .listen ( 8888 ) ;
Where does `` request '' and `` response '' come from , and how could I have found out ?
JS
I am looking for a way to trigger different methods for the buttons in typeahead suggestions.I am using backbone underneath and I have created the related events and methods that are to be called , however when I click only the default typeahead : selected event happens , but not the methods I have created.EDITThis is ...
var QueryInputView = Backbone.View.extend ( { el : $ ( ' # query-input ' ) , initialize : function ( options ) { _.bindAll ( this , 'clearInput ' , 'initWordSuggester ' , 'initConceptSuggester ' , 'initTypeAhead ' ) ; this.initTypeAhead ( ) ; } , events : { 'keyup ' : function ( e ) { if ( e.keyCode === 13 ) { var valu...
Include buttons inside typeahead suggestions using Backbone
JS
I 'm trying to use AWS SimpleDB Javascript SDK.Here 's the web page with my script : When I run this web page I get this error : XMLHttpRequest can not load https : //sdb.amazonaws.com/ . No 'Access-Control-Allow-Origin ' header is present on the requested resource . Origin 'null ' is therefore not allowed access . The...
< ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < title > < /title > < /head > < body > < script src= '' https : //dl.dropboxusercontent.com/u/4111969/aws-sdk-2.1.39.js '' > < /script > < script type= '' text/javascript '' > AWS.config.update ( { accessKeyId : 'MYKEY ' , secretAccessKey : 'MYSECRET '...
Errors with AWS SimpleDB Javascript SDK
JS
I am fetching images from JSON with help of this codepen1 : https : //codepen.io/kidsdial/pen/QomgvaNow along with images , i need to fetch the text , so i tried codepen2 : https : //codepen.io/kidsdial/pen/bZvRgR , but text is not displaying ... .Text `` Good Food Good life `` should display like below image : Please ...
var target ; let jsonData = { `` layers '' : [ { `` x '' : 0 , `` layers '' : [ { `` x '' : 0 , `` src '' : `` Y1rcR8A.jpg '' , `` y '' : 0 } , { `` x '' : 476 , `` src '' : `` 0x7hnlG.png '' , `` y '' : 326 } , { `` justification '' : `` center '' , `` x '' : 357 , `` y '' : 633 , `` src '' : `` 2ccd95bae3f2a0c8249205...
Get the Text values from json file
JS
I spent some time debugging a strange infinite loop problem in a NodeJS testsuite . It only happens under rare conditions but I can reproduce it when I attach to the chrome debugger.I think it has to do with V8 's handling of stack traces in exceptions and a extension that the vows library did to the AssertionError obj...
$ git clone https : //github.com/flatiron/vows.git $ cd vows & & npm install & & npm install should $ cat > example.jsvar should = require ( 'should ' ) ; var error = require ( './lib/assert/error.js ' ) ; try { ' x'.should.be.json ; } catch ( e ) { console.log ( e.toString ( ) ) ; } // without debug , it should fail a...
V8 lazy generation of stack traces seems to cause an infinite loop in the vows library
JS
I am using the latest version of redux-observable and Rxjs i.eThe store - middleware , setup looks like this : And my epic looks like thisSo when I executed the program for the first time I got the following error : I googled it and found a solution here which says to install rxjs-compat @ 6 ( however it does n't makes...
// My version '' redux-observable '' : `` ^1.0.0 '' , '' rxjs '' : `` ^6.3.2 '' // Setting up middlewaresimport { pingEpic } from './epics ' ; import pingReducer from './reducers/pingReducer ' ; import { combineReducers , createStore , applyMiddleware } from 'redux ' ; import { combineEpics , createEpicMiddleware } fro...
rxjs v6 / redux-observable v1.0.0 : Operators not working in epic
JS
I 'm developing a Javascript based multiplayer game.So far I have the basic server , client and networking ready.I did have an issue where my player was moving faster on a 120Hz screen as opposed to a 60Hz screen . I 've fixed this by multiplying the player 's movementspeed by the deltatime of the 'requestAnimationFram...
//Game loop ; Do each 1/60th of a secondsetInterval ( gameTick , 1000/60 ) ; function gameTick ( ) { player.handleKeys ( ) ; enemies.foreach ( ( enemy ) = > { enemy.update ( ) ; } ) ; } //Draw loop ; match to player screen refresh ratewindow.requestAnimationFrame ( gameLoop ) ; function gameLoop ( ) { player.draw ( ) ;...
Javascript multiplayer game - requestAnimationFrame for game/physics logic ?
JS
I am not sure how the Javascript engines ( specifically browser engines ) store an array.For example - how much memory would this use ? I want to map integer dates as array indexes , but I need to be sure it is n't a bad idea .
var x = new Array ( 0 , 1 , 2 , 1000 , 100000000 ) ;
Javascript Array index fundamentals
JS
Can someone explain to me why the resulting promise ( d ) from the code below is resolved immediately ? I 'm creating an array of promises that are pending forever , so the resulting promise should also be pending forever as it waits for all subsequent promises to finish ( as presented here ) . I 've been using promise...
//promises that are never resolved nor rejectedvar a = new Promise ( function ( r , re ) { } ) ; var b = new Promise ( function ( r , re ) { } ) ; var c = new Promise ( function ( r , re ) { } ) ; var d = [ a , b , c ] .reduce ( function ( previousPromise , promise ) { return previousPromise.then ( promise ) ; } , Prom...
Why this chain of promises immediately resolves ?
JS
When sorting an array of numbers in JavaScript , I accidentally used < instead of the usual - -- but it still works . I wonder why ? Example : And an example array for which this does not work ( thanks for Nicolas 's example ) :
var a = [ 1,3,2,4 ] a.sort ( function ( n1 , n2 ) { return n1 < n2 } ) // result is correct : [ 4,3,2,1 ] [ 1,2,1,2,1,2,1,2,1,2,1,2 ]
Why does sorting a JS array of numbers with < work ?
JS
Here is one of the questions in JavaScript online-test before job interview : Q : How to make comparison a == b to be true ? ( e.g . console.log ( a == b ) // true ) I answered that it 's impossible because a and b are two different instances of F and equal comparison in JS in case of non-primitives compares reference....
function F ( ) { } ; var a = new F ( ) ; var b = new F ( ) ;
How to make comparison of objects ` a == b ` to be true ?
JS
I am trying to use jQuery to select a div , but ignore all divs selected that are children of a selected div . No divs have any other way to identify them other than an HREF that I am matching . For example : This code selects all the divs , including the child . How can I limit it to only select the outermost div that...
outerdiv = $ ( ' a [ href^= '' http : //bizmate . `` ] ' ) .closest ( 'div ' ) ; outerdiv.prepend ( `` This was selected '' ) < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < div > Wo n't be selected < div > Powered by < a href= '' http : //bizmate.in '' > Bizmate <...
jquery select outermost div of a nest of selected divs
JS
I have two arrays.I want a percent value that describes how much their values are different.I try using MSE and RMSE : and : The result is : I do n't think that this result is correct.First of all , mse and rmse are not in range [ 0 , 100 ] , and then are values very large even if the two array are not so different.Wha...
/*** Mean Squared Error* MSE = ( 1/n ) * Ʃ [ ( r - p ) ^2 ] } */export function computeMse ( a , b ) { const size = a.length let error = 0 for ( let i = 0 ; i < size ; i++ ) { error += Math.pow ( b [ i ] - a [ i ] , 2 ) } return ( 1 / size ) * error } /*** Root Mean Squared Error* RMSE = √MSE*/export function computeRm...
How to find a precent value that represents how much two arrays are different ?
JS
I have created a simple jQuery & CSS based tooltip which is not aligned horizontally even though i made positioning relative for the parent anchor link element.If i set the width of the tooltip to 100px or something else it works but the content may extend so I want to avoid defining the width.HTML CodejQuery CodeCSS C...
< div class= '' single-session-speakers '' > < div class= '' single_session_speaker_thumb iva_tip '' > < a href= '' # '' > < img alt= '' Anne-Marie '' src= '' http : //placehold.it/50x50 '' > < span class= '' ttip '' > Anne-Marie < /span > < /a > < /div > < div class= '' single_session_speaker_thumb iva_tip '' > < a hr...
jQuery tooltip not horizontally aligned ?
JS
Trying to make a method which can read the current visible text inside of a element . The method you see below is as far as i 've gotten the past few days.Is there anything more reliable for getting the visible text in a element other than using a caret/range ? Cause the issue I 'm having is that i have a lot of overfl...
function getTextInColumn ( rect ) { var startX = rect.left ; var startY = rect.top ; var endX = rect.left + rect.width - 2 ; var endY = rect.top + rect.height - 2 ; var start , end , range = null ; var i = 0 ; var rangeText = `` ; while ( ( rangeText === `` & & i < 100 & & endY > 5 ) ) { range = null ; if ( typeof docu...
Get visible text in CSS3 columns
JS
I 'm running into an issue where a callback sent to setTimeout from a resolved promise never get executed . supposed I have the following : myFunc ( ) never resolves as it is continually waiting for callbackCalled to be true.What am I missing here ? I believe the event loop should n't be blocked since I 'm calling awai...
class Foo { constructor ( foo ) { this.foo = foo ; } async execUntilStop ( callback ) { const timeoutLoopCallback = ( ) = > { if ( this.stopExec ) return ; callback ( { data : 'data ' } ) ; setTimeout ( timeoutLoopCallback , 10 ) ; } ; setTimeout ( timeoutLoopCallback , 10 ) ; return { data : 'data ' } ; } stop ( ) { t...
timeout loop in promise never executes after promise is resolved ?
JS
There is already an answer posted to the test itself , which can be found here , but I ca n't seem to figure out why that answer is correct.The part of the test that is giving me trouble is : The ( apparently ) correct answer , as noted in the above linked question is I tried inserting the answer - fixed the syntax err...
var keys = [ ] ; var fruits = [ 'apple ' , 'orange ' ] ; for ( propertyName in fruits ) { keys.push ( propertyName ) ; } ok ( keys.equalTo ( [ '__ ' , '__ ' , '__ ' ] ) , 'what are the properties of the array ? ' ) ; ok ( keys.equalTo ( [ ' 0 ' , ' 1 ' , 'fruits.prototype ' ) , 'what are the properties of the array ? '...
Having trouble understanding a reflection test in Javascript Koans
JS
I 've been playing around with Elm for a couple of days and I wanted to make a port of Moment.JS , since I 've seen a lack of libraries for what I wanted , and Moment just has everything that I need.The thing is that I always face the same error . I have Moment.JS in my Native folder ( it is named MomentJS.js ) and ano...
var _user $ project $ Native_Moment = ( function ( ) { var moment = require ( 'moment ' ) ; var format = function ( format , date ) { return moment ( ) .format ( ) ; } return { format : format } ; } ) ( ) ; module Moment exposing ( format ) { -| A module desc @ docs format- } import Native.MomentJSimport Native.Moment ...
Making a Native ELM module with Moment.js
JS
Save the following HTML as a local file . Something like /tmp/foo.html , then open that in Firefox ( I 'm on 49.0.2 ) I do n't have a server running on port 1234 , so the requests do n't even successfully connect.The behavior I 'd expect here is for all the requests to fail , and be done with it.What actually happens i...
< ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < /head > < body > < script src= '' http : //localhost:1234/a.js '' > < /script > < script src= '' http : //localhost:1234/b.js '' > < /script > < script src= '' http : //localhost:1234/c.js '' > < /script > < script src= '' http : //localhost:1234/d.js...
Why do browsers re-request scripts on non-200 response ?
JS
I 've installed Django-CMS onto an existing site and while it is n't throwing errors , it is n't working . In particular , the header on a given page appears when I use `` / ? edit '' but none of the pull down menus work , and very little ( possibly none ) of the JavaScript works . Other facets : I 've done this on a l...
DEBUG = TrueTEMPLATE_DEBUG = FalseALLOWED_HOSTS = [ '*domain of server* ' ] LOGIN_REDIRECT_URL = '/'DATABASES = { 'default ' : { 'ENGINE ' : 'django.db.backends.mysql ' , 'NAME ' : '*db name* ' , 'USER ' : '*username* ' , 'PASSWORD ' : '*password* ' , 'HOST ' : `` , 'PORT ' : `` , } } STATIC_ROOT = '*path to the static...
Django-cms installs , but pull-downs and other JS does n't work - ideas for fixing ?
JS
I prototyped Function so that it has a getBody function : See here for more info.I tried to test it this way : but received an error : TypeError : console.log.getBody is undefined.I figured out that maybe this happens because console.log was defined before I actually prototyped Function so I created an empty function x...
Function.prototype.getBody = function ( ) { // Get content between first { and last } var m = this.toString ( ) .match ( /\ { ( [ \s\S ] * ) \ } /m ) [ 1 ] ; // Strip comments return m.replace ( /^\s*\/\/ . * $ /mg , '' ) ; } ; console.log ( console.log.getBody.getBody ( ) ) ; console.log ( x.getBody.getBody ( ) ) ;
Why does prototyping Function not affect console.log ?
JS
I have a div card that plays an animation on click , which includes the card scaling to be larger . The problem is that as the card scales bigger , it 's edges are displayed under other cards . http : //puu.sh/oqtEs/5c0d525f8d.pngI was able to fix this by adding z-index to the class that gets applied on click , but it ...
@ -webkit-keyframes flipAndZoomAnim { 0 % { -webkit-transform : rotateY ( 0deg ) scale ( 0.5 ) translateZ ( 1px ) } 20 % { -webkit-transform : rotateY ( 180deg ) scale ( 0.5 ) translateZ ( 1px ) } 40 % { -webkit-transform : rotateY ( 180deg ) scale ( 1.0 ) translateZ ( 1px ) } 80 % { -webkit-transform : rotateY ( 180de...
Display div affected by CSS3 animation on top
JS
I was considering ways to create arrays containing a default value using native methods and ended up withExpecting it to be 2 or 3 times slower than a while loop , as the native methods have to loop twice whereas while loops only once , so I compared it on jsperf againstand it is actually 18 to 27 times slower ( tested...
function pushMap ( length , fill ) { var a = [ ] , b = [ ] ; a.length = length ; b.push.apply ( b , a ) ; return b.map ( function ( ) { return fill ; } ) ; } function whileLengthNew ( len , val ) { var rv = new Array ( len ) ; while ( -- len > = 0 ) { rv [ len ] = val ; } return rv ; }
Why is filling a new Array so much faster with a while loop ?
JS
I made this ( run snippet below ) I just need to add one feature to be able to use it on the site I 'm building it for . Some of the floating shards need to be blurred to give a sense of depth . Can Canvas do this , and if so , how ?
var Canvas = document.getElementById ( ' c ' ) ; var ctx = Canvas.getContext ( '2d ' ) ; var resize = function ( ) { Canvas.width = Canvas.clientWidth ; Canvas.height = Canvas.clientHeight ; } ; window.addEventListener ( 'resize ' , resize ) ; resize ( ) ; var elements = [ ] ; var presets = { } ; presets.shard = functi...
HTML Canvas , blurring drawn polygon
JS
I ca n't seem to putting the width and height of an img into another class css . If you could just give me a hint that would be nice ! Here 's my code : Of course its wrapped around a document.ready . Here is the HTML where i want to take the width and height of the image : And here is the div class where i want to giv...
$ ( '.Main_hover ' ) .each ( function ( ) { var $ this = $ ( this ) ; var w = $ this.find ( 'img ' ) .width ( ) ; var h = $ this.find ( 'img ' ) .height ( ) ; $ ( `` .fusion-button-wrapper '' ) .css ( 'height ' , h ) ; $ ( `` .fusion-button-wrapper '' ) .css ( 'width ' , w ) ; } ) ; < div class= '' imageframe-align-cen...
Javascript get width and height of img and place it into css of another class
JS
I have two buttons that are using the same ng-click with different params.No matter what I do , the buttons pass the same param as what is in the first function call.With a simple controller function for testing , the same param gets logged . In this case , it is true for both.These seems to happen only in Ionic , not ...
< label class= '' item item-input '' > < button ng-click= '' takePicture ( true ) '' > Save Settings < /button > < button ng-click= '' takePicture ( false ) '' > Choose from Gallery < /button > < /label > $ scope.takePicture = function ( my_param ) { console.log ( my_param ) ; }
Function parameter the same in button ng-click
JS
for some reason I do that every time because I find it clean . I declare variables on top to use them below . I do that even if I use them only once.Here is an example ( using jQuery framework ) : I tend to do that in PHP too . Am I right if I believe it 's not very memory efficient to do that ? Edit : Thank you for al...
$ ( `` # tbListing '' ) .delegate ( `` a.btnEdit '' , `` click '' , function ( e ) { var storeId = $ ( this ) .closest ( `` tr '' ) .attr ( `` id '' ) .replace ( `` store- '' , `` '' ) , storeName = $ ( this ) .closest ( `` tr '' ) .find ( `` td : eq ( 1 ) '' ) .html ( ) , $ currentRow = $ ( this ) .closest ( `` tr '' ...
Is that a bad Javascript practice I 'm doing here ?
JS
I have an array which contains `` Zeros '' and I want to move all ofthe `` Zeros '' to the last indexes of the array.The expected output is : But instead I get :
[ 1,2,3,0,0,0,0 ] [ 1,2,0,3,0,0,0 ] let a = [ 0 , 1 , 2 , 0 , 0 , 3 , 0 ] ; let count = 0 ; let len = a.length ; for ( i = 0 ; i < len ; i++ ) { if ( a [ i ] == 0 ) { count = count + 1 ; a.splice ( i , 1 ) ; } } for ( j = 0 ; j < count ; j++ ) { a.push ( 0 ) ; } console.log ( a ) ;
Weird bug in Javascript splice method