lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
Just doing a little introduction to JavaScript . I 'm used to more than often testing the existence of my pointers in C++ so as not to crash.Never did I read Hamlet , but I read this page about null and undefined in JavaScript.And in a Nutshell I can : Honestly that is a little too much for me : ) . What is the classic...
if ( varname == null ) if ( varname === null ) if ( typeof ( varname ) ! = 'undefined ' ) if ( varname ! = undefined ) if ( 'varname ' in object ) if ( object.hasOwnProperty ( 'varname ' ) )
`` To Be or Not to Be '' about variables in JavaScript
JS
Following is my javascript function , I want to use variable selected outside function , but I am getting selected not defined error in console of inspect element . window.yourGlobalVariable is not solving my problem .
function showMe ( pause_btn ) { var selected = [ ] ; for ( var i = 0 ; i < chboxs.length ; i++ ) { if ( chboxs [ i ] .checked ) { selected.push ( chboxs [ i ] .value ) ; } } }
How to make a variable which is inside a function global ?
JS
When I create a blank object : Why ca n't I view the '__proto __ ' object when I create a new object , but I can when I add a function ? Edit : For completeness , to create a truly blank object ( no prototypal linkage ) , we could do : But for the purposes of the question , I 'll use the o = { } syntax.Edit 2 : This sh...
var o = { } ; var o = Object.create ( null ) ;
Why ca n't I view __proto__ upon object creation ?
JS
Why caching an application prevent Cors request ? I have an example , two html page exactly Identical except the second line : index.html linkindex2.html linkWhy the one without manifest is working fine and the one with manifest works only the first time and stop working when the application is cached ? ( press F5 seve...
< ! DOCTYPE html > < html manifest= '' main.appcache '' > < ! DOCTYPE html > < html >
Why caching HTML5 page prevent doing Cors request ?
JS
Guys i want to make my typing text in to Two lines.Here is my DemoPlz check this codeHTMLJAVA SCRIPT
< div id= '' container '' > < div class= '' writer '' > Hi ! This is a test text . < br > < br > Can any one Help me in this ? . < /div > < /div > var txt = $ ( '.writer ' ) .text ( ) ; var timeOut ; var txtLen = txt.length ; var char = 0 ; $ ( '.writer ' ) .text ( '| ' ) ; ( function typeIt ( ) { var humanize = Math.r...
Typing Text in Jquery
JS
We had this following query in our Node.JSAs you can see , the query is a collection of last 20 records entered . But then from this result we would like to do resort again to 1 in _id so in the list we will have ID 55 - 75 for instance ( the order ) . So the last one always at the bottom.How do we achieve this again ?
mongo.connect ( 'mongodb : //XXX : XXX @ ds054XXX.mlab.com:54289/XXXdb ' , function ( err , db ) { var collection = db.collection ( 'chatmessages ' ) var stream = collection.find ( ) .sort ( { _id : -1 } ) .limit ( 20 ) .stream ( ) ; stream.on ( 'data ' , function ( chat ) { socket.emit ( 'user message ' , chat.content...
How to resort the collection in MongoDB ?
JS
I 'm fixing up a template we 're using on one of our sites which has the following codeThis snippet works.I 've tried concatenating the static scripts like thisHowever , now I 'm getting an errorI 'm no noob when it comes to JavaScript stuff , but I ca n't imagine why combining the 3 inline scripts into a single < scri...
< script type= '' text/javascript '' src= '' http : //partner.googleadservices.com/gampad/google_service.js '' > < /script > < script type= '' text/javascript '' > GS_googleAddAdSenseService ( `` ca-pub-123 '' ) ; GS_googleEnableAllServices ( ) ; < /script > < script type= '' text/javascript '' > GA_googleAddSlot ( `` ...
How to combine inline JavaScripts into one ?
JS
When I updated angular-route 1.5.0 to 1.5.1 , I have an error : Angular Unit Test : Error : Unexpected request : GET When I launch karma , I have an error message : 1 ) Call getAll method [ App Category ] Error : Unexpected request : GET http : //myapp.com/app-category ? is_active=true No more request expected in /node...
describe ( ' [ App Category ] ' , function ( ) { beforeEach ( module ( 'myApp ' ) ) ; var $ httpBackend , HttpService , AppCategory ; beforeEach ( inject ( function ( _ $ httpBackend_ , _HttpService_ , _AppCategory_ ) { $ httpBackend = _ $ httpBackend_ ; HttpService = _HttpService_ ; AppCategory = _AppCategory_ ; } ) )...
Karma Error when update angular-route 1.5.0 to 1.5.1
JS
I am developing an application on shiny ( ui and server ) , and I want to implement a map with the hcmap function of the Highchart package . But , when implementing the map I found that there is a dependence of the function hcmap with the site : https : //code.highcharts.com/mapdata/.So my goal is to implement the map ...
library ( shinydashboard ) library ( shinydashboardPlus ) library ( highcharter ) library ( shiny ) shinyUI ( dashboardPagePlus ( dashboardHeader ( ) , dashboardSidebar ( ) , dashboardBody ( fluidRow ( box ( width = 6 , title= '' map '' , highchartOutput ( `` map '' ) ) ) ) ) ) shinyServer ( function ( input , output )...
hcmap with a local file javascript in R Shiny
JS
I want to use the jquery : not selector in such a way that when a bunch of elements do n't have a specified class , then i want to add a class to one of them.What I want to achieve is : 'when design-preview1 , design-preview2 design-preview 3 and design-preview 4 do not have the class `` selected '' , add class `` sele...
$ ( `` .design-preview1 , .design-preview2 , .design-preview3 , .design-preview4 '' ) .not ( `` .selected '' ) . $ ( `` .design-preview1 '' ) .addClass ( 'selected ' ) ; } ) ; $ ( '.pop-design1 ' ) .click ( function ( ) { $ ( `` .design-preview li : not ( .design-preview2 ) .selected '' ) .removeClass ( 'selected ' ) ;...
How to use jQuery : not selector for more than one element at a time
JS
I have a piece of code where I have two buttons and when I press one button I want a div to flip on the y-axis and when I press the other button I want the same div to flip on the x-axis . this works just fine when I use the button for the y-axis even if the previous flip was on the x-axis . But when I want to switch f...
var ax = ' x ' ; $ ( document ) .ready ( function ( ) { $ ( ' # card ' ) .flip ( { trigger : 'manual ' , axis : ' x ' } ) ; $ ( ' # left ' ) .click ( function ( ) { if ( ax ! = ' y ' ) { $ ( `` # card '' ) .flip ( { axis : ' y ' } ) ; $ ( `` # card '' ) .on ( 'flip : change ' , function ( ) { $ ( ' # card ' ) .flip ( '...
jQuery flip plugin switch function fails on switch
JS
If I create a Node.js module `` augs '' that containsThen type in the REPLI get back 'undefined'.We have a significant amount of code in our web app that relies on convenience methods added to Object , Function , Date , etc . We 're trying to share some code between the frontend and the backend , but it seems like Node...
Object.foo = `` bar '' ; require ( `` ./augs '' ) ; typeof Object.foo
Can I augment Object , Function , Date , etc . with `` static methods '' in Node ?
JS
Try this in dev tools console : the output is { } , instead of something sensible.Any ideas ?
JSON.stringify ( document.body.getBoundingClientRect ( ) )
why does n't getBoundingClientRect serialise with JSON.toStringify ?
JS
How do I define a get ( ) routing in an expressJS application with the intention of doing easy unit testing ? So as a first step I moved the function of get ( ) in an own file : index.jslib/setStatus.jslib/getStatus.jsSo first of all I 'm not quite sure , if I split that code correctly - thinking of doing unit testing....
const express = require ( 'express ' ) const socketIo = require ( 'socket.io ' ) const Gpio = require ( 'pigpio ' ) .Gpioconst app = express ( ) const server = http.createServer ( app ) const io = socketIo ( server ) const setStatus = require ( './lib/setStatus.js ' ) app.locals [ 'target1 ' ] = new Gpio ( 1 , { mode :...
expressJS/jestJS : How to split get ( ) function to write simple jest unit test ?
JS
I am displaying a huge tabular structure with knockout . The user has the option to remove rows by clicking a checkbox on the row : The problem is that the table has to be re-rendered on click , which on slow computers/browsers takes up to one or two seconds - the checkbox changes its state after the table has been ren...
data-bind= '' checked : row.removed '' ko.bindingHandlers.checkedWithLoader = { update : function ( element , valueAccessor , allBindings ) { loader.show ( ) ; // call knockout 's default checked binding here loader.hide ( ) ; } } ;
How to create a wrapper function for default knockout bindings
JS
I am loading a CZML file in cesium . And want to highlight multiple polygons ( like myid_1 , myid_2 , myid_3 ) if polygon with id as `` myid '' is clicked . But I am unable to process it as I am not getting the entity objects of other polygonsto process its color change.On click handler is as below.How can I get the ot...
var handler = new Cesium.ScreenSpaceEventHandler ( scene.canvas ) ; handler.setInputAction ( function ( click ) { var pickedObject = scene.pick ( click.position ) ; if ( Cesium.defined ( pickedObject ) ) { console.log ( pickedObject.id instanceof Cesium.Entity ) ; //returns true var colorProperty = Cesium.Color.YELLOW ...
How to update polygon material if I know Id of polygon ?
JS
I want append < span > < /span > tag in my every < a > tag : now : I want : now , i using below codes to implement it : I think this codes is not good , how to simplify it ? thanks : )
< a href= # > aaa < /a > < a href= # > bbb < /a > < a href= # > ccc < /a > < a href= # > < span > aaa < /span > < /a > < a href= # > < span > bbb < /span > < /a > < a href= # > < span > ccc < /span > < /a > $ ( function ( ) { var buttons = $ ( `` a '' ) ; var text=buttons.text ( ) ; buttons.text ( `` '' ) ; buttons.pre...
how to simplify my code using jquery ?
JS
Background information I am setting up a function which creates a date array based on a start date and an end date . The function will receive start and end dates , which have first been formatted to year-month-dayT12:00:00:00 format and then converted into milliseconds with .getTime ( ) format . My script I have made ...
var $ date_array = [ ] ; function calc_workdays_between_dates ( a , b ) { function $ create_date_array ( $ start_date , $ end_date ) { var $ counter = 0 ; while ( $ start_date ! == $ end_date ) { var x = new Date ( $ start_date ) ; x.setDate ( x.getDate ( ) + $ counter ) ; $ date_array.push ( x ) ; $ start_date = x.get...
While loop counter increasing `` exponentially '' in spite of using ++
JS
I 'm doing some validation on a HTML form using min and max attributes . I also want to prevent form submission if the submit button is clicked once to prevent multiple form submissions before a page is reloaded . Here 's the inline code for disabling the button : Here 's the number input field code : If I include the ...
< input type= '' submit '' name= '' name '' value= '' REGISTER '' onclick= '' this.disabled=true ; this.form.submit ( ) ; '' > < input type= '' number '' name= '' endNo '' placeholder= '' END '' min= '' 5 '' max= '' 20 '' >
Why is disabling form submission affecting min and max attributes ?
JS
I am using the Laravel framework and fetching data . Now I am trying to filter the data with Ajax and jQuery . But a couple problem that I am facing ... UPDATED 4When I start filter , there is this error looping : `` /var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php '' , `` line ...
public function search ( Request $ request ) { $ q = $ request- > q ; $ sortbyprice = $ request- > sortbyprice ; $ region = $ request- > region ; $ rooms = $ request- > rooms ; $ price = $ request- > price ; $ max = $ request- > input ( 'max ' ) ; $ min = $ request- > input ( 'min ' ) ; $ paginationData = [ ' q ' = > $...
Is it possible to filter already fetched data with jQuery
JS
I have a simple loading bar made with css , you update the css and the bar fills , super simple.I decided to update the bar with jQuery , works great but now I throw it into a practical environment . I have a bunch of files being downloaded and each time a file successfully downloads , it updates the position . The mai...
var colorInc = 100 / 3 ; function setWater ( myval ) { var val = myval ; var waitForMe = $ .Deferred ( ) ; if ( val ! = `` '' & & ! isNaN ( val ) & & val < = 100 & & val > = 0 ) { setTimeout ( function ( ) { waitForMe.resolve ( ) } , 100 ) ; var valOrig = val ; val = 100 - val ; if ( valOrig == 0 ) { // $ ( `` # percen...
Is there any way to wait for a Dom to be updated or asynchronously update the Dom ?
JS
Given the following code , where both a and b are Numbers representing values within the range of signed 32-bit signed integers : and assuming that the runtime is in full compliance with the ECMAScript 6 specifications , will the value of quotient always be the correct signed integer division of a and b as integers ? I...
var quotient = ( ( a|0 ) / ( b|0 ) ) |0 ;
Javascript : Is This Truly Signed Integer Division
JS
I 'm trying to make certain `` cards '' that display next to each other , and when the card is clicked , I want to get the id of the card . However , my function gets the id of the child elements when I click it , which is undefined , rather than of the parent card , unless I click on the border of the card div . How d...
< div id= '' parentCard '' onclick= '' getID ( event ) '' > < div id= '' child1 '' > I 'm a child < /div > < div id= '' text '' > < p > Text 1 < /p > < p > Text 2 < /p > < p > Text 3 < /p > < /div > < /div > function getID ( event ) { console.log ( event.target.id ) ; }
How do I get the id of a clicked parent element in a card ?
JS
I have a JSON document of variable depth . An example : What I am trying to do is to retrieve the values of certain keys , say text . Since I do not know where these keys might appear in the .JSON , I need to use a recursive function . I then try to display these keys and values in a HTML file.I have a preliminary atte...
[ { `` type '' : `` firsttype '' , `` text '' : { `` id '' : `` content '' } } ] $ .getJSON ( `` file.json '' , function getText ( oValue , sKey ) { links = [ ] ; if ( typeof oValue == `` object '' || typeof oValue == `` array '' ) { for ( i in oValue ) { getText ( oValue [ i ] , i ) ; } } else { links.push ( `` < li i...
Can I have a recursive JavaScript function inside a $ .getJSON function ?
JS
I use only jQuery for writing JavaScript code . One thing that confuses me is these two approaches of writing functions , First approachSecond approachWhat is the difference between the two and why should one use the first approach or the second approach ?
vote = function ( action , feedbackId , responseDiv ) { alert ( 'hi ' ) ; return feedbackId ; } function vote ( action , feedbackId , responseDiv ) { alert ( 'hi ' ) ; return feedbackId ; }
What is the difference between these two functions/approaches ?
JS
I am looking at someone else 's code and trying to understand it . They have a function call name surrounded in parenthesis : Is this different than : edit : Just to add more context , the function myFunction has the following form :
myButton.onclick = ( myFunction ) ( a , b , c ) ; myButton.onclick = myFunction ( a , b , c ) ; myFunction = function ( a , b , c ) { return function ( ) { // do something with a , b , and c } }
What do brackets surrounding function name mean ?
JS
In ECMAScript6 an iterator is an object with a next ( ) method that returns an object with two properties : { value , done } . E.g . : Having created an iterator one finds it is not very useful in its own right as there 's no built-in syntax to take advantage of an iterator . Instead , one has to do things like : '' It...
function createIterator ( ra ) { let i = 0 ; return { next ( ) { if ( i < ra.length ) return { value : ra [ i++ ] , done : false } ; else return { value : undefined , done : true } ; } } ; } const it = createIterator ( [ ' a ' , ' b ' , ' c ' ] ) ; while ( true ) { const o = it.next ( ) ; if ( o.done ) break ; else con...
why do we need both iterable and iterator concepts ?
JS
the result is : time1 : 1481ms , time2 : 102ms , i running this test on nodejs , but i do n't know why the first test run slower than the second one .
function add ( x , y ) { return x + y ; } console.time ( `` time1 '' ) ; for ( var i = 0 ; i < 90000000 ; ++i ) { add ( 1 , 2 ) ; add ( ' a ' , ' b ' ) ; } console.timeEnd ( `` time1 '' ) ; function addText ( x , y ) { return x + y ; } function addNumber ( x , y ) { return x + y ; } console.time ( `` time2 '' ) ; for (...
JavaScript test on V8
JS
I have to insert data in a XML file in a specific place . For example : I have to find 'data2 ' using DOM than go back and insert new elements in the 'tag2 ' which contains 'data2 ' in it . More specifically I am writing a function that gets arguments : the search key and the data to insert . How can I find 'data2 ' an...
< tag1 > < tag2 > < tag3 > data < /tag3 > < /tag2 > < tag2 > < tag3 > data2 < /tag3 > < /tag2 > < /tag1 >
How to find XML element by the data in it using DOM ?
JS
I 'm using Modernizr and am having trouble getting a jquery UI datepicker to display in-place of the native html5 date input in FireFox . This fiddle shows what I mean - open it in FireFoxWhen opening in Firefox I just get a text inputhttp : //jsfiddle.net/Te2yL/Code : To confirm , when open in FireFox the Jquery-ui js...
< head > //Include Modernizr - all items are included ( full-fat version ) < script src= '' assets/js/vendor/modernizr.js '' > < /script > < /head > < body > < input type= '' date '' id= '' start-date '' ng-model= '' someVariable '' format-date class= '' form-control date '' / > < script > Modernizr.load ( { test : Mod...
Modernizr : Failing to execute datetime ( ) on date input in Firefox
JS
I 'm following Adjust image size based on the font size to change image size according to text size , but have quite different results from macOS and Android ( both with Chrome ) .On Desktop 's Chrome : On Android 's Chrome : You can see that compared with text , the image on Android is significantly smaller . How do I...
< ! DOCTYPE html > < html > < head > < style > body { text-rendering : optimizeLegibility ; -webkit-font-smoothing : subpixel-antialiased ; -webkit-font-smoothing : antialiased ; -moz-osx-font-smoothing : grayscale ; } .logos > img { display : inline-block ; height : 100vh ; max-height : 5em ; } .test-logos { display :...
Adjust image size based on the font size on Android Chrome
JS
I 'm doing a Unity project where I have the need to convert UTM coordinates to latitudes and longitudes . I have tried several C # solutions , but none of them were accurate enough . But I found some Javascript code that gives out the exact result I 'm looking for ( https : //www.movable-type.co.uk/scripts/latlong-utm-...
var a = 6378137 ; var f = 1/298.257223563 ; var e = Math.sqrt ( f* ( 2-f ) ) ; var n = f / ( 2 - f ) ; var n2 = n*n , n3 = n*n2 , n4 = n*n3 , n5 = n*n4 , n6 = n*n5 ; var A = a/ ( 1+n ) * ( 1 + 1/4*n2 + 1/64*n4 + 1/256*n6 ) ; var a = 6378137 ; var f = 1 / 298.257223563 ; var e = Math.Sqrt ( f * ( 2 - f ) ) ; var n = f /...
C # and Javascript code calculations giving different results
JS
Here is my snippet , And my data here , Everything is fine here , but when i enable the legend here , it is giving me the gradient irrespective of the color column I am using , how do i specify the color column with changelabel as legend like
output $ map < - renderHighchart ( { region_map = hcmap ( `` countries/nz/nz-all '' ) highchart ( type = `` map '' ) % > % hc_title ( text = `` Average '' ) % > % hc_add_series_map ( map = region_map , df = data1 , joinBy = `` name '' , value = `` LTA '' , borderColor = `` # 141B4D '' , color = `` color '' , showInLege...
Highmap R ( or ) javascript - adding custom legend
JS
I have this function : and I am trying to test it with the following : Even though I am clearly calling callback ( ) multiple times ( whilst testing only ) , expect ( callback ) .to.have.been.called.once ; is always asserting to true . I have checked on the Chai api that that expects the call to be exactly once , altho...
let removePresentation = function ( presentationName , callback ) { let rimraf = require ( 'rimraf ' ) ; callback ( ) ; callback ( ) ; callback ( ) ; if ( ! presentationName || ! presentationName.trim ( ) ) { callback ( ) ; return ; } presentationName = presentationName.replace ( '.zip ' , `` ) ; rimraf ( './presentati...
Why are these tests passing ?
JS
I need to replace a specific character for all elements whose class is the same with jQuery . Consider this html code : I need to replace all the ® charactesr with superscript tags with this code : However , this code will replace the first occurrence only . For the second and beyond occurrences , it 'll replace the wh...
< div class= '' product-name '' > < h1 > Apple® < /h1 > < /div > < div class= '' product-name '' > < h2 > iPhone® < /h2 > < /div > < div class= '' product-name '' > < h3 > iPhone 5S® < /h3 > < /div > $ ( '.product-name ' ) .html ( $ ( '.product-name ' ) .html ( ) .replace ( /®/gi , ' < sup > & reg ; < /sup > ' ) ) ;
How to replace the same character multiple times ?
JS
Tried to use curry function to write if condition ( without `` if '' `` true '' and `` false '' ) . Have no idea how to do it right ! Can anyone help and show me how to do it ? It should return 1 or 2 depends on which function is getting pass to if condition . But this code does not work at all .
const True = ( ) = > { } ; const False = ( ) = > { } ; const If = True = > False = > ifFunction ( True ) ( False ) ; const ifFunction = If ( True ) ; ifFunction ( ' 1 ' ) ( ' 2 ' ) ; // 1console.log ( If ( True ) ( ' 1 ' ) ( ' 2 ' ) ) ; // 1console.log ( If ( False ) ( ' 1 ' ) ( ' 2 ' ) ) ; // 2
currying function instead of if condition in javascript
JS
https : //codepen.io/popmotion/pen/KyewbvThis is not working for some reason.https : //popmotion.io/pure/ as mentioned here it has to be whenever I use it clamp movement is showing as undefined . What should it be actually ? Any may to make that working ?
const slider = document.querySelector ( '.slider ' ) ; const sliderX = value ( 0 , styler ( slider ) .set ( ' x ' ) ) listen ( slider , 'mousedown touchstart ' ) .start ( ( ) = > { pointer ( { x : sliderX.get ( ) } ) .pipe ( ( { x } ) = > x , clampMovement ) .start ( sliderX ) ; } ) ; listen ( document , 'mouseup touch...
Popmotion carousel fix for new version
JS
I just got Javascript : The Good Parts by Douglas Crockford and I 'm having some difficulty understanding one of his examples regarding prototypes . The code in the book reads as follows : I 'm assuming that this code is used to target a function 's prototype . But why use such a complex approach ? Why not just use var...
if ( typeof Object.create ! == `` function '' ) { Object.create = function ( o ) { var F = function ( ) { } F.prototype = o ; return new F ; } ; }
confusion about javascript exercise
JS
I am using CSS Modules in an Angular Project with Webpack.I had already transformed the class names in .css and .scss files with postcss-modules.Then with posthtml-css-modules I had changed the values on the class property in html elements for his hash value defined by postcss-modules.I can say that everything is worki...
function setMyClassNameInHash ( condition ) { return condition ? doHash64 ( 'myClass1 ' ) : doHash64 ( 'myClass1 ' ) ; }
Use [ hash : base64:5 ] in JavaScript / TypeScript file
JS
I have been working with the module pattern in JavaScript and have a question about scope and square bracket notation ( SBN ) . Please consider the following simple example.From within the init function is it possible to call myMethod using SBN ?
( function ( module ) { function myMethod ( text ) { console.log ( text ) ; } module.init = function ( name ) { // here I want to do something like // eval ( name ) ( `` hello '' ) ; // using SBN , e.g . .. [ name ] .call ( this , `` hello '' ) ; } ; } ) ( window.Module = window.Module || { } ) ; Module.init ( `` myMet...
Square bracket notation and scope in JavaScript module pattern
JS
Given this JavaScript code ( which is just a comment referring to a url ) : JSLint with `` Safe Subset '' turned on will say How can a comment be dangerous ? Comments , by definition , are n't parsed ! Or are they ? Edit : Using a different url is n't necessarily dangerous . For example this : does n't trigger the flag...
// see http : //enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ Dangerous comment.// http : //enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ // http : //enterprisejquery.com
jslint flagging `` dangerous comment ''
JS
In rails 3.1 , does .coffee and //= require files get processed only once or with each assetrequest ? For example , I have a fileIdeally , the server would compile these to js ONCE , then bundle them , then create a static file . But if it happens on each asset requests , it 's going to be wasting cycles repeating it ?...
//= require source/main.js.coffee//= require source/second.js.coffee//= require source/third.js.coffee
Does the asset pipeline rails 3.1 waste cycles ?
JS
I have hierarchical data like this : I want to build tree-like grid by flattening that data . I am using following directives : The problem is that , in collection added from link method , depth from parent scope is appended to newDepth . As a result depth for level 3 nodes has value depth= '' 3 2 1 `` .How to disable ...
[ { `` children '' : [ { `` children '' : [ ... ] , [ ... ] } , { `` children '' : [ ... ] , [ ... ] } , ] , [ ... ] } ] app.directive ( 'tree ' , function ( hierarchyService , logger , $ timeout ) { return { scope : { data : '= ' } , restrict : ' E ' , replace : true , template : ' < div > ' + ' < table class= '' tabl...
Angular appends parent attribute value
JS
Based on the example from MDN , I 've created my own extension that showing just a 'hi ' message . I 've included a file named `` popup.js '' via tag . But this file is not getting executed . This is my manifest.json file : This is my popup.html file : There is only a single line in my popup.js file . That is , But I c...
{ `` manifest_version '' : 2 , `` name '' : `` Ext '' , `` version '' : `` 1.0 '' , `` description '' : `` Shows a hi message . `` , `` icons '' : { `` 48 '' : `` icons/ff.jpg '' } , `` permissions '' : [ `` tabs '' ] , `` browser_action '' : { `` default_icon '' : `` icons/toggle-off.png '' , `` default_title '' : `` ...
Firefox extension : JavaScript file included via script tag is not working
JS
On my first event I will open a mbox dialog . mbox is a kind of extention for bootbox , which is for showing a modal . I need mbox to use another template as modal content.So in the modal will be loaded with the content of createElement-Template . If the user has done some input changes the modal should be closed . The...
Template.main.events ( { 'submit form ' : function ( event , template ) { event.preventDefault ( ) ; var bbox = mbox.dialog ( { title : 'title ' , message : Template.createElement } ) ; } } ) ; Template.createElement.events ( { 'change input ' : function ( event , template ) { bbox.modal ( 'hide ' ) ; } } ) ; var bbox ...
Close modal which has been created in another event function
JS
I want to make `` Spinning Wheel '' type of game , in that the user can choose three possible outcomes , and then , after they can spin the wheel , if any of the chosen three come up then he/she is a winner.In the demo below you can see that , after spinner stops , the result is not the right value . After spinner itse...
//set default degree ( 360*5 ) var degree = 1800 ; //number of clicks = 0var clicks = 0 ; $ ( document ) .ready ( function ( ) { /*WHEEL SPIN FUNCTION*/ $ ( ' # spin ' ) .click ( function ( ) { //add 1 every click clicks ++ ; /*multiply the degree by number of clicks generate random number between 1 - 360 , then add to...
Wheel of luck - Final selection does n't match pointer
JS
I had someone run a pentest against an application recently and one of the critical problems it found was when some garbage was passed in a URL like this : The problem is that the attacker simply adds a slash then some encoded javascript ( an image tag with alert box ) , which kills the page . Simple and effective atta...
http : //example.com/index.php/ % 27 % 3e % 3c % 69 % 4d % 67 % 20 % 53 % 72 % 43 % 3d % 78 % 20 % 4f % 6e % 45 % 72 % 52 % 6f % 52 % 3d % 61 % 6c % 65 % 72 % 74 % 28 % 34 % 37 % 34 % 31 % 32 % 29 % 3e
How to protect against this type of attack ?
JS
I have a square , when clicked it appears in a random location and it also change size ( so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace ) .sometimes the square exceed his container borderHow can I make sure that the square will never exceed his container ?
function position ( ) { var positionTop = Math.random ( ) * 100 ; var positionLeft = Math.random ( ) * 100 ; var position = `` position : relative ; top : '' + positionTop + `` % ; left : '' + positionLeft + `` % ; '' return position ; } document.getElementById ( `` shape '' ) .onclick = function ( ) { document.getElem...
How to prevent element from exceeding his container borders
JS
I did the same thing he did here : How to correctly import the Angular Material module through a shared module in Angular 4 ? Except that I want to create an ui-kit like template then use it in different apps with different locations ( they are not in same folder ) .Currently , I 'm doing that and everything works fine...
< button mat-raised-button color= '' primary '' > Click me ! < /button > Error : StaticInjectorError [ ElementRef ] : StaticInjectorError [ ElementRef ] : NullInjectorError : No provider for ElementRef ! at _NullInjector.get ( core.js:993 ) at resolveToken ( core.js:1281 ) at tryResolveToken ( core.js:1223 ) at StaticI...
sharedModules into multiple completely different apps
JS
I do n't quite understand why the if statement evaluates true but the console.log comparison does not . I double checked the MDN documentation and they say { } is a truthy value . So why does my console.log statement disagree ? I did try , as a last ditch , using == instead of === .
var test = { } ; console.log ( test ) ; console.log ( test === true ) ; console.log ( { } === true ) ; if ( { } ) { console.log ( 'What the ? ' ) ; }
Why does my empty object literal log as false ?
JS
I have a toggle button that changes a bit of text . The problem I run into is if I have 2 words and I want to change the text of one it changes one but when I toggle it off style is removed from both spans instead of the span of the selected text.How can I remove the span from the specific text selected and leave the s...
function headuppercase ( e ) { tags ( 'span ' , 'sC ' ) ; } function tags ( tag , clas ) { var ele = document.createElement ( tag ) ; ele.classList.add ( clas ) ; wrap ( ele ) ; } function wrap ( tags ) { var el = document.querySelector ( 'span.sC ' ) ; sel = window.getSelection ( ) ; if ( ! el ) { if ( sel.rangeCount ...
Toggle a specific Text with JavaScript not working as expected
JS
I ` ve faced an issue with Chrome version 45 . Issue : When i do try to remove last child div with JavaScript the Chrome engine hides all other tags in parent div ( span and b tags will be hidden ) : It looks as though only the current Chrome version ( 45 ) is affected . Beta and dev channels are not affected . For tes...
< div class='parentDiv ' id='pdiv ' > Some text < span style='color : red ; ' > BBBBBBBBBBBBBBBBBBBBBBB < /span > more example text more example < b style= '' color : green ; '' > more < /b > example text more example more example text more example more example text more example more example text example text example t...
Possible Chrome 45 bug : removeChild method causes other nodes in parent element to disappear
JS
Here is my Plunker : https : //plnkr.co/edit/rBGQyOpi9lS0QtnCUq4LI want to console.log ( ) what is being typed in each textarea tag . Typing in a textarea triggers the printStuff ( ) function : When I start typing in any textarea , I get this error : How do I fix this error ? UPDATED WITH MannFromReno 's ANSWERI still ...
$ scope.printStuff= function ( customize , item ) { console.log ( customize [ item.index ] .data ) ; } ; angular.js:14290 TypeError : Can not read property 'data ' of undefined at b. $ scope.printStuff ( index.html:31 ) at fn ( eval at compile ( angular.js:15118 ) , < anonymous > :4:299 ) at b. $ eval ( angular.js:1792...
Can not print data from ngRepeat'ed ` textarea `
JS
I would consider myself to be reasonably competent with JavaScript and familiar with many of the different ways of achieving the same thing . But today I came across some function syntax which I had n't seen before : If I were to write such code I would have done it like this : Ignoring the fact that this is not the be...
function document.body.onload ( ) { alert ( 'loaded ' ) ; } document.body.onload = function ( ) { alert ( 'loaded ' ) ; }
JavaScript Function Syntax Explanation : function object.myFunction ( ) { .. }
JS
which would make it impossible to de-serialize correctly ( I would expect something like a= > a+10 instead.Is there a way to do it right ?
const makeIncrementer = s= > a= > a+smakeIncrementer ( 10 ) .toString ( ) // Prints ' a= > a+s '
How to correctly serialize Javascript curried arrow functions ?
JS
While I was messing around with truth tables in JavaScript , I noticed that the following evaluates to true : Why ? I 've only tested this in Firefox , and I 'm sure I could dig up the details in the ECMAScript 2.6.2 spec , but TBH I 'm feeling lazy .
var a , b , c ; a = { } ; b = function ( ) { } ; c = a < b ; console.log ( c ) ;
Why is { } < function ( ) { } ?
JS
I 've used setTimeout plenty of times passing a function as a reference e.g.In some cases , to preserve the value of this I 've had to assign it to a variable before hand , but do n't understand why the following does not work : Using an anonymous function however , does work :
setTimeout ( someFunction , 3000 ) ; var logger = { log : function ( ) { var that = this ; console.log ( that.msg ) ; setTimeout ( that.log , 3000 ) ; } , msg : `` test '' } ; logger.log ( ) ; var logger = { log : function ( ) { var that = this ; console.log ( that.msg ) ; setTimeout ( function ( ) { that.log ( ) } , 3...
Why is an anonymous function required to preserve `` this '' using setTimeout
JS
I have a list with 10.000 entrys . for exampleI dont use an array ( 0,1,2,3 ) because i can checkvery fast - > if this hash exist or not.But i am not sure , is this a good solution ? Is it maybe a problem to handle an object with 10.000 entries ? EDIT : I try to build an rss feed reader which shows only new feeds . So ...
myList = { } ; myList [ hashjh5j4h5j4h5j4 ] myList [ hashs54s5d4s5d4sd ] myList [ hash5as465d45ad4d ] ... . if ( typeof myObject [ hashjh5j4h5j4h5j4 ] == 'undefined ' ) { alert ( 'it is new ' ) ; } else { alert ( 'old stuff ' ) ; }
Best way to store a huge list with hashes in Javascript
JS
I 'm trying to add an authorization layer to an API , and the current design I have results in more SQL queries than it feels like should be required , so I 'm wondering how I can simplify this.ContextHere 's the database schema for this piece of the problem : And the API endpoint in question is GET /users/ : user/team...
CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY , email CITEXT NOT NULL UNIQUE , password TEXT NOT NULL , name TEXT NOT NULL , created_at DATE NOT NULL DEFAULT CURRENT_TIMESTAMP ) ; CREATE TABLE IF NOT EXISTS teams ( id TEXT PRIMARY KEY , email CITEXT NOT NULL , name TEXT NOT NULL , created_at DATE NOT NULL DEFA...
How to perform complex API authorization in fewer SQL queries ?
JS
I 'm only familiar with HTML and CSS , which I use on a daily basis . ! Important CSS overrides are something I have to do TONS of in order to customize websites for clients that use a 3rd party CRM system , but now I 've been asked to see if I can override what a Javascript image slider does ; namely if I can force it...
< script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { var randSlick = Math.floor ( Math.random ( ) * $ ( ' # carousel > div ' ) .length ) ; $ ( ' # carousel ' ) .slick ( { infinite : true , autoplay : false , autoplaySpeed : 10000 , slidesToShow : 1 , slidesToScroll : 1 , arrows : false , fade :...
Hacking/Overriding Javascript
JS
I have this string : The string is divided in 3 categories . Date ( dd/mm/yyyy ) NumberCharacterthus : 07-09-2012 73 ABCI want to get the sum of number , where date is 09 and has character ABC.Currently , from another question I found out how to retrieve just the date , when string has no charactersExample : http : //j...
var result = `` / 07-09-2012 73 ABC / 11-09-2012 195 DEF/ 03-09-2012 95 / 04-09-2012 188 ABC / 31-10-2012 72 / 18-09-2012 205 / 26-09-2012 244 ABC / 14-09-2012 86 / 20-09-2012 92 DEF / 28-09-2012 97 / 01-09-2012 95 DEF/ 17-09-2012 95 / 17-09-2012 83 / 12-09-2012 95 / 18-09-2012 95 ABC / 18-09-2012 69 / 21-09-2012 95 / ...
jQuery : Access sum of a string of numbers with specific date and text
JS
At the moment I 'm coding a web application that imports image data from Google Maps via the Static API - http : //code.google.com/apis/maps/documentation/staticmaps/ - into an HTML5 canvas . Unfortunately , I 've run into the problem of not being able to manipulate the pixel data from Google Maps due to cross domain r...
var ctx = document.getElementById ( 'canvas ' ) .getContext ( '2d ' ) ; var img = new Image ( ) ; img.src = 'LINK TO GOOGLE MAPS IMAGE ' ; img.onload = function ( ) { ctx.drawImage ( img,0,0 ) ; }
What Does This Mean and How Does It Help ?
JS
I am using the D3 library to create some graphs . They are placed within a viewbox ( see snippet below under `` output '' ) . The viewbox is to allow for responsive scaling . However at certain resolutions , the line either disappears , or blurs/thickens . I think this is linked to it not being pixel perfect at those r...
shape-rendering : crispEdges ; this.y = d3.scale.linear ( ) .rangeRound ( [ this.height , 0 ] ) ; this.yAxis = d3.svg.axis ( ) .scale ( this.y ) .tickSize ( this.width ) .tickValues ( [ 0 , 25 , 50 , 75 , 100 ] ) .tickFormat ( function ( d ) { return parseInt ( d , 10 ) + `` % '' ; } ) .orient ( `` right '' ) ; this.y....
How to stop paths from blurring/disappearing in D3 when using a viewbox ?
JS
$ .when behaves differently depending on whether one or more Deferred object are passed to it . This behaviour is documented in the docs - but the problem is that it is forcing me to write two different code paths . Case I : Case II : Any way to elegantly handle this without resorting to checking the length of dfd or t...
function foo ( dfds ) { $ .when.apply ( this , dfds ) .done ( function ( ) { console.log ( arguments ) ; } ) ; } foo ( [ $ .getJSON ( `` http : //freegeoip.net/json/8.8.8.8 '' ) , $ .getJSON ( `` http : //freegeoip.net/json/8.8.8.9 '' ) ] ) ; ... ./* Output ( what I 'd come to expect ) */ [ Array [ 3 ] , Array [ 3 ] ] ...
Jquery : $ .when behaves differently depending on number of arguments
JS
I have an array like thisAnd I can get IP address of PC Client by using my own function : My question is how can I check if client IP is within my allowed subnet , I tried to use indexOf ( ) function , but result was wrong.For example :
var ALLOW_SUBNET = [ '192.168.1 . ' , '192.168.2 . ' , '192.168.3 . ' , '192.168.4 . ' ] ; getIPClient ( ) var ipclient = input.getIPClient ( ) ; if IP Client is 192.168.1.115 = > allowif IP Client is 192.168.5.115 = > deny .
javascript check if an element content some part of an array
JS
I have the problem that I cant remove the Scrollbars of Firefox Quantum . Oh Chrome it works like a charm whith this css : Also I tried to remove it with jQuery and with adding it directly to the body tag like this style= '' overflow : hidden ; '' Nothing of that works . It seems I cant get rid of them . How can I remo...
div : :-webkit-scrollbar { border : none ; width:0 ; background : rgba ( 0,0,0,0 ) ; display : none ; overflow-x : hidden ; overflow-y : hidden ; } div : :-webkit-scrollbar-track { border : none ; width:0 ; background : rgba ( 0,0,0,0 ) ; display : none ; overflow-x : hidden ; overflow-y : hidden ; } div : :-webkit-scr...
Javascript/Ionic3 Overflow : hidden disable scroll in Firefox
JS
What is this approach for ? For instance , from the Google OAuth API : To me , this would seem to be identical to simply outputtingI 'm assuming it is n't . so what 's the difference ?
( 0 , _.Q ) ( `` gapi.auth.authorize '' , _.Ek.Ff ) ; ( 0 , _.Q ) ( `` gapi.auth.checkSessionState '' , _.Ek.MH ) ; ( 0 , _.Q ) ( `` gapi.auth.getAuthHeaderValueForFirstParty '' , _.Ek.Qe ) ; ( 0 , _.Q ) ( `` gapi.auth.getToken '' , _.Ek. $ f ) ; ( 0 , _.Q ) ( `` gapi.auth.getVersionInfo '' , _.Ek.Wk ) ; ( 0 , _.Q ) ( ...
Purpose of ( 0 , obj.method ) ( param1 , param2 ) in Closure Compiler minified code
JS
I have a code responsible for cropping image and saving its cropped areas in a list of divs . Each of these divs represents each of the cropped images . But the problem is - I dont want them to be so huge , I want them to have fixed height and width , e.g . max 100x100px.Codesandbox with working image cropping : https ...
const width = pos.w + `` px '' ; const height = pos.h + `` px '' ; const marginLeft = - pos.x + `` px '' ; const marginTop = - pos.y + `` px '' ; return ( < div key= { i } style= { { width : width , height : height , backgroundSize : `` 400px 300px '' , backgroundPosition : ` top $ { marginTop } left $ { marginLeft } `...
Max-height and max-width for divs with dynamic backgrounds ?
JS
I am stuck on the following function which appears in a few other posts I 've also reviewed.Also given in this link . Javascript..totally lost in this tutorialIn the above explanation , the answer instead tried to set a goal of 11 . They have a start of 1 , which is first tested against 11 , and then a start of 6 which...
function findSequence ( goal ) { function find ( start , history ) { if ( start == goal ) return history ; else if ( start > goal ) return null ; else return find ( start + 5 , `` ( `` + history + `` + 5 ) '' ) || find ( start * 3 , `` ( `` + history + `` * 3 ) '' ) ; } return find ( 1 , `` 1 '' ) ; } print ( findSeque...
Eloquent Javascript 's findSequence clarification
JS
I 've got the following javascript that loads a form into a hidden div on the page and the shows the divthis loads a partial view with the following : when the javascript event is triggered , it is all loaded in correctly when viewing the DOM explorer , but the form is not shown . info before and after is shown , but n...
function load ( ) { ... stuff to get date and id ... var xhttp = new XMLHttpRequest ( ) ; xhttp.onreadystatechange = function ( ) { if ( xhttp.readyState==4 & & xhttp.status==200 ) { document.getElementById ( `` PopupDiv '' ) .innerHTML = xhttp.responseText ; document.getElementById ( `` PopupDiv '' ) .removeAttribute ...
Form not showing in IE
JS
I am new to AngularJS , and am trying to make formatted JSON based on the table tr and td values.The table tr is auto generated . Once the form is submitted , I try to generate the json values.After the form is submitted , I need to generate the JSON.I have 3 rows table , so I need to generate 3 object array the json I...
< form > < table > < ! -- Auto generated rows -- > < tr > < td > < input type= '' text '' class= '' form-control '' name= '' tname '' value= '' '' > < /td > < td > < select ng-model= '' selection1 '' class= '' form-control '' name= '' ttype '' value= '' '' > < option value= '' bbb '' selected > Test < /option > < optio...
AngularJS JSON format
JS
Why do these two dates are differents : Result : whereas these two dates are equals : Result : Another question is why do date1.setMonth ( 10 ) gives a date in December ( should be November ) .
var date1 = new Date ( ) ; date1.setFullYear ( 2012 ) ; // year ( four digits ) date1.setMonth ( 10 ) ; // month ( from 0-11 ) date1.setDate ( 1 ) ; // day of the month ( from 1-31 ) var date2 = new Date ( 2012 , 10 , 1 , 0 , 0 , 0 , 0 ) ; Date 1 : Sat Dec 01 2012 14:56:16 GMT+0100Date 2 : Thu Nov 01 2012 00:00:00 GMT+...
Difference in initialization of two dates in Javascript
JS
My application is storing multiple document types in the same bucket . I know it is not good practice but I have a limit on how many buckets I can create on my server and there is not way around it at the moment . The documents are prefixed with their types so when I get a document I just need to concatenate the prefix...
function ( doc , meta ) { var getStep = function ( stepName , exit , mapper ) { if ( meta.id.indexOf ( stepName ) ! == -1 ) { var hotelId = parseInt ( meta.id.replace ( stepName + ' _ ' , `` ) ) ; if ( hotelId > 0 ) { var result = { hotelId : hotelId , exit : exit } ; if ( mapper ! == undefined ) { mapper ( result ) ; ...
How to merge data in Couchbase with map reduce ?
JS
TL ; DR ; To make it simple , how can I filter multiple properties of a parent child array which could be several tree level deep . This is for an Open Source datagrid lib used by several hundred users.So I have an array of parent/children references , the children can also have children themselves and so on , there 's...
const myFiles = [ { id : 11 , file : `` Music '' , parentId : null } , { id : 12 , file : `` mp3 '' , parentId : 11 } , { id : 14 , file : `` pop '' , parentId : 12 } , { id : 15 , file : `` theme.mp3 '' , dateModified : `` 2015-03-01 '' , size : 85 , parentId : 14 , } , { id : 16 , file : `` rock '' , parentId : 12 } ...
How to filter multiple properties of a parent child array which could be several tree level deep
JS
In Angular 1.5 , I want to load the template via custom promise . The example code that I would like to run is The reason I want to do this is to load the template from a proxy iframe.If there is any way to provide my custom template resolver for promise that would too suffice .
var module = angular.module ( `` myApp '' , [ ] ) ; module.component ( `` component '' , { template : [ `` $ q '' , function ( $ q ) { var defer = $ q.defer ( ) ; setTimeout ( function ( ) { defer.resolve ( `` < p > Hello world < /p > '' ) ; } , 100 ) return defer.promise ; } ] , controller : function ( ) { } } ) ;
Load angular 1.5 component template via promise
JS
I 'm trying to iterate through all 32 bit floating point numbers in JavaScript to visually compare some methods for polynomial evaluation for accuracy . To do so , I 've implemented the code shown below . Unfortunately , this code is way too slow . Would there be any way to improve performance ? In C/C++ the equivalent...
function nextFloat ( f ) { // Note that this moves away from 0.0 // It will fail at +/- infinity and result in an NaN var bitRepr = floatToBits ( f ) ; bitRepr++ ; return bitsToFloat ( bitRepr ) ; } function prevFloat ( f ) { // Note that this moves towards 0.0 // This will fail at 0.0 and result in an NaN var bitRepr ...
Fast nextafter function in JavaScript
JS
I am trying to to extract a Json response in jquery sent from a php file.This is the .js code : This is the response from the php file : I have tried all combinations I can think of in both files , but nothing seems to work . It is a simple check for a username in the database . If I console log the data I get from the...
$ .ajax ( { url : 'index.php ? page=register ' , //This is the current doc type : 'POST ' , datatype : 'json ' , data : { 'userCheck ' : username } , success : function ( data ) { // Check if username is available or not } , error : function ( ) { alert ( 'Much wrong , such sad ' ) ; } } ) ; if ( $ sth- > fetchColumn (...
Extract Json response
JS
Just saw some interesting code while doing a typo in coffee-script . I got the following codeNow I 've read alot about the module pattern in javascript and why its a bad thing ( takes more memory , longer to create ... ) but of course the upside is having truly private functions/variables . Would n't the above code be ...
var Mamal , mam ; Mamal = ( function ( ) { var __priv_func ; function Mamal ( ) { } Mamal.prototype.simple_var = 5 ; Mamal.prototype.test = function ( ) { return __priv_func ( this ) ; } ; __priv_func = function ( instance ) { return alert ( instance.simple_var ) ; } ; return Mamal ; } ) ( ) ; mam = new Mamal ( ) ; mam...
Would this be a good way to do private functions ?
JS
in our project we are utilizing the jquery-mobile popup dialogOnce the dialog is shown , the first time I attempt to fill in the text on my phone ( Huawei P9 lite , Android 6.0.0 , Chrome 55.0.2883.91 ) , the popup closes and reopens.I am able to replicate this issue even on the demo Form popup.On a sightly larger devi...
< a href= '' # popupLogin '' data-rel= '' popup '' data-position-to= '' window '' class= '' ui-btn ui-corner-all ui-shadow ui-btn-inline ui-icon-check ui-btn-icon-left ui-btn-a '' data-transition= '' pop '' > Sign in < /a > < div data-role= '' popup '' id= '' popupLogin '' data-theme= '' a '' class= '' ui-corner-all ''...
Prevent jquery-mobile popup repositions for Huawei phones after text is entered to an input element
JS
I 'm trying to build a side navigation bar where categories are listed and upon clicking a category a respective sub list of subcategories is shown right below the category . And if the category is clicked again , the sub list contracts.So I 'm running a loop across category objects . Inside this outer loop , I 'm incl...
{ % load staticfiles % } { % load i18n pybb_tags forumindexlistbycat % } { % catindexlist as catindexlisted % } { % block body % } < div class= '' col-sm-12 col-md-12 col-xs-12 col-lg-12 body-container leftsidenavigator '' style= '' margin-top:15px ; '' > < div class= '' col-sm-12 col-md-12 col-xs-12 col-lg-12 leftside...
what could cause html and script to behave different across iterations of a for loop ?
JS
When my RegExp has a number of capturing groups , I want to know which group made the capture ( or at least the first/last such group , if there were more than one ) . If you 're familiar with Python , this is basically the equivalent of re.MatchObject.lastgroup . Some code to make it clearer : It prints : The result a...
var re_captures = new RegExp ( `` ( \\d+ ) | ( for ) | ( \\w+ ) '' , `` g '' ) ; var str = `` for me 20 boxes please '' ; var result ; while ( ( result = re_captures.exec ( str ) ) ! == null ) { console.log ( result [ 0 ] , 'at ' , result.index , result.slice ( 1 ) ) ; } for at 1 [ undefined , 'for ' , undefined ] me a...
Efficiently find which group matched in a RegExp search
JS
Quick question out of curiosity : code below works in Firefox and Chrome but not in Safari . Is this Javascript spec circumvented by Firefox and Chrome or is this a quirk in Safari ? in all ( firefox , safari and chrome ) works as expected.Cheers , Jeroen .
var a = { } ; a.var = `` test '' ; a [ `` var '' ] = `` test '' ; a.id = `` another test '' ;
attribute name `` var '' in javascript associative array
JS
Suppose there is a global variable which is a functionand there are methods of this class such as I want to ensure that YUI compression and obfuscation works without putting entire class inside a closure likeIs there a way to make YUI compression work without doing this ?
function MyClass ( ) { } MyClass.func1 = function ( ) { } ( function ( ) { function MyClass ( ) { } MyClass.func1 = function ( ) { } } ) ( ) ;
How do I obfuscate global variable using YUI without putting entire class inside a closure
JS
I 'm building a DSL which would benefit from being able to hack some JS internals . I understand this is a very bad idea in general JS usage , but for my purposes it 's okay . The following code works fine : But this does n't : Can someone who understands the internals a bit explain what 's happening here ? What 's the...
var str = new String ( `` blah '' ) ; str.valueOf = function ( ) { return 10 } console.log ( str * 10 ) ; // outputs 100 var str = `` blah '' ; str.valueOf = function ( ) { return 10 } console.log ( str * 10 ) ; // outputs NaN ( because str === `` blah '' ) String.prototype.valueOf = function ( ) { return 10 } console....
Replacing ` String.prototype.valueOf ` in JavaScript
JS
I want to implement a functionality in my app wherein the user can take snapshot of the current screen and can annotate it ( modify/scribble/etc ) and after that , can send it in an email . My app uses phonegap for ios as well as android support . But mainly it consist of javascript/jquery.So far I am able to achieve :...
$ ( '.myClass ' ) .html2canvas ( { onrendered : function ( canvas ) { var capturedCanvas = document.getElementById ( 'capturedImageView ' ) ; capturedCanvas.style.backgroundImage = 'url ( '+canvas.toDataURL ( ) ; + ' ) ' ; } } ) ;
Save captured screenshot after editing it
JS
I want to achieve something like an infinite drag like the one in Konva js Can anyone help me with this . I try varius things but non of them were ok. Im new in p5js and javascript . Please for any hints . Only this element prevents me from completing the entire project .
var grid ; var current_img ; var BgCat1 = [ ] ; var layerOne ; let show_grid = false ;
draggable backgroun
JS
can someone explain to me what is going on in the following code . The function is receiving n as parameter , so where is the m coming from ? The whole code is confusing.. if someone can explain ?
function greaterThan ( n ) { return function ( m ) { return m > n ; } ; } var greaterThan10 = greaterThan ( 10 ) ; console.log ( greaterThan10 ( 11 ) ) ; // → true
Higher order javascript functions
JS
SITUATION : I would need to download the childNode , then set ( ) it into the other node.Problem is I want to do this only once the childNode 's score attribute reaches 100.Where and when should I check if posts have a score of 100 or more and how would I copy them to the new index only once ? WHAT I THOUGHT OF : When ...
if ( funPost.score > = global.hotNumber & & funPost.hot == false ) { var hotPostRef = firebase.database ( ) .ref ( `` hot/section/ '' +key ) ; var hotPost = { title : funPost.title , image : funPost.image , id : funPost.id , key : funPost.key } hotPostRef.set ( hotPost ) ; funPostRef.update ( { `` hot '' : true } ) ; }...
How to copy a childNode from one node to another ?
JS
I had some legacy JS code that creates a giant nested object structure with [ ] . The code goes some like thisIt is about 250+ KB of javascript , which is fairly large . When I try to wrap it around with requirejs to load into another requirejs module , it throws Out Of Memory error.The error goes away if I use { } whe...
var data = [ ] ; data [ `` first '' ] = [ ] ; data [ `` first '' ] [ `` second '' ] = [ ] ; data [ `` first '' ] [ `` second2 '' ] = `` hello '' ; var sizeof = require ( 'object-sizeof ' ) ; var obj = [ ] ; obj [ 'ball ' ] = 'hello ' ; obj [ 'air ' ] = 'hello ' ; obj [ 'ball ' ] [ 'fire ' ] = 'world ' ; obj [ 'ball ' ]...
Does { } consume less memory than [ ] for nested objects in Javascript ?
JS
I have html table with numbers in cells ( class `` numbers '' ) . Some numbers are whole numbers , others with one decimal number or two decimal numbers.I would like to make script , that converts all numbers to two decimal format and then put into the code.Here is my first attemp , that convert one decimal number to t...
e.g.1 = 1.001.0 = 1.001.00 = 1.00 var elements = document.getElementsByClassName ( `` numbers '' ) ; for ( var i = 0 , l = elements.length ; i < l ; i++ ) { elements [ i ] .innerHTML = elements [ i ] .innerHTML.replace ( /\d { 1,2 } ( \.\d { 1 } ) /g , `` $ & 0 '' ) ; }
Javascript - replace whole numbers by decimals
JS
In this dropdown nav I 'm building if a dropdown is opened and you click to open a second one , the black box should remain visible . At the moment the black box disappears when you click on a second dropdown and reappears after the dropdown is completely opened.UpdateI also noticed the black box shows after a dropdown...
$ ( document ) .ready ( function ( ) { $ ( `` .click '' ) .on ( `` click '' , function ( e ) { var menu = $ ( this ) ; toggleDropDown ( menu ) ; } ) ; $ ( document ) .on ( 'mouseup ' , function ( e ) { var container = $ ( `` nav .top-bar-section ul '' ) ; // if the target of the click is n't the container nor a descend...
When click on second dropdown black box should remain visible
JS
I 'm pulling my hair out over this . I have a webpage where I 'd like to have a fixed position div on the left ( the parrot & translater ) follow the page as it scrolls down.http : //www.cartoonizemypet.com/new/help/I managed to follow this tut http : //jqueryfordesigners.com/fixed-floating-elements/ and get what I tho...
# content { padding-top:20px ; padding-bottom:713px ; /* Height of the footer element */ width:888px ; margin-left : auto ; margin-right : auto ; position : relative ; } # help-col1 { left:0 ; width:218px ; position : absolute ; height:500px ; } # parrot-box { position : absolute ; top:0 ; margin-top : 20px ; } # parro...
Apple store style fixed div on LEFT
JS
V8 is capable of wrangling a lot of memory with use of -- max-old-space-size . I regularly use node for tasks which require 10GB+ , it 's great - memory is cheap and it 's much faster than reading/writing from/to disk.Where I run into trouble , however , is when trying to create very large individual arrays/maps/object...
FATAL ERROR : invalid table size Allocation failed - JavaScript heap out of memory RangeError : Invalid array length
Artificial performance limits in V8 / nodejs
JS
I have some code that exercises the “ invalid values ” setting on an element range index . In this case , I have configured a dateTime element range index on the onDate element in my database ( which will apply to both XML elements and JSON properties ) . I ’ ve set that index to reject invalid values . This setting me...
'use strict ' ; declareUpdate ( ) ; var errors = [ ] ; var inputs = { '/37107-valid.json ' : ( new Date ( ) ) .toISOString ( ) , '/37107-invalid.json ' : 'asdf ' , // Should throw an error '/37107-null.json ' : null } ; for ( var uri in inputs ) { try { xdmp.documentInsert ( uri , { 'onDate ' : inputs [ uri ] } , xdmp....
Why can ’ t I catch certain exceptions in a MarkLogic request ?
JS
I am getting a little deeper into my first functional app and need to better understand what it going on in my controller . Here I have a controller that handles the action when a user clicks on an 'Option ' . Looking at the this object raises a few questions : What exactly is this ? I would expect it to be an instance...
App.Option = Ember.Object.extend ( { identity : 'model : Option ' , id : `` , cost : `` , isSelected : false , isSuppressed : false } ) ; App.OptionController = Ember.Controller.extend ( { actions : { toggleOption : function ( ) { this.set ( 'isSelected ' , ! this.get ( 'isSelected ' ) ) ; var id = this.get ( 'content....
Ember.js : questions concerning controllers , 'this ' , 'content ' and model structure
JS
I 'm using nodejs , couchdb for my application . In the future , if I want to check whether my documents look like the same as a model , I 'm thinking to fetch all the documents and compare with the model or a schema and add the missing field to the document as null and update it . How to compare and find out the speci...
{ `` _id '' : `` '' , `` email '' : `` '' , `` password '' : `` '' , `` mobile '' : `` '' , `` username '' : `` '' , `` sharedNetworksArr '' : [ ] } { `` _id '' : `` 1 '' , `` email '' : `` abc @ gmail.com '' , `` password '' : `` abc '' , `` username '' : `` abc '' } { `` _id '' : `` 1 '' , `` email '' : `` abc @ gmai...
How to add specific missing fields to a json object by comparing with a model
JS
If I have an object with multiple keys calling the same function and this function is implemented outside its scope , how to determine which key called this function ? For example :
function tellYourAge ( ) { return function ( ) { // I already know here that this refers to Population // For example , console.log ( this ) will print the Population object } } { let Population = { Mahdi : tellYourAge ( ) , Samuel : tellYourAge ( ) , Jon : tellYourAge ( ) } ; Population.Mahdi ( ) ; // It should log 18...
How to tell which key called a function in javascript
JS
I create a function somewhere and I bind it to this so that I can use the parent block 's meaning of this as the value of this within the function . For example : Is the this I pass as an argument to bind passed by reference , or by value ? So if I change the parameters of the this object a bit later in the outer block...
var foo = function ( ) { // some stuff involving other stuff } .bind ( this ) ;
Does .bind ( this ) pass by reference or by value ?
JS
I have a div with id content . I want to search in this div My Company and then add after My Company the trade mark ® symbol anywhere it appears in the div id=content . The problem is the text My Company is n't always in HTML as My Company . It could be My < span style= '' something '' > C < /span > ompany or My < font...
$ ( `` # content '' ) .each ( function ( ) { var text = $ ( this ) .text ( ) ; text = text.replace ( `` My Company '' , `` My Company® '' ) ; $ ( this ) .text ( text ) ; } ) ; < div id= '' content '' > Lorem ipsum dolor sit amet , consectetur adipiscing elit . Morbi et nisl quam . Praesent semper enim elit , vel imperd...
Add text in a div where find something
JS
I am working on this plnkr . I have three lines at angle 30 , 45 and 60 . I want to apply a brush on these lines so that when the chart is brushed the lines get redrawn at where it crossed the brushed rectangle with appropriate the values on the axis . Any help or hint to solve this problem is greatly appreciated.EDIT ...
var ga = d3.select ( `` svg '' ) .append ( `` g '' ) .attr ( `` class '' , `` a axis '' ) .attr ( `` transform '' , `` translate ( `` + margin.left + `` , '' + ( height + margin.top ) + `` ) '' ) .selectAll ( `` g '' ) .data ( [ 30 , 45 , 60 ] ) .enter ( ) .append ( `` g '' ) .attr ( `` class '' , `` rotatedlines '' ) ...
brush on rotated lines using d3 to create zoom effect