lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I have some HTML in my DOM and I want to replace some strings in it , but only if that was not already replaced or that is not a TAG.All that is based on an Array that contains the string I want to find and the new string I want this to be replace with.Work in progress : https : //jsfiddle.net/u2Lyaab1/23/UPDATE : The ...
var list = [ { original : 'This is ' , new : 'New this is ' } , { original : ' A list ' , new : 'New A list ' } , { original : 'And I want ' , new : 'New And I want ' } , { original : 'To wrap ' , new : 'New To wrap ' } , { original : 'li ' , new : 'bold ' } , { original : 'This ' , new : 'New This ' } , { original : '...
JavaScript replace ( ) if string found between startIndex and endIndex as substring ( ) does
JS
Im trying to use the speechSynthesis API . It 's working on desktop browsers and mobile Chrome but not mobile Safari.I added a little test and it seems the API is supported on Safari , could it be a permissions issue that it 's not working ?
const msg = new SpeechSynthesisUtterance ( `` Hello World '' ) ; window.speechSynthesis.speak ( msg ) ; if ( `` speechSynthesis '' in window ) { alert ( `` yay '' ) ; } else { alert ( `` no '' ) ; }
speechSynthesis not working on mobile Safari even though it 's supported
JS
I 'm using the default source mapping built into Brunch . I see the files fine , but I can not hit breakpoints within the source mapped files . Using the Javascript access to the debugger via debugger ; works , which leads me to believe it 's something wrong with the Brunch side of things.Here is my brunch-config.js : ...
module.exports = { files : { javascripts : { joinTo : { 'js/vendor.js ' : /^ ( ? ! source\/ ) / , 'js/app.js ' : /^source\// } , entryPoints : { 'source/scripts/app.jsx ' : 'js/app.js ' } , order : { before : /^ ( ? ! source ) / } } , stylesheets : { joinTo : 'css/core.css ' } , } , paths : { watched : [ 'source ' ] } ...
Brunch source mapping : not hitting breakpoints in Chrome devtools
JS
I have created a toolbar in my windows app which contains a few buttons.What I want is a select dropdown list along side these buttons but no idea how to create it or append it to the toolbar via Javascript ( as the elements of the list will change depending on the dataset I use ) .I create my toolbar like so :
//JSvar viewsDataArray = [ new WinJS.UI.Command ( null , { id : 'cmdDelete ' , label : 'delete ' , section : 'primary ' , type : 'button ' , icon : 'delete ' , tooltip : 'View 1 ' , onclick : clickbuttonprintout ( ) } ) , new WinJS.UI.Command ( null , { id : 'cmdFavorite ' , label : 'favorite ' , section : 'primary ' ,...
Can a select drop down list be added to my winJS toolbar via Javascript ?
JS
Defining a simple component as follows : When using it like this : I still get template binding errors if model is undefined in the parent , as it tries to resolve the bindings even with the ngIf=false . Why is this the case ?
@ Component ( { selector : 'loader ' , template : ` < div *ngIf='false ' > < ng-content > < /ng-content > < /div > ` , } ) export class Loader { } < loader > { { model.something } } < /loader >
ngIf=false with ngContent still loads template bindings
JS
ProblemWhen using the GET request from a $ resource , the response on success is an empty array in Microsoft Internet Explorer 9 only.TestsScenarios of Success : Using FF or Chrome , the GET request returns an array of data in both development and local environments.IE9 accessing a local server , the `` GET '' request ...
var AnswerSetBySubjectByForm = function ( $ resource ) { return $ resource ( '/rest/answerset/subject/ : idSubject/form/ : idForm ' , { idSubject : ' @ idSubject ' , idForm : ' @ idForm ' } , { 'get ' : { method : 'GET ' , isArray : true } } ) ; } ; var AnswerSetController = function ( $ scope , AnswerSetBySubjectByFor...
`` GET '' ting AngularJS resource in MSIE 9 returns empty array
JS
I 'm having trouble extending the native WebSocket class using es6 classes.The following piece of code works on Chrome and Firefox , but not on Safari : TypeError : ws.doSomething is not a function . ( In 'ws.doSomething ( ) ' , 'ws.doSomething ' is undefined ) console.log ( 'MyWebSocket.prototype ' ) lets me see that ...
class MyWebSocket extends WebSocket { doSomething ( ) { console.log ( 'hi ' ) ; } } let ws = new MyWebSocket ( 'wss : //127.0.0.1:4000 ' ) ; ws.doSomething ( ) ;
Problem extending native ( es6 ) classes in Safari
JS
I came across some code which was filling an array of objects like so : However , I 'm wondering what the main purpose of fill ( null ) .map ( getObj ) is ? It seems redundant as I can simply write the following and get the same resulting array : So , I 'm wondering if these two lines of code do exactly the same thing ...
const getObj = ( ) = > { return { a : 1 , b : 2 , c : 3 } ; } const arr = Array ( 3 ) .fill ( null ) .map ( getObj ) ; console.log ( arr ) ; const getObj = ( ) = > { return { a : 1 , b : 2 , c : 3 } ; } const arr = Array ( 3 ) .fill ( getObj ( ) ) ; console.log ( arr ) ;
Difference between fill and fill map
JS
If I do this : The output is : Why does a inside of the self executing function become NaN ? I know it works fine if I do : But if I go the way of the first version , it has the NaN issue.Why is this happening ?
var a = 0 ; ( function ( ) { var a = a ; //want to make local a = global a ++a ; console.log ( `` fn '' , a ) ; } ) ( ) ; console.log ( a ) ; ​ fn NaN0 ( function ( ) { var b = a ; ++b ; console.log ( `` fn '' , b ) ; // fn 1 } ) ( ) ;
Local Javascript scoping issue
JS
fiddle http : //jsfiddle.net/Q8F5u/3/ I have multiple divs , each having a delete button on its top to delete that particular div ( actually i have to hide not delete ) . After the divs have been deleted I want to retrieve them back by pressing CTRL + Z.I have had some success in bringing them back . The Logic i have u...
var deletedBlocks = [ ] ; $ ( '.delete ' ) .on ( 'click ' , function ( ) { var deletedid = $ ( this ) .closest ( 'div [ id^=block ] ' ) .attr ( 'id ' ) ; deletedBlocks.push ( deletedid ) ; $ ( this ) .closest ( 'div [ id^=block ] ' ) .fadeOut ( 500 ) ; } ) ; $ ( 'body ' ) .on ( 'keydown ' , function ( e ) { //check for...
Undo ( ctrl + z ) functionality to bring back hidden divs
JS
I 'm using the d3-tip plugin to show tooltips for countries . The countries are an svg layer that sits on top of the Leaflet base layer.I want the tooltips to be centered within each state.What I currently have works great for all browsers except Firefox . Firefox is just way off . I 've tried to adjust for Firefox , b...
< ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' > < script src= '' http : //d3js.org/d3.v3.min.js '' > < /script > < link rel= '' stylesheet '' href= '' http : //cdn.leafletjs.com/leaflet-0.5/leaflet.css '' / > < ! -- [ if lte IE 8 ] > < link rel= '' stylesheet '' href= '' http : //cdn.leafletjs.com/le...
d3-tip offset on svgs within Leaflet , Firefox only , not working
JS
I am working on an angular v1.3 app and I am using angular-poller in one my controllers to automatically send request to get new data from my backend every 2 seconds.It works fine in Chrome , but does not work in IE11 . But strangely enough , I am using the Fiddler to see if the requests are sent out when I using IE11 ...
poller.get ( myResourceService , { action : 'get ' , argumentsArray : [ { id : $ stateParams.id } ] , delay : '2000 ' , smart : true } ) .promise.then ( null , null , function ( result ) { $ scope.details= result ; } ) ;
Angular-poller does n't work on IE11 when the development tool is not opened
JS
I am trying to create simple animation in loop but every time it works wrong.How should it work ? Test 1 fadein , wait 2 seconds and Test 2 fadein , wait 2 seconds and Test 3 fadein , wait 2 seconds and Test 4 fadein , wait 2 seconds and fadeout Test 1 , Test 2 , Test 3 , Test 4 at the same time ( important , I ca n't ...
< div class= '' col-md-12 slogan text-right '' > < h1 class= '' slogan1 '' > test 1 < /h1 > < h1 class= '' slogan2 '' > test 2 < /h1 > < h1 class= '' slogan3 '' > test 3 < /h1 > < p class= '' slogan4 '' > test 4 < /p > < h1 class= '' slogan5 '' > test 5 < /h1 > < h1 class= '' slogan6 '' > test 6 < /h1 > < h1 class= '' ...
Text fadein/fadeout animation in loop
JS
Why do many javascript libraries look like this : It appears to define an unnamed function which is immediately called . Why go through this effort ?
( function ( ) { /* code goes here */ } ) ( ) ;
Why do many javascript libraries begin with `` ( function ( ) { `` ?
JS
I want to open a ftp browser at client site so that he can upload files in ftp.I am using window.open ( ) method to open the ftp in a child window.The ftp looks like this : [ 1 ] : http : //i.stack.imgur.com/T6WYg.jpgnow i want to track the user activity like directories he visited , and send the path to the jsp page h...
var windowObjectReference = window.open ( `` ftp : // '' + username + `` : '' + password + `` @ '' + server , _blank ' , toolbar=yes , location=yes , status=yes , scrollbars=auto , copyhistory=no , menubar=yes , width= 500px , height=500px , left=300px ) , top=100px , resizable=yes ' ) ;
Tracking user activity on window opened by window.open ( ) method
JS
Just bumped into the fact that an if statement can have multiple parameters in javascript : How well is this supported ? p.s . I get that this is similar to using & & , but this is interesting and a google could n't provide the answer .
// Webkitif ( true , true , false ) console.log ( `` this wo n't get logged '' ) ;
Javascript : if ( arg1 , arg2 , arg3 ... ) statement
JS
An old idiom for getting very old browsers to ignore JavaScript blocks in HTML pages is to wrap the contents of the < script > element in HTML comments : The rationale is that old JavaScriptless browsers will render as text the contents of the < script > element , so putting the JavaScript in an HTML comment makes the ...
< script > < ! -- alert ( `` Your browser supports JavaScript '' ) ; // -- > < /script >
HTML Opening-Comment is valid JavaScript ?
JS
IntroductionI 'm building an HTML5 web application that creates a visual representation of a binary search tree from a given list of numbers.Currently , I have an algorithm which calculates the visual spacing between nodes on each row based on the maximum depth of the tree ( which is a base-0 value ) : From here , the ...
offset = 50offset *= pow ( 2 , maxDepth - currentDepth ) if ( parent.get ( 'left ' ) === node ) { x = parentX - offsetX ; y = parentY + offsetY ; } else if ( parent.get ( 'right ' ) === node ) { x = parentX + offsetX ; y = parentY + offsetY ; }
How to minimize visual width of ( binary ) search tree ?
JS
Hi I 'm stumbled up on a problem related to regular expressions that I can not resolve.I need to tokenize the query ( split query into parts ) , suppose the following one as an example : What I eventually need is to have an array of 7 tokens : The seventh token consists of several words because it was inside double quo...
These are the separate query elements `` These are compound composite terms '' 1 ) These2 ) are3 ) the4 ) separate5 ) query6 ) elements7 ) These are compound composite term ( ? : '' ) ( ? : \w+\W* ) + ( ? : '' ) |\w+ var tokens = query.match ( / ( ? : '' ) ( ? : \w+\W* ) + ( ? : '' ) |\w+/g ) ;
A javascript regular expression to tokenize the query
JS
I 'm having a problem when I use orderBy in a ng-repeat with an autoincrementing limitTo . When the page load a few elements the directive stops working and stops increasing the element limit.This is the html : This is the directive : And finally the loadMore functionSorry for my English , if you do not understand me o...
< div class= '' row '' id= '' main '' > < div class= '' col-xs-12 col-sm-6 col-md-3 col-lg-2 block animate '' ng-if= '' ! errorDialogActive '' ng-repeat= '' build in builds.builds.build | limitTo : totalDisplayed | orderBy : 'lastBuildDetails.startDate ' : true track by build._id '' ng-class= '' { 'running ' : project....
OrderBy and progressive-loading AngularJS
JS
I 've previously used the following based on other SO answers ( without really understanding the need for ( nor the workings of ) the prototype.apply.applywhile this prevents IE from crapping on itself , it also make the line number reporting unusable ( it always reports the apply.apply.. line.I was playing around a li...
var mylogger = { log : function ( ) { if ( window.console ) { if ( window.console.log ) { Function.prototype.apply.apply ( console.log , [ console , arguments ] ) ; } } } , ... } ; var mylogger = { // function invocation returning a safe logging function.. log : ( function ( ) { if ( window.console & & window.console.l...
What is the current best way to wrap console.log ( ) that will preserve line numbers ?
JS
I am trying to block the back button in certain cases . However as soon as I add the eventlistener it always blocks the back button.It comes in the else structure but when it returns true it does n't execute the back action anymore.There are no errors whatsoever in logcat.I have no idea what is causing this ...
document.addEventListener ( `` deviceready '' , onDeviceReady , false ) ; function onDeviceReady ( ) { document.addEventListener ( `` backbutton '' , onBackKey , false ) ; } function onBackKey ( ) { if ( $ scope.quicksetup ) { alert ( `` 1 '' ) ; return false ; } else { alert ( `` 2 '' ) ; return true ; } }
cordova/phonegap block and allow back button
JS
I have following html : And following js code : And output is strange for me : I create also jsFiddle example.Is it correct behavior ? I do n't understand , why in .html ( ) function , value of input type= '' text '' is not returned .
< div class= '' copy_me_text '' > < div > < input type= '' text '' name= '' name '' / > < input type= '' hidden '' name= '' id '' / > < /div > < /div > < div class= '' copy_me_hidden '' > < div > < input type= '' hidden '' name= '' name '' / > < input type= '' hidden '' name= '' id '' / > < /div > < /div > var $ cloned...
jquery.html ( ) strange behavior with form
JS
This code results in `` ! '' being logged on the console.Do anonymous functions share a this ? Am I using this wrong ? I do n't really understand what 's going on here.I 'd like for g.a ( ) to continue returning the value of x defined in the first anonymous function.I 'm using node.js if it makes a difference .
var g = { } ; ( function ( ) { var t = this ; t.x = `` x '' ; g.a = function ( ) { console.log ( t.x ) ; } ; } ) ( ) ; ( function ( ) { var t = this ; t.x = `` ! `` ; g.b = function ( ) { console.log ( t.x ) ; } ; } ) ( ) ; g.a ( ) ;
specifics of closures in JavaScript and anonymous functions
JS
JSFiddle : http : //jsfiddle.net/nbh1rn33/I have a weird issue with jQm panel.An opened panel does n't close fully . See below image : Strangely , this only happens on Android browser , and not on PC ( Chrome , IE ) . Is this a bug with jQm or have I done something wrong ?
< ! DOCTYPE html > < html > < head > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link href= '' http : //code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css '' rel= '' stylesheet '' / > < script src= '' https : //code.jquery.com/jquery-2.1.4.js '' > < /script > < script src= '' h...
jQuery mobile panel does n't close fully only on Android browser
JS
Background : As needed in some task , I need a simple sort function . For simplicity , I wrote another function to wrap the built-in sort function as : My attempts are : Make it possible to sort a object directlyKeep the original object as the hash tableAllow some simple syntaxFor instance , There are several usages : ...
function sortBy ( obj , extra , func ) { if ( typeof func == 'function ' ) { f = func ; } else if ( typeof extra ! = 'function ' ) { eval ( 'function f ( a , b , ai , bi , e ) { return ' + func + ' } ' ) ; } else { var f = extra ; extra = null ; } var res = [ ] ; for ( var i in obj ) { if ( obj.hasOwnProperty ( i ) ) {...
About a sort function for javascript
JS
I want to check the image transparency and display an error message if the image background is not transparent . I have the function hasAlpha ( file ) to check it the file has a transparent background but I am not sure how to pass it through the function uploadFile ( file ) function which already checks for file size ....
// File Upload//function ekUpload ( ) { function Init ( ) { console.log ( `` Upload Initialised '' ) ; var fileSelect = document.getElementById ( `` file-upload '' ) , fileDrag = document.getElementById ( `` file-drag '' ) , submitButton = document.getElementById ( `` submit-button '' ) ; fileSelect.addEventListener ( ...
Javascript - File upload ; check if image has transparent background
JS
I 'd like to use the haste-compiler package to do the haskell-to-javascript thing : I noticed that there is a newer version of zip-archive that bumped the version of binary to > = 0.7 , which supplies the decodeOrFail function . So I tried checking out the haste-compiler repo and bumping the zip-archive version to the ...
jsnavely @ beefy : ~/project $ cabal install haste-compilerResolving dependencies ... ... Configuring zip-archive-0.2.3 ... Building zip-archive-0.2.3 ... Preprocessing library zip-archive-0.2.3 ... [ 1 of 1 ] Compiling Codec.Archive.Zip ( src/Codec/Archive/Zip.hs , dist/build/Codec/Archive/Zip.o ) src/Codec/Archive/Zi...
escape from cabal hell with haste , binary and zip-archive
JS
I want to generate multiple pages which will have content on different languages from one common template . How can I do it with webpack ? I tried to use different webpack plugins like webpack-static-i18n-html , i18n-webpack-plugin but nothing works for me . The best thing I found is a webpack-static-i18n-html , but it...
const Path = require ( 'path ' ) ; const HtmlWebpackPlugin = require ( 'html-webpack-plugin ' ) ; const StaticI18nHtmlPlugin = require ( `` webpack-static-i18n-html '' ) ; // ... module.exports = { // ... plugins : [ // ... new StaticI18nHtmlPlugin ( { locale : 'en ' , locales : [ 'en ' , 'ua ' , 'ru ' ] , baseDir : Pa...
How to create multiple pages with different languages from one template ?
JS
How can i wait for 2 promises to get completed ? Promise.race ( ) wait for one promise to get completed.EditI have n number of promises , what i want to achieve is wait for first k number of promises to get resolved and than trigger some event . assume k < nEdit - 2I am sure that k number of promise will be successfull...
var p1 = new Promise ( ( resolve , reject ) = > { setTimeout ( resolve , 1000 , 'one ' ) ; } ) ; var p2 = new Promise ( ( resolve , reject ) = > { setTimeout ( resolve , 2000 , 'two ' ) ; } ) ; var p3 = new Promise ( ( resolve , reject ) = > { setTimeout ( resolve , 3000 , 'three ' ) ; } ) ; Promise.all ( [ p1 , p2 , p...
ES6 Promise wait for K out N promises to resolve
JS
I have a Google Site with multiple pages all containing a Google Apps Script Gadget . Users have reported that a couple of months ago , the Apps Script Gadgets stopped working . I have tested them , and found that the Apps Script gadget loads correctly and displays content from UI service , however , when any button is...
Uncaught SecurityError : Failed to read the 'frame ' property from 'Window ' : Blocked a frame with origin `` https : //sites.google.com '' from accessing a frame with origin '' https : //xxxxxxxxxxxxxxxx-a-sites-opensocial.googleusercontent.com '' .Protocols , domains , and ports must match .
Apps Script Gadget on Google Site started throwing CORS errors
JS
When I type the last number in , the first number goes inside the text-box ( it disappears ) , it 's adding one extra space . After I click outside the text-box it looks good which I need during typing last character.Help me to get out from this issues . Thanks
# number_text { padding-left : 9px ; letter-spacing : 31px ; border : 0 ; background-image : linear-gradient ( to right , # e1e1e1 70 % , rgba ( 255 , 255 , 255 , 0 ) 0 % ) ; background-position : left bottom ; background-size : 38px 1px ; background-repeat : repeat-x ; width : 220px ; box-sizing : border-box ; outline...
First number goes inside when type last number in text-box
JS
In rxjs5 , I have an AsyncSubject and want to subscribe to it multiple times , but only ONE subscriber should ever receive the next ( ) event . All others ( if they are not yet unsubscribed ) should immediately get the complete ( ) event without next ( ) .Example :
let fired = false ; let as = new AsyncSubject ( ) ; const setFired = ( ) = > { if ( fired == true ) throw new Error ( `` Multiple subscriptions executed '' ) ; fired = true ; } let subscription1 = as.subscribe ( setFired ) ; let subscription2 = as.subscribe ( setFired ) ; // note that subscription1/2 could be unsubscri...
How to subscribe exactly once to an element from AsyncSubject ( consumer pattern )
JS
I am trying to make a play and stop button . I do n't know how to morph the triangle shape ( it is a path ) into the square shape ( it is a path ) when it has been clicked . Only showing one shape at a time . Can anyone help ?
< svg class= '' playStop '' version= '' 1.1 '' id= '' Layer_1 '' xmlns= '' http : //www.w3.org/2000/svg '' xmlns : xlink= '' http : //www.w3.org/1999/xlink '' x= '' 0px '' y= '' 0px '' viewBox= '' 0 0 971 530 '' style= '' enable-background : new 0 0 971 530 ; '' xml : space= '' preserve '' > < style type= '' text/css '...
How to morph one SVG path element into another on a click command ?
JS
I 've been implementing a useful subclass of the ES6 Set object . For many of my new methods , I want to accept an argument that can be either another Set or an Array , or really anything that I can iterate . I 've been calling that an `` iterable '' in my interface and just use .forEach ( ) on it ( which works fine fo...
// remove items in this set that are in the otherIterable// returns a count of number of items removedremove ( otherIterable ) { let cnt = 0 ; otherIterable.forEach ( item = > { if ( this.delete ( item ) ) { ++cnt ; } } ) ; return cnt ; } // add all items from some other iterable to this setaddTo ( iterable ) { iterabl...
What is the technical definition of a Javascript iterable and how do you test for it ?
JS
I have a button at the top a table that displays a modal window to initiate a VOIP call - the ultimate aim is for it to call the first number in the list and then the 2nd number and so on . I 've got it working in that it displays the modal window and allows me to initiate a call to the first number in the list.I now n...
Authentication accepted < br/ > ActionID = Jo9oACY52cp1 https : //www.acme.com/GetStatus.php ? ActionID= $ action_id xshsJ6Y2eLDC,1500806656.160 , ANSWER $ ( `` # startBulkContactCall '' ) .click ( function ( ) { $ ( this ) .attr ( 'selectedRow ' , ' 1 ' ) ; contactMobile = $ ( $ ( $ ( 'table > tbody > tr : nth-child (...
AJAX Request - Add Additional GET request inner loop
JS
I have been unable to find any reference to this statement in any book , manual , or site . As far as I can tell , it functions exactly as a // comment . For example : will printWhat I 'm curious about is exactly what the difference between -- > and // is , if any exists , and also why -- > seems to completely absent f...
console.log ( `` 1 '' ) ; -- > console.log ( `` 2 '' ) ; console.log ( `` 3 '' ) ; 13
What does -- > do in JavaScript ?
JS
How do I add the values of checked radio buttons to a seperate div without overwriting the existing classes ? I ' running into troubles since I like to load the values of the checked radio buttons on page load , as well I like to update the classes correctly . My function overwrite the existing class instead of adding ...
document.addEventListener ( 'DOMContentLoaded ' , function ( ) { var radioButtons = document.getElementsByName ( 'color ' ) ; var paragraph = document.querySelector ( '.folder ' ) ; for ( var i=0 ; i < radioButtons.length ; i++ ) { var elem = radioButtons [ i ] ; elem.addEventListener ( 'change ' , function ( e ) { con...
How do I add the values of checked radio buttons to a seperate element
JS
Is there a particular reason why i often encounter : instead of : It should have the same effect when passing this to call or not ? There seems to be some performance difference : http : //jsperf.com/call-vs-parenthesis .
( function ( ) { console.log ( `` Hello '' ) ; } ) .call ( this ) ; ( function ( ) { console.log ( `` Hello '' ) ; } ) ( ) ;
Why is .call ( this ) used instead of parenthesis
JS
I have the following code : Which I believe ( perhaps mistakenly ) shows two equivalent ways to achieve the same functionality : first by chaining promises and second with the syntactic sugar of async/await.I would expect the promise chaining solution to console.log first , then the async function second , however the ...
var incr = num = > new Promise ( resolve = > { resolve ( num + 1 ) ; } ) ; var x = incr ( 3 ) .then ( resp = > incr ( resp ) ) .then ( resp = > console.log ( resp ) ) ; async function incrTwice ( num ) { const first = await incr ( num ) ; const twice = await incr ( first ) ; console.log ( twice ) ; } incrTwice ( 6 ) ;
Why does this async function execute before the equivalent Promise.then chain defined before it ?
JS
The image is the grandparent div , the black translucent overlay is the parent div , and the cropped section is the child div . User will see the grandparent image and the parent overlay , then he can crop through it using the child cropper div . I tried and failed with opacity and rgba background.These crazy approache...
# grandparentImage { background : url ( https : //9to5mac.com/wp-content/uploads/sites/6/2018/07/Desert-2.jpg ) no-repeat ; background-size : cover ; position : relative ; height : 500px ; } # parentOverlay { background : rgba ( 0,0,0,0.5 ) ; height : 100 % ; position : relative ; } # childCropper { border : 1px dashed...
Is a see-through child div possible ?
JS
I want to pass a simple function to a web worker , rather than writing it directly in the web worker . I know this is n't directly possible , but that you can `` work around '' this in many cases by calling toString ( ) on your function and calling eval on that string , once it 's in the worker.The caveat that I have n...
( ) = > { return new _MyClass__WEBPACK_IMPORTED_MODULE_5__ [ `` MyClass '' ] ( ) ; } new Worker ( URL.createObjectURL ( new Blob ( [ functionString ] ) ) ) ; ( ) = > { return import ( './MyClass ' ) .then ( module = > new module.MyClass ( ) ) ; }
Pass a function to a web worker that uses a webpack imported class
JS
I am new to JavaScript and I want learn more about it.For example : Is this similar to : If the above code is correct and if they both are equal , then I want to know all operators and conditions like this . Where can I find them ?
a == true & & alert ( `` a is true '' ) ; if ( a == true ) { alert ( `` a is true '' ) ; }
I want to know if the two JavaScript snippets are the same or not
JS
I wanted to try manually walking the prototype chain of a few objects just to see what I find along the way . However , I got stuck on the first one that I tried . Here 's the code : The above code results in the following output in the Developer Tools Console of Google Chrome : It makes sense that x 's constructor is ...
function MyObject ( ) { } var x = new MyObject ( ) ; console.log ( ' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ' ) ; console.log ( ' x.constructor.name : ' + x.constructor.name ) ; console.log ( ' x.constructor.prototype.constructor.name : ' + x.constructor.prototype.constructor.name ) ; console...
Difficulty Manually Walking The Prototype Chain
JS
I was looking for a way to perform a linear curve fit in Javascript . I found several libraries , but they do n't propagate errors . What I mean is , I have data and associated measurement errors , like : Where my notation a +/- b means { value : a , error : b } .I want to fit this into y = mx + b , and find m and b wi...
x = [ 1.0 +/- 0.1 , 2.0 +/- 0.1 , 3.1 +/- 0.2 , 4.0 +/- 0.2 ] y = [ 2.1 +/- 0.2 , 4.0 +/- 0.1 , 5.8 +/- 0.4 , 8.0 +/- 0.1 ] m = 1.93 +/- 0.11b = 0.11 +/- 0.30
Linear curve fitting with errors
JS
there is a line from a plugin that i 'm using that im trying to understand : self is a jquery object , which in this code is an img dom element , it hides it , then sets the src attribute of this img object to the html5 data-attribute . but now its accessing a property in the jquery object returned by .attr ( , which i...
$ self.hide ( ) .attr ( `` src '' , $ self.data ( settings.data_attribute ) ) [ settings.effect ] ( settings.effect_speed ) ; ( function ( $ , window , document , undefined ) { var $ window = $ jq191 ( window ) ; $ jq191.fn.lazyload = function ( options ) { var elements = this ; var $ container ; var settings = { thres...
Do n't understand how this is calling the fadeIn method in Jquery
JS
Edit : I thought about a possible solution , but I made another question as it is very specific : see AJAX proxy with PHP , is it possible ? A couple of times I 've encountered this problem ... I create sites that have a certain degree of modularity . So , it is possible that there are `` components '' ( think of a rou...
{ siteroot } /component/datagrid/datagrid.php { siteroot } /component/datagrid/js/datagrid.js { siteroot } /component/datagrid/css/datagrid.css { siteroot } /component/datagrid/ajax/getsomedata.php $ ( `` # ajax '' ) .load ( `` siteroot/component/datagrid/ajax/getsomedata.php '' ) ; var codeBase = < ? echo json_encode ...
Context-aware AJAX call in a modular site
JS
This may seem like a particularly obscure point , however I am attempting to improve my grounding in the Javascript language as a whole ( more specifically its best and most efficient practices ) .Whilst testing a theory in http : //jsperf.com/ I came up with some odd results : Suppose we have two `` identical '' proto...
var Object1 = function ( ) { } Object1.prototype.defaults = { radius : 400 , up : 1 } Object1.prototype.centerOffset = function ( ) { return this.defaults.radius*this.defaults.up ; } var Object2 = function ( ) { } Object2.prototype = { defaults : { radius : 400 , up : 1 } , centerOffset : function ( ) { return this.def...
Why is defining JS prototype functions separately faster than in a dictionary ?
JS
Is there such a concept as a synchronous promise ? Would there be any benefit to writing synchronous code using the syntax of promises ? ... could be written something like ( but using a synchronous version of then ) ;
try { foo ( ) ; bar ( a , b ) ; bam ( ) ; } catch ( e ) { handleError ( e ) ; } foo ( ) .then ( bar.bind ( a , b ) ) .then ( bam ) .fail ( handleError )
Would there be any benefit to writing synchronous code using the syntax of promises
JS
I would like make a double bonds with two div using librairy jsPlumb Javascript . I can make a connection , but not a double bonds.Do you know how to make a double bond ? For a simple link between two DIV : For a double link in two DIV , I test this , but it does n't work : Somebody have a solution ?
jsPlumb.ready ( function ( ) { jsPlumb.importDefaults ( { ConnectorZIndex:5 } ) ; var jsP = jsPlumb.getInstance ( { PaintStyle : { lineWidth:2 , strokeStyle : '' # 000 '' , outlineColor : '' black '' , outlineWidth:1 } , Connector : `` Straight '' , Endpoint : `` Blank '' } ) ; var e0 = jsP.addEndpoint ( `` firstLink '...
JSplumb double bonds
JS
I have an iframe that is generated in JavaScript with createElement ( ) when a function is fired , which becomes a text editor . It works just fine in Chrome , Safari and Edge , but in Firefox , the innerHTML text , `` Text Layer '' , will briefly flash within the iframe and then it disappears and the iframe does n't s...
function text ( ) { var rtf = document.createElement ( `` iframe '' ) ; rtf.name = `` richTextField '' ; rtf.id = `` richTextField '' ; rtf.className = `` texteditor '' ; var dwrap = document.createElement ( `` div '' ) ; dwrap.appendChild ( rtf ) ; var tframe = document.getElementById ( `` richTextField '' ) ; tframe....
Dynamically created editable iframe not working in Firefox
JS
There are some css values that is defined with a number , such as opacityI know while writing css , I would do : But when I am going to modify that opacity with javascript , what should I provide ? only 0.5 or `` 0.5 '' ? if I run : So I used to provide string while modifying that.But someone reviewing my code , sugges...
# element { opacity : 1 ; /* without a quote mark , just 1 */ } typeof document.getElementById ( 'element ' ) .style.opacity // returns `` srting '' document.getElementById ( 'element ' ) .style.opacity = 0.5
Number or String while setting style values with javascript
JS
I have a html < input > element that I want to accept only numbers and to be recognised on mobile devices as a number field . I also want invalid characters to be swallowed , just like for standard type=number swallowing disallowed characters . I 've tried the obvious type=number but it has a number of shortcomings . S...
< input type= '' number '' ( keydown ) = '' keyDown ( ) '' > function keyDown ( $ event : KeyboardEvent ) { const inputField = // obtain reference to input element const value = inputField.value ; if ( value.indexOf ( ' . ' ) ! == -1 & & $ event.key === ' . ' ) { // disallow another . if one is present // ! input field...
How to customise ` < input > ` element with tighter restrictions
JS
I have created a class in JavaScript like this : As you can see , I explain in code above . Why when we set properties after their initialization , it just takes effects in internall calls ? How can I create a property that I can change it 's value ? UPDATE : It seems that I have to explain my code . The probelem is al...
var Test = function ( ) { this.element = null ; this.init = function ( ) { if ( Test.html == `` '' ) { Test.loadHtml ( this ) ; return ; } this.initElements ( ) ; this.someMethodInternalCall ( ) ; } ; this.initElements = function ( ) { // append the loaded html to body // etc ... this.element = $ ( `` some-element-cont...
property initialization in JavaScript
JS
In my angular 2 app , I am making a call from component to service and from service to the back end Web API . The response obtained from Web API is sent back from service to the component and I am subscribing to the response inside the component . For error handling , I am using a common error component which is used a...
this._accountdetailsService.getContacts ( this.group.id ) .subscribe ( contacts = > this.contacts = contacts , error = > this.callErrorPage ( error ) ; ) ; getContacts ( groupId : number ) : any { return this._http.get ( this._serverName + 'api/CustomerGroups/ ' + groupId + '/contacts ' ) .map ( response = > { if ( res...
Make a failed Web API call again on clicking Retry button on a modal popup in Angular 2 and continue execution if the call succeeds on 'Retry '
JS
I have a problem with centering div in HTML ( vertical & horizontal ) . My code looks something like this : Only chrome center this div in to the middle of the screen .
< div id= '' container '' > SOME HTML < /div > # container { width : 366px ; height : 274px ; margin : 50 % ; top : -137px ; left : -188px ; position : absolute ; }
How to center div ?
JS
In jQuery , what 's the difference between the following two constructions of jQuery.each : Is there any difference , or is it purely syntax ?
// Givenvar arr = [ 1,2,3,4 ] , results = [ ] , foo = function ( index , element ) { /* something done to/with each element */ results.push ( element * element ) ; // arbitrary thing . } // construction # 1 $ .each ( arr , foo ) ; // results = [ 1,4,9,16 ] // construction # 2 $ ( arr ) .each ( foo ) ; // results = [ 1,...
jQuery $ .each ( arr , foo ) versus $ ( arr ) .each ( foo )
JS
Yesterday , I did not have this issue . I do n't believe any of my code has changed in any way since then . I get `` Polyfill JSON does not have implementation of stringify '' . Line 46 of FBLogin.js is the FB.init .
window.fbAsyncInit = function ( ) { FB.init ( { appId : ' # # # # # # # # # # ' , //this is replaced with my appId cookie : true , xfbml : true , version : 'v2.5 ' } ) ; } ; ( function ( d , s , id ) { var js , fjs = d.getElementsByTagName ( s ) [ 0 ] ; if ( d.getElementById ( id ) ) return ; js = d.createElement ( s )...
Hitting FB.init returns error `` Polyfill JSON does not have implementation of stringify ''
JS
I have a living linechart that updates frequently , see http : //jsfiddle.net/cddw17fg/5/Running this js in IE11 with the `` Development Tools '' the `` Total memory '' increases slightly first , but after some minutes it starts growing fast.After starting the jsfiddle the memory consumption looks 'good ' ... but after...
function redraw ( ) { if ( ! redraw.isGraphShown ) { redraw.isGraphShown = true ; ... } else { d3.select ( ' # chart svg ' ) .datum ( data ) .transition ( ) .duration ( 1500 ) .call ( chart ) ; d3.select ( '.nv-x.nv-axis > g ' ) .selectAll ( ' g ' ) .selectAll ( 'text ' ) .attr ( 'transform ' , function ( d , i , j ) {...
nvd3 application memory leak
JS
I 'm trying to swap out content within a button that toggles a nav collapse.I currently have the following code ; I want to be able to change the content within to be ; This needs to be toggled however , so when you click collapse , it changes back to its original stateCa n't seem to figure it out ...
< button class= '' navbar-toggle collapse in '' data-toggle= '' collapse '' id= '' menu-toggle-2 '' > < i class= '' fa fa-expand '' aria-hidden= '' true '' > < /i > Expand < /button > //in js script $ ( `` # menu-toggle-2 '' ) .click ( function ( e ) { e.preventDefault ( ) ; $ ( `` # page '' ) .toggleClass ( `` toggled...
jquery toggle content inside element
JS
I 'm writing a lightweight htc program for IE 9 ( =javascript ) . CSS3 has a new property called transition , but it does n't work in IE 9 . I 'm trying to implement this , but I need to know when a property changes . I 'm familiar with DOMAttrModified & onpropertychange , but they do n't trigger if CSS changes the pro...
a { color : # FFF ; } a : hover { color : # 000 ; } div : hover a { color : # FFF ; }
Fire event if the CSS style is changed by the user ?
JS
I have a use case where the text has to be encoded and sent using the AES 256 algorithm . The client-side code is in C # which would be decrypting the code.Encryption code in JS : Updated code used in the client side : The keyString and IV value used are same in C # and is encrypted using Utf8 . Looking for the equival...
const crypto = require ( 'crypto ' ) ; algorithm = 'aes-256-cbc ' , secret = '1234567890123456 ' , keystring = crypto.createHash ( 'sha256 ' ) .update ( String ( secret ) ) .digest ( 'base64 ' ) .substr ( 0 , 16 ) ; iv = crypto.createHash ( 'sha256 ' ) .update ( String ( secret ) ) .digest ( 'base64 ' ) .substr ( 0 , 1...
AES encryption in Node JS and C # gives different results
JS
I am trying to write a test to work out whether the text rendered inside an < input > has the same baseline as a label : In order to do this , I would like to compute the baseline of the text that has been rendered in each element and compare the two values . Is this possible and if so , how is it done ? If not , is th...
function getBaseline ( element ) { var span = document.createElement ( `` span '' ) ; span.setAttribute ( `` style '' , `` font-size:0 '' ) ; span.innerText = `` A '' ; jQuery ( element ) .prepend ( span ) ; return span.getBoundingClientRect ( ) .bottom ; }
How to compute the baseline of text
JS
Some claim eval is evil.Any regular HTML page may look like : That is , assuming the person doing this knows his job and leaves javascript to load at the end of the page.Here , we are basically loading a script file into the web browser . Some people have gone deeper and use this as a way to communicate with a 3rd part...
< script src= '' some-trendy-js-library.js '' > < /script > < /body > < /html > < script src= '' //foo.com/bar.js '' > < /script >
Javascript eval ( and friends )
JS
For learning purpose , I am using Tensorflow.js , and I experience an error while trying to use the fit method with a batched dataset ( 10 by 10 ) to learn the process of batch training.I have got a few images 600x600x3 that I want to classify ( 2 outputs , either 1 or 0 ) Here is my training loop : Here is how I defin...
const batches = await loadDataset ( ) for ( let i = 0 ; i < batches.length ; i++ ) { const batch = batches [ i ] const xs = batch.xs.reshape ( [ batch.size , 600 , 600 , 3 ] ) const ys = tf.oneHot ( batch.ys , 2 ) console.log ( { xs : xs.shape , ys : ys.shape , } ) // { xs : [ 10 , 600 , 600 , 3 ] , ys : [ 10 , 2 ] } c...
new shape and old shape must have the same number of elements
JS
I was looking at FireBug Lite and saw that they use a pretty cool technique to pass options into an external script file.I was wondering if anyone know of the name of this technique and where I can find more info about it or how it works . Seems pretty cool . Thanks !
< script type= '' text/javascript '' src= '' https : //getfirebug.com/firebug-lite.js '' > { overrideConsole : false , startInNewWindow : true , startOpened : true , enableTrace : true } < /script >
JSON Object passed to External JavaScript - Cool Technique
JS
Using mysql/php/js to try and display a curve chart - currently the chart is displaying but it is blank.downloadURL is a method that retrieves information from my database - looking to retrieve altitude and simply plot it . The method definitely works ok as I 'm also using it for adding markers to a google map ...
google.load ( 'visualization ' , ' 1.0 ' , { 'packages ' : [ 'corechart ' ] } ) ; google.setOnLoadCallback ( drawChart ) ; function drawChart ( ) { var graph = Array ( ) ; downloadUrl ( `` map.php '' , function ( data ) { var xml = data.responseXML ; var markers = xml.documentElement.getElementsByTagName ( `` marker ''...
Google Charts - Graph is blank
JS
If I run the following code in google chrome console I get the following resultsWhy in the first example the variable is not deleted and in the second example it is deleted ?
var x = 1 ; alert ( delete x ) ; // false eval ( 'var y = 2 ' ) ; alert ( delete y ) ; // true
about eval statement constructs and delete
JS
I read the angular animation doc and recreated the demo . If you click the Fold In button , the text will be changed as the animate define.The demo does not work well . The animation does n't work well . This is my code : https : //jsfiddle.net/jiexishede/5nokogfq/In the Webstorm : I change var app = angular.module ( '...
Uncaught Error : [ $ injector : unpr ] Unknown provider : $ $ isDocumentHiddenProvider < - $ $ isDocumentHidden < - $ $ animateQueue < - $ animate < - $ compile < - $ $ animateQueuehttp : //errors.angularjs.org/1.5.8/ $ injector/unpr ? p0= % 24 % 24isDocumentHiddenP…eQueue % 20 % 3C- % 20 % 24animate % 20 % 3C- % 20 % ...
Ca n't run the animation demo in AngularJS
JS
I allow the user to insert an object , an image , and then i call a function on that object . What seems randomly to me , sometimes it works and sometimes not , I guess it has to do with the DOM not being updated yet ? Because if I manually trigger that last function with a button after a second or so it always works ....
//add a new imagefunction add_image ( img ) { var objCount = count_objects ( ) + 1 ; var objId = 'object_'+objCount ; var myNewImg = jQuery ( ' < div/ > ' , { id : objId , class : 'object_image invisible ' , } ) .appendTo ( ' # objectbox ' ) ; //sätt objektnamnet ( användaren kan ändra senare ) $ ( ' # '+objId ) .attr ...
Insert object ( jquery ) delay ?
JS
Essentially children can be dragged onto parents , but parents ca n't be dragged onto children.I wrote a simple example to demonstrate this . Three divs that are both draggable and droppable onto one another . You can drag blue onto its parents green or red and you can drag green onto its parent red . You ca n't drag r...
< div class= '' first '' > < div class= '' second '' > < div class= '' third '' > < /div > < /div > < /div > $ ( 'div ' ) .draggable ( { revert : true , helper : 'clone ' , appendTo : 'body ' , refreshPositions : true } ) ; $ ( 'div ' ) .droppable ( { greedy : true , accept : 'div ' , activeClass : 'active ' , hoverCla...
JQuery UI draggable helper ca n't be dragged onto droppable children
JS
Given this piece of code ( simplification of a React component I came by ) : I do n't understand what is going on there . What 's this construct ? I 'm referring to what is inside 'myFn ( ) 'This construct/code-block is being called no matter what argument ( therefore it does n't behave as a default parameter ) What 's...
const myFn = function ( { otherFn = ( ) = > { console.log ( 'inside myFn declaration ' ) ; return 'true ' } } ) { console.log ( 'Inside myFn2 ' , otherFn ( ) ) ; foo ( otherFn ) ; bar ( otherFn ) ; ... } myFn ( { name : 'some name ' , type : 'some type ' } ) ; // output : // inside myFn declaration// Inside myFn2 true ...
Javascript code block as a parameter for a function
JS
I want to evaluate checkbox is checked or not from a scanned image . I found the node module like node-dv and node-fv for this . But when to install this I got the following error on mac.Is the above dependency is the best solution for my problem ? If not please suggest me a good solution .
../deps/opencv/modules/core/src/arithm1.cpp:444:51 : error : constant expression evaluates to 4294967295 which can not be narrowed to type 'int ' [ -Wc++11-narrowing ] static int CV_DECL_ALIGNED ( 16 ) v64f_absmask [ ] = { 0xffffffff , 0x7fffffff , 0xffffffff , 0x7fffffff } ; ^~~~~~~~~~../deps/opencv/modules/core/src/a...
Evaluate check box from a scanned image in node.js
JS
I have a set of quiz game questions in a sql database ( javascript and sqlite actually ) . The questions all have a difficulty level from 1 to 5 , 5 being hardest . Here is a simplified visualization of the data ... Now I can shuffle these fine in sql or code so they are in a random order with no repeats but I also wan...
+ -- -- -- -- -+ -- -- -- -- -- -- -- + | id | difficulty | + -- -- -- -- -+ -- -- -- -- -- -- -- + | 1 | 1 | | 2 | 5 | | 3 | 2 | | 4 | 3 | | 5 | 2 | | 6 | 2 | | 7 | 4 | | 8 | 1 | | 9 | 5 | | 10 | 3 | + -- -- -- -- -+ -- -- -- -- -- -- -- +
How to make a controlled `` shuffle '' order ?
JS
Okay here we go : Stream.html ( Template file ) Default.aspx ( jQuery ) Update : The above has been changed to : Issues with jQuery : I have comments that belong to each .streamItem . My previous solution was to use ListView control as follows : So as you can see , this is not a solution since I started using jQuery Te...
< div class= '' streamItem clearfix '' > < input type= '' button '' / > < div class= '' clientStrip '' > < img src= '' '' alt= '' $ { Sender } '' / > < /div > < div class= '' clientView '' > < a href= '' # '' class= '' clientName '' > $ { Sender } < /a > < p > $ { Value } < /p > < p > $ { DateTime } < /p > < div class=...
CSS + jQuery - Unable to perform .toggle ( ) and repeated jQueryTemplate Item [ I must warn you this is a bit overwhelming ]
JS
Say I have two values 0 < = a < b < = 1 , how can I chose an x such that a < = x < b with the shortest binary expansion possible ? My approach so far is to take the binary strings of a and b , with the decimal point removed , and at the first place they differ , take the expansion of a up until that point . If there 's...
var binaryInInterval = function ( a , b ) { if ( a < 0 || b > 1 || a > = b ) return undefined ; var i , u , v , x = `` ; a = a.toString ( 2 ) .replace ( ' . ' , `` ) ; b = b.toString ( 2 ) .replace ( ' . ' , `` ) ; for ( i = 0 ; i < Math.max ( a.length , b.length ) ; i++ ) { u = parseInt ( a.substr ( i , 1 ) , 10 ) || ...
Find Shortest Binary String In Given Interval
JS
Before suggesting bin packing algorithms , they assume you can re-order the elements and arrange them any way you please . Note as you read that I have a restriction on the ordering and arrangement.So obviously there 's no such thing as kerning divs , but it 's the most appropriate term I could think of . Basically I h...
< script type= '' text/javascript '' src= '' https : //ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js '' > < /script > < script > var maxwidth = window.innerWidth - 80 ; function justify ( row , filled ) { var remaining = maxwidth - filled + 30 , imgs = $ ( 'img ' , row ) , margin = Math.floor ( ( remaining/i...
Algorithm for kerning divs
JS
I have a resource defined for which I have defined a custom method . In my template , I am not able to hit this method.My code looks like this . The getName ( ) function is not being called . What am I missing here $ scope.Persons = Person.query ( ) - > works perfectly
personservices.factory ( `` Person '' , [ `` $ resource '' , function ( $ resource ) { var Persons = $ resource ( `` '' , { } , { query : { method : 'GET ' } } ) ; Persons.prototype.getName = function ( ) { /* do something */ return name ; } return Persons ; } ] ) ; < ul > < li ng-repeat= '' person in persons '' > { { ...
AngularJS : $ resource custom methods not being called
JS
I want to retrieve a random row from the table of meals , how is the way to do that ? My code :
var transaction = db.transaction ( [ `` meals '' ] , `` readonly '' ) ; var store = transaction.objectStore ( `` meals '' ) ; var index = store.index ( `` time '' ) ; // to search in the field time typerange = IDBKeyRange.only ( 3 ) ; // 3 means it is a lunch index.openCursor ( range ) .onsuccess = function ( e ) { var...
Is there any way to retrieve random row from indexeddb
JS
I 'm trying to accommodate GDPR by not loading our analytics scripts until the user consents.The way I 'm doing it works as expected in every browser we support but FF Quantum 's private browsing window . ( If it helps , it works as expected in Chrome Incognito ) This is the code that I 'm using below : Is this a secur...
/** * @ name loadAnalytics * @ function * @ param { boolean } [ consented ] Determines if the consent click event should be tracked */function loadAnalytics ( consented ) { if ( analyticsExists ( ) ) return callbackAnalytics ( consented ) ; if ( ! window.analyticsScriptURL ) return ; var script = document.createElement...
Firefox Quantum Private browser not loading scripts added by javascript
JS
In Ruby , you can do this : I tried to do it in JavaScript : This works : This doesn'tChrome gives me a syntax error : `` Unexpected token ILLEGAL '' . Why ?
3.times { print `` Ho ! `` } # = > Ho ! Ho ! Ho ! Number.prototype.times = function ( fn ) { for ( var i = 0 ; i < this ; i++ ) { fn ( ) ; } } ( 3 ) .times ( function ( ) { console.log ( `` hi '' ) ; } ) ; 3.times ( function ( ) { console.log ( `` hi '' ) ; } ) ;
Why does n't JavaScript let you call methods on numbers directly ?
JS
I am new to react js . I am creating a comparison between user typing and actual sentence to be typed Somehow I am able to achieve this but It is not perfect like nested map is not rendering properly if letter typed correctly it should render green background My state is updated properly But my nested map Kinda not wor...
renderLine = ( ) = > { let test = this.props.test.get ( 'master ' ) return test.map ( line = > { return line.check.map ( ( ltr , i ) = > ltr.status ? < span key= { i } className= '' correct '' > { ltr.letter } < /span > : ltr.letter ) } ) } ; handleKeyPress = e = > { if ( e.charCode === 32 ) { this.setState ( { pushToN...
Nested map is not rendering the Redux State Correctly
JS
I have codes similar to the following : I am new in JS and I am wondering if this is a specific pattern in javascript programming . I specfically wondering what is the meaning of last line : Is It Module pattern ?
( function ( MyHelper , $ , undefined ) { var selectedClass = `` selected '' ; MyHelper.setImageSelector = function ( selector ) { var container = $ ( selector ) ; setSelected ( container , container.find ( `` input : radio : checked '' ) ) ; container.find ( `` input : radio '' ) .hide ( ) .click ( function ( ) { setS...
What is this pattern in javaScript and where can I read more about it
JS
I made the following class to 'hijack ' the console.log function . The reason behind this is that I want to add and remove valuesdynamically . It will be used for debug purposes , so the origin of the function call console.log ( ) is important . In the following code I will explain my logic in the comments.The problem ...
export class ConsoleLog { private _isActive = false ; private _nativeLogFn : any ; constructor ( ) { // -- -- -- -- -- -- -- -- -- -- -- // Store the native console.log function , so it can be restored later // -- -- -- -- -- -- -- -- -- -- -- this._nativeLogFn = console.log ; } public start ( ) { if ( ! this._isActive...
Add dynamic values to the console methods at run-time with preservation of original call position and line number intact
JS
I 'm trying to deal with different behavior of ngModel in different browsers.My directive wraps jqueryUI autocomplete and on its select event it calls ngModel. $ setViewValue ( selectedItem.id ) . Autocomplete allows user to select item by mouse click or by pressing enter on the keyboard.If suggested item is : I expect...
{ `` name '' : `` Apple '' , `` id '' : `` 1000 '' }
ngModel - How to deal with its different behavior in different browsers ?
JS
How can I use jQuery to trigger a callback of a JavaScript function when I scroll down and see a picture ? I wish to delay loading certain images until they actually appear on-screen ... Ideally , I 'd be able to do something like : So no images are loaded apart from those I have seen .
$ ( ' # img # ' ) .look_on ( ) { ...
How can I get jQuery to call an event handler when an image actually appears on-screen ?
JS
I have the following code . It works perfectly and the caller needs each part to return this due to chaining : The thing is that I need my code to pass a set of ESLint rules . The above fails with the following , where line 36 is the first line of code : The following snippet passes the rules but does NOT return this s...
module.exports = function ( res ) { return { success : function ( content , contentType , resultCode ) { sendResponse ( res , content , validateContentType ( contentType ) , validateResultCode ( resultCode||'ok ' ) ) return this } , error : function ( resultCode , content , contentType ) { sendResponse ( res , content ...
How can I 'return this ' in the current JavaScript snippet to cater for chaining in the caller without breaking my ESLint rules ?
JS
I 've a piece of code that 's been working fine until I include some css.Here is the link to the code ( the code editor here did n't like the mix of script and html and was testing my patience sorry ) . Gist code snippet can be viewed hereIt 's using Bootstrap . The issue is this works fine ( it displays a text input w...
< ! -- CSS -- > < link href= '' css/app.css '' rel= '' stylesheet '' >
Javascript text input clear button stops working in Bootstrap when I add my css . Any advice ?
JS
Can anyone explain why this line is used in lodash library.and why not just return 0 ;
if ( ! value ) { return value === 0 ? value : 0 ; }
lodash implementation of return value === 0 ? value : 0
JS
I have to filter a list of items , that contain two crucial data attributes : CategoryTagsFiltering by category should be by logical OR but filtering by tags should be by logical AND.Filtering using one of these two is not a problem.I applied , for example : to filter by tags . Or : to filter by category.This works fin...
< li class= '' song '' data-title= '' freedom '' data-id= '' 7 '' data-tags= '' tag-18-eot , tag-2-eot '' data-category= '' 1 '' > Freedom < /li > $ ( collection ) .filter ( 'li [ data-tags*= '' tag-50-eot '' ] [ data-tags*= '' tag-51-eot '' ] ' ) ; $ ( collection ) .filter ( ' [ data-category= '' 1 '' ] , [ data-categ...
Mixing logical AND and OR in jQuery selector
JS
When you are building an application where settings are set serverside with PHP , what 's the best way to communicate these settings to Javascript on pageload ? Why set all settings serverside and not partly clientside , partly serverside ? Because the app is certainly in PHP , but the Javascript part may be written in...
< input typ= '' hidden '' name= '' settings '' value= '' JSON encoded settings '' / >
What 's the best way to communicate PHP settings to Javascript ?
JS
I am not an expert in bitwise operators , but i often see a pattern which is used by programmers of 256k demos at competitions . Instead of using Math.floor ( ) function , double bitwise NOT operator is used ~~ ( maybe faster ? ) .Like this : Search revealed that there are more patterns that used the same way : When pl...
Math.floor ( 2.1 ) ; // 2~~2.1 // 2 2.1 | 0 // 22.1 > > 0 // 2 Math.floor ( 2e+21 ) ; // 2e+21~~2e+21 ; // -11198791682e+21 | 0 ; // -1119879168
Why : Math.floor ( 2e+21 ) ! = ~~ ( 2e+21 )
JS
I have made a Ajax Like Button . After clicking the like button , it takes around 800ms - 1100 ms to do the following things : Open insertlike.php page in the background using JqueryAdd the like to database in insertlike.php pageConfirm the like using JSONTurn the like button color into green . But Facebook 's and othe...
$ ( `` .insertlike '' ) .submit ( function ( e ) { var data = $ ( this ) .serialize ( ) ; var url = $ ( this ) .attr ( `` action '' ) ; var form = $ ( this ) ; $ .post ( url , data , function ( data ) { try { data = JSON.parse ( data ) ; $ ( form ) .children ( `` button '' ) .html ( data.addremove + `` Watchlist '' ) ;...
How to increase my Ajax Like Button Speed ( Jquery + PHP )
JS
This is a question similar to how to pass arguments to addeventlistnerBut the scenario is a bit different by using Youtube player 's api.So I have multiple youtube player on the same page , using swfobject : Where I 'm using ruby to generate the ytplayer object id.And I 'm listening the event onStateChange in another f...
swfobject.embedSWF ( `` http : //www.youtube.com/v/ '' +video_id+ '' ? enablejsapi=1 & version=3 & modestbranding=1 & theme=light & color=white & autohide=1 & controls=1 & showinfo=0 & iv_load_policy=3 & autoplay=0 & playerapiid= < % = `` ytPlayer # { index } '' % > '' , `` < % = `` ytPlayer # { index } '' % > '' , `` ...
How to get the source or id from youtube player onstatechange callback
JS
I 'm currently rendering Vue apps inside object tags ( iframe could work too ) of a container/master Vue app . First I setup a fileserver serving that container or the requested sub-app to render inside the div.For the sake of simplicity I will only show the required routing of my Node/Express serverMy app container / ...
// serve the sub-app on demandrouter.get ( '/subApps/ : appName ' , function ( req , res ) { res.sendFile ( path.resolve ( __dirname , ` ../apps/ $ { req.params.appName } /index.html ` ) ; } ) ; // always render the app container if no sub-app was requestedrouter.get ( '* ' , function ( req , res ) { res.sendFile ( pat...
update initial router url when running inside iframe / object tags
JS
I have a singleton object that use another object ( not singleton ) , to require some info to server : This is the 'class ' that make the request to the server } The problem is that i ca n't call myRequestManager.require from inside singleton object . Firebug consolle says : `` myRequestManager.require is not a functio...
var singleton = ( function ( ) { /*_private properties*/ var myRequestManager = new RequestManager ( params , //callbacks function ( ) { previewRender ( response ) ; } , function ( ) { previewError ( ) ; } ) ; /*_public methods*/ return { /*make a request*/ previewRequest : function ( request ) { myRequestManager.requi...
JavaScript 'class ' and singleton problems
JS
Not sure if this is a new question so pls ref to any good source if you have any.My team is working on a big JS chart project we inherited from the previous developers who made intensive use of built-in objects prototypes for adding reusable code . We have a lot of new utility functions added to Date , Object and other...
Date.prototype.my_custom_function = new function ( ... ) { ... } ; var period = new Date ( ) ; period.my_custom_function ( ) ; DateLib.my_custom_function // defined in a DateLib functionvar period = new Date ( ) ; DateLib.my_custom_function ( period ) ;
Performance and memory of prototype pollution vs dedicated library object
JS
I 'm trying to replicate a simple bitwise Javascript operation in Python . [ Javascript ] [ Python ] Having read the following : Bitwise OR in ruby vs javascriptit sounds like the issue here is that 0xA867Df55 ( 2825379669 ) in Javascript is larger than the largest signed 32-bit int ( 2147483647 ) , which is causing an...
> 0xA867Df55 2825379669 > 0xA867Df55 ^ 0 -1469587627 > > > 0xA867DF552825379669L > > > 0xA867DF55 ^ 02825379669L > > > ( 0xA867DF55 & 0x1FFFFFFF ) ^ 0141025109L
Replicating Javascript bitwise operation in Python
JS
The following comparisons all return false in javascript : However the following return true : What is the reason for this ? Especially the difference between [ 0 ] ! = [ 0 ] and [ 0 ] ==0Fiddle : http : //jsfiddle.net/vnBVj/
[ ] === [ ] [ ] == [ ] { } === { } { } == { } [ 0 ] === [ 0 ] [ 0 ] == [ 0 ] [ 0 ] == ' 0 ' [ 0 ] ==0 [ ] ==false // ( and all other == that were exampled above )
Why does [ ] === [ ] ( and others ) return false in javascript ?
JS
I have this code : So the .html ( ) is added via ajax . I want the $ sel text to be selected when it 's output on the page ( as if the user highlighted it with their cursor ) . I have the following code to select elements : How can I use that code and select just the text within $ sel ? So , output the html and select ...
$ sel = 'lorem ipsum ' ; jQuery ( this ) .html ( ' < p > Hello world ' + $ sel + ' great day ! ' ) ; function SelectText ( element ) { var doc = document , text = doc.getElementById ( element ) , range , selection ; if ( doc.body.createTextRange ) { range = document.body.createTextRange ( ) ; range.moveToElementText ( ...
Select part of text after it 's been added