lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
JavaScript newbie here , I was going through some js code at work when i came across a helper function for object creation , which went like thiswhile this does get the job done i would like to know if there is a better , cleaner way of writing this .
createElement = function ( name , data ) { if ( name == TYPES.TEXT ) { return new Text ( data ) ; } else if ( name == TYPES.WORD ) { return new Word ( data ) ; } else if ( name == TYPES.PARAGRAPH ) { return new Paragraph ( data ) ; } else if ( name == TYPES.TABLE ) { return new Table ( data ) ; } < list goes on and on ...
JavaScript object creation
JS
When something is appended to the DOM in memory , does that cause a browser reflow ? Or is it only when the pixels on the screen are told to change that the reflow happens ? For example : Case 1 : Img elements appended to the DOM one at a timeCase 2 : Img elements are put in a separate array and then appended to the DO...
var parentDiv = $ ( ' # imgHolder ' ) ; var imgArray = [ ] ; // Array of img paths populated in another function $ .each ( imgArray , function ( ) { parentDiv.append ( createImgEle ( this ) ) ; // createImgEle ( ) // returns an < img > with the right src } var parentDiv = $ ( ' # imgHolder ' ) ; var imgArray = [ ] ; //...
When something is appended to the DOM in memory , does that cause a browser reflow ?
JS
Functionality : User to play a time-based game in game page . There will be a countdown timer that will keep track of the game duration , hence , when the counter =0 , it will do a check and assess if the user has satisfy the game condition . The Game conditions are as follows:1 . ) if the counter is equal to 0 and the...
function Page2 ( ) { $ ( `` # page1 '' ) .hide ( ) ; $ ( `` # page2 '' ) .show ( ) ; } //script for div id =page2function MainGame ( ) { var numOfSpin = 0 , distanceCovered = 0 , counter = 0 , timer = 10 ; var rollingInterval ; $ ( `` # scrollerDiv '' ) .scroll ( function ( ) { var height = $ ( `` # scrollerDiv '' ) .s...
timer is not reset when `` game '' restarts
JS
Possible Duplicate : Facing weird problem while adding and removing class . Suppose I have the following html -- What I am trying to do is , check whether span with class ui-icon ui-icon-minusthick exists or not , if it exists first remove it and then add it . I tried in following way , but it 's not workingjavascript ...
< div class= '' div_portlet ui-widget ui-widget-content ui-corner-all defaultcontentbg portlet-width default_border default_border_color portlet_space '' > < div class= '' div_header headertitle align_center defaultheadercolor portlet-header-left-padding default_bottom_border default_border_color '' > < span class= '' ...
how to find a html element and then remove it ?
JS
I have the following code : The MSDN Say ~ Performs the NOT operator on each bit . NOT a yields the inverted value ( a.k.a . one 's complement ) of a.010001 should thus return this 101110.This Topic kinda confirm thatSo I ca n't understand how we can get -10010 instead ? The only potential explanation is that : 010001 ...
var a = parseInt ( '010001',2 ) ; console.log ( a.toString ( 2 ) ) ; // 10001var b = ~a ; console.log ( b.toString ( 2 ) ) ; // -10010
~ bitwise operator in JavaScript
JS
John Resig has a popular blog post on partial application : http : //ejohn.org/blog/partial-functions-in-javascript/ It 's mentioned in many places , and has However , the code in the blog post does n't work . Here it is : Now , if you try to run this in your console it 'll work fine . However , if you try to use the d...
Function.prototype.partial = function ( ) { var fn = this , args = Array.prototype.slice.call ( arguments ) ; return function ( ) { var arg = 0 ; for ( var i = 0 ; i < args.length & & arg < arguments.length ; i++ ) if ( args [ i ] === undefined ) args [ i ] = arguments [ arg++ ] ; return fn.apply ( this , args ) ; } ; ...
Is it me , or does John Resig 's popular blog post on partial application not work ?
JS
It seems that in JavaScript ( ES6 ) Classes super.__proto__ === this.__proto__.Can you explain why this is the case ? The behaviour seems consistent across different browsers , so I suspect this is specified somewhere in the spec.Consider the following code : I would have expected that super.__proto__.myFunc ( ) ; woul...
class Level1 { myFunc ( ) { console.log ( 'Level1 ' ) ; } } class Level2 extends Level1 { myFunc ( ) { console.log ( 'Level2 ' ) ; } } class Level3 extends Level2 { myFunc ( ) { console.log ( 'Level3 BEGIN ' + Math.random ( ) ) ; super.__proto__.myFunc ( ) ; console.log ( super.__proto__ === this.__proto__ ) ; console....
Why in JavaScript is ( super.__proto__ === this.__proto__ ) true ?
JS
I have created a pop out sideBar . In that sideBar I have a accordion which contains divs . Those divs are draggable . The user can drag those divs and position them main page . The problem that I am experiencing is that when the divs are dragged they are not visible outside the accordion . This can been seen in This v...
overflow : hidden ;
Draggable divs from accordion
JS
Possible Duplicate : Is JavaScript 's Math broken ? Why ca n't decimal numbers be represented exactly in binary ? What will be result of next code : It is strange , but result will be false.Reason is that result of 0.1+0.1+0.1will be 0.30000000000000004How can be explained this behavior ?
if ( 0.3 == ( 0.1 + 0.1 + 0.1 ) ) { alert ( true ) ; } else { alert ( false ) ; }
Sum of 3 variables : strange behavior
JS
Minimum Reproducible Example on GithubI 'm trying to inject some images into my pages created from markdown . I 'm trying to do this using ReactDomServer.renderToString ( ) The img is showing as a black box , if I right click the image I can open it in a new tab , which shows the image as it is supposed to be .
const componentCreatedFromMarkdown = ( { data } ) = > { ... useEffect ( ( ) = > { const injectDivs = Array.from ( document.getElementsByClassName ( 'injectDivs ' ) ) injectDivs.forEach ( ( aDiv ) = > { aDiv.innerHTML = ReactDOMServer.renderToString ( < Img fluid= { data.allFile.edges [ 0 ] .node.childImageSharp.fluid }...
Injecting gatsby-image into html created from markdown using ReactDOMServer.renderToString
JS
I 'm doing my baby steps in node.js , and i 'm trying to understand sandbox mechanism.Currently i 'm using node v4.0.0 and node-inspector v0.12.3.I 've installed gf3/sandbox module and run it with this simple code : In order to debug easily , i 've also commented the timeout function in sandbox.js file : The issue is t...
var s = new Sandbox ( ) ; s.run ( ' 1 + 1 + `` apples '' ' , function ( output ) { console.log ( output.result ) ; } ) ; // timer = setTimeout ( function ( ) { // self.child.stdout.removeListener ( 'output ' , output ) ; // stdout = JSON.stringify ( { result : 'TimeoutError ' , console : [ ] } ) ; // self.child.kill ( ...
Debugging gf3/sandbox module
JS
I would like to know why I am getting an infinite loop here . I just do n't want to pass this initial values , so if they are undefined they get automatically calculated . Its just to clean my function call to use only a single parameter . If I pass them everything runs ok and the process ends . Can anyone help ? Thank...
function merge ( array , lower , half , upper ) { //Suppressed for the sake of brevity } function mergeSort ( array , lower , upper ) { if ( ! lower & & ! upper ) { //take a look here lower = 0 ; upper = array.length - 1 ; } if ( lower < upper ) { var half = Math.floor ( ( lower + upper ) /2 ) ; mergeSort ( array , low...
Why am I getting an infinite loop when I do n't define the parameters ?
JS
I have this script adding a new span inside an editable div each time the user input a dot in the input text , trying to separate text written in different spans based on the presence of a dot separating them . ( I use a custom tag 'mytag ' but it behaves actually like a span ) JS : Here it is the JSFIDDLELet 's say I ...
< div style= '' border:1px solid black ; '' id='editor-container ' contenteditable= '' true '' > < mytag id= '' 0 '' > test < /mytag > < /div > var divContainer = document.getElementById ( `` editor-container '' ) ; var nodeIdIncrement = 0 ; var htmlBefore = divContainer.innerHTML ; var html ; var editedCharIndex ; mov...
In case of two adjacent editable span and the cursor being in the middle , how html decide on which one i 'm writing ?
JS
I ran into a case where I have run both functions in a JavaScript or expression : In this case it will output : `` First function '' trueIn C # there is a logical ( | ) OR that is different from a conditional or ( || ) that will make sure both expressions are evaluated : This will output : In this case it will output :...
function first ( ) { console.log ( `` First function '' ) ; return true ; } ; function second ( ) { console.log ( `` Second function '' ) ; return false ; } ; console.log ( ! ! ( first ( ) ||second ( ) ) ) ; Func < bool > first = ( ) = > { Console.WriteLine ( `` First function '' ) ; return true ; } ; Func < bool > sec...
Logical OR in JavaScript
JS
I have a strange situation where I am loading some content into a modal using jQuery load ( ) . This is working perfectly in development but on the production server , the object is being ignored and only sending a GET request . I 've checked the typeof object which is successful and tried other variations in the secon...
var $ modal = $ ( ' # ajax-modal ' ) ; $ ( 'body ' ) .modalmanager ( 'loading ' ) ; //_token = document.querySelector ( 'meta [ name= '' csrf-token '' ] ' ) .getAttribute ( 'content ' ) ; setTimeout ( function ( ) { var _post = { ajax : true , lead : lead , type : type } ; $ modal.load ( 'leads/action/ ' , _post , func...
Jquery load ignoring object and not posting
JS
I am facing issue while creating HTML table with JSON data , as I am new to this so not correctly able to write the logic.I have a json data from which i have to create a dynamic html table . The design of table is little complex that 's why I am not able to populate the HTML table with the correct data.From my JSON I ...
var data = [ { `` billdate '' : `` 2018-08-01 '' , `` outlet '' : `` S0001 '' , `` amount '' : 291589 , `` cash '' : 288276 , `` creditcard '' : 0 , `` coupon '' : 0 , `` paytm '' : 0 , `` credit '' : 0 , `` swiggy '' : 3313 , `` kb '' : 0 , `` bigbasket '' : 0 } , { `` billdate '' : `` 2018-08-01 '' , `` outlet '' : `...
Facing issues while creating HTML table with JSON data
JS
I was trying to figure out why one of our clients on Facebook was having issues and I traced it to the number 10150141932135203 turning into 10150141932135204 giving us rather unexpected results.How can I deal with integer numbers of this size ?
$ node > 1015014193213520310150141932135204 > 1015014193213520410150141932135204 > 1015014193213520510150141932135204 > 1015014193213520610150141932135206 > 1015014193213520710150141932135208 > 1015014193213520810150141932135208 > 1015014193213520910150141932135208 > 1015014193213521010150141932135210
Why does console.log ( 10150141932135203 ) print 10150141932135204 in both Firefox and Chrome and how to I deal with large integer values like these ?
JS
I have a table with 2 columns as shown in example , When table is re-sized ( ie . width is reduced ) , How could I make td 2 to locate below td 1 rather than displaying side by side ?
< table > < tr > < td > 1 < /td > < td > 2 < /td > < /tr > < /table >
How do I make my column dynamic in HTML
JS
I made a button group , and want when user select each button background of previous or next button move/slide to selected one , i made this effect with pure css and just used jquery to add or remove active class . now the problem is when you click on All button , then New it works fine , but if you click on Used the s...
.RadioButton .btn : first-child : :before { right : 0 ; transition : .3s all ease ; } .RadioButton .btn : nth-child ( 2 ) : :before { transition : .3s all ease ; } .RadioButton .btn : last-child : :before { left : 0 ; transition : .3s all ease ; } $ ( '.RadioButton ' ) .each ( function ( ) { $ ( this ) .find ( '.btn ' ...
Making background slide animation
JS
Was just playing around with nodejs and chrome 's console when I tested this : How come ? Is n't it wrong ?
[ ] == true // false ! [ ] == true // false ! ! [ ] == true // true
how come ! [ ] is not true ?
JS
I am working on a styleguide for a project and currently I would like to have a basic clicking behaviour on anchor links , so that they scroll to the correspondent id.As an example : That scrolls down to : In Aurelia , the default behaviour is to treat links as routes . I ca n't get the internal link to work , as it im...
< a href= '' # section '' > < /a > < div id= '' section '' > < /div >
How do I keep on the same page by clicking on internal anchor links , using Aurelia ?
JS
I 'm trying to run trusted JS code in an `` isolated '' context.Basically came up with this method : This works great , however when the script is using the var keyword it is stored in the execution context as opposed to the provided context in the with statement ( which I understand is by design ) . So for example , t...
function limitedEval ( src , context ) { return ( function ( ) { with ( this ) { return eval ( src ) } } ) .call ( context ) } var ctx = { } ; limitedEval ( 'var foo = `` hello '' ' , ctx ) ; limitedEval ( 'alert ( foo ) ' , ctx ) ; // error : foo is undefined
Running JS code in limited context
JS
I just ran into a problem when defining a function in a block scope . Consider the following program : I expected this program to alert Merry Christmas ! . However in Firefox is gives me the following ReferenceError : On Opera and Chrome it alerts the greeting as I expected it to.Evidently Firefox treats the function i...
try { greet ( ) ; function greet ( ) { alert ( `` Merry Christmas ! `` ) ; } } catch ( error ) { alert ( error ) ; } ReferenceError : greet is not defined greet ( ) ; // Merry Christmas ! function greet ( ) { alert ( `` Merry Christmas ! `` ) ; } greet ( ) ; // Happy New Year ! function greet ( ) { alert ( `` Happy New...
Function declaration or function expression
JS
Im trying to understand why new runs against the function rather than the return of the function in the example y = : So in the case of y new creates a copy of the returnFunction then invokes itAnd by invoking an anonymous function we have no this so it defaults to Window.In the case of x , by wrapping it in the parens...
function returnFunction ( ) { return function blah ( str ) { this.x = str ; return this ; } } y = new returnFunction ( ) ( `` blah '' ) // output : Window { x : `` blah '' ; top : Window , window : Window , location : Location , ... . } x = new ( returnFunction ( ) ) ( `` blah '' ) // output : blah { x : `` blah '' } z...
Using new operator with return of a javascript function returns odd scope
JS
I have a JavaScript function which I use to update hidden from fields with the file name of an image shown to a user . This works fine on a page with a single image and single hidden field . I am trying to customize it so that it can be used on a single page to update multiple hidden fields depending on whether they ex...
< input id= '' id_9-slider_one_image '' name= '' 9-slider_one_image '' type= '' hidden '' / > < input id= '' id_10-slider_two_image '' name= '' 10-slider_two_image '' type= '' hidden '' / > < input id= '' id_11-slider_three_image '' name= '' 11-slider_three_image '' type= '' hidden '' / > < input id= '' id_9-slider_one...
A JavaScript function to update multiple hidden fields depending if they exist or not
JS
Following this SO post , I am able to place the caret inside a span element , which is inside a div contenteditable= '' true '' .I am able to target whichever span I desire , via its id , while also being able to decide which character should the caret be placed after.But how can I place the caret inside a span that ha...
function setCaret ( x , y ) { var element = document.getElementById ( x ) ; var range = document.createRange ( ) ; var node ; node = document.getElementById ( y ) ; range.setStart ( node.childNodes [ 0 ] , 0 ) ; var sel = window.getSelection ( ) ; range.collapse ( true ) ; sel.removeAllRanges ( ) ; sel.addRange ( range...
How do I position the caret inside a span element that has no text inside of it yet ?
JS
I have following code in java scriptPlease run it on your browser console . It will print alternative Matched and Unmatched . Can anyone tell the reason for it .
var regexp = /\ $ [ A-Z ] + [ 0-9 ] +/g ; for ( var i = 0 ; i < 6 ; i++ ) { if ( regexp.test ( `` $ A1 '' ) ) { console.log ( `` Matched '' ) ; } else { console.log ( `` Unmatched '' ) ; } }
Regular expression with javascript
JS
I 've textarea where it increases as the text input gets added . It will reach a certain height ( until 4 rows ) and then scroll appears . I am unable to decrease the height when the text is removed.Also , I am unable to set single line text by default.FiddleBelow is the image which I am trying to achieve
< div class= '' mainContainer '' > < div class= '' container '' > < div class= '' content '' > < /div > < /div > < div class= '' footerCls '' > < div class= '' inputcls '' > < textarea name= '' text '' placeholder= '' Text goes here ... '' onkeydown= '' expand ( event , this ) '' onkeyup= '' expand ( event , this ) '' ...
Unable to decrease the height as the text gets removed in a dynamic texarea
JS
This is from How do JavaScript closures work ? . The first answer makes zero sense to me and I ca n't comment on it . It is extremely frustratingWhat does this mean ? Where does the y variable come from ?
function foo ( x ) { var tmp = 3 ; return function ( y ) { alert ( x + y + ( ++tmp ) ) ; } } var bar = foo ( 2 ) ; // bar is now a reference to the closure returned by foobar ( 10 ) ;
where does this variable come from
JS
Then I need a function that gets the average high . Here is what i did : But when i test it i got NaN as as response not the average . What I did wrong here ? Can someone give a clue ?
function getAverageHeight ( ) { let total_height = 0 ; let average_height = statues.length ; if ( statues.length > 0 ) { for ( let i = 0 ; i < statues.length ; i++ ) { let statue = statues [ i ] ; total_height += isNaN ( statues.height ) ? 0 : statue.height ; } average_height = ( total_height / statues.length ) .toFixe...
Average in Javascript
JS
UPDATE : Can anyone help ? I have been pursuing this without luck for the better half of this week . I do notice that the client is generating two POSTs . I have added code for the adapter . Is there anywhere else I should be looking ? I am going through the video tutorial provided below and am unable to resolve two er...
import Component from ' @ ember/component ' ; export default Component.extend ( { actions : { save ( ) { this.get ( 'submit ' ) ( ) ; } } } ) ; < form { { action `` save '' on= '' submit '' } } > { { input placeholder= '' description '' value=todoItem.description } } < br / > { { # if todoItem.validations.isValid } } <...
Ember : No model was found for 'user ' and Duplicate POSTs created when executing the save promise
JS
I am looking to recreate the following as seen below , dynamically without having manually define where the matches are in the Object 's properties.Desired OutcomeSo farHowever I can see there is an error logic in my code that , when it comes back out of the recursion , it overwrites the changes values with its self , ...
const obj = { levelOne : { someFun : ( ) = > { } , levelTwo : { anArray : [ ] , something : 'asas ' , levelThree : { stay : 'the same ' , name : 'Set this one ! ' , } , } , } , } const updatedObj = { ... obj , levelOne : { ... obj.levelOne , levelTwo : { anArray : [ ] , ... obj.levelOne.levelTwo , levelThree : { ... ob...
Dynamically set property of nested object if they exist . Recreate _.extend
JS
I 've been exploring Twin-Bcrypt JavaScript library , and found a strange thing . At one moment , I 've made my own salt on server side with PHP base64_encode ( openssl_random_pseudo_bytes ( 16 ) ) and used it in TwinBcrypt.hash ( ) function , which responded that salt is invalid because of the regular pattern mismatch...
var SALT_PATTERN = /^\ $ 2 [ ay ] \ $ ( 0 [ 4-9 ] | [ 12 ] [ 0-9 ] |3 [ 01 ] ) \ $ [ .\/A-Za-z0-9 ] { 21 } [ .Oeu ] / ;
JS Twin-Bcrypt salt pattern
JS
I am trying to use text to speech to help the blind users to use my website as part of my project , it worked well with me for the input , select and button elements . But I want also to make voice for the other elements such label elements . I tried to use ( for ) instead of id and tried to use the event ( mouseover )...
< div class= '' all '' > < form action= '' /action_page.php '' > < div class= '' container '' > < h1 > Register < /h1 > Select Voice : < select id='voiceList ' > < /select > < br > < br > < p > Please fill in this form to create an account. < /p > < hr > < input id='text1 ' type= '' text '' placeholder= '' Enter Email ...
JavaScript text to speech for different elements
JS
I already have a decent algorithm that is able to combine and mix CMYK colors together . However it is unable to combine additional hex colors without failing . I would like some help in figuring out how I can edit the algorithm to accept other colors . I know its possible to color mix several colors as I 've seen it b...
var slider = new Slider ( ' # ex1 ' , { formatter : function ( value ) { return 'Current value : ' + value ; } } ) ; var colorPercentages = { } ; var colors = document.getElementsByClassName ( `` colors '' ) ; for ( let i = 0 ; i < colors.length ; i++ ) { if ( ! ( colors [ i ] .getAttribute ( `` id '' ) in colorPercent...
Adding additional hex colors to RGB color mixing algorithm
JS
I 'm creating a really Find/Replace System but one of the main features are not working.What 's Supposed to happen : Once you search all words found will highlight on the page . I want it so you can click it and it opens an Div saying : Replace { WORD HERE } with { INPUT } and then you can hit replace and it will repla...
return 'Code Here ' ; shortcut.add ( `` Ctrl+F '' , function ( ) { $ ( ' # finder ' ) .animate ( { 'bottom ' : '-53px ' } , 100 ) ; } ) ; shortcut.add ( `` Shift+F '' , function ( ) { $ ( ' # finder ' ) .animate ( { 'bottom ' : '0px ' } , 100 ) ; } ) ; shortcut.add ( `` Ctrl+C '' , function ( ) { $ ( ' # finder ' ) .an...
Unique Find/Replace System Not Working
JS
I am doing little mosaic ( if i can call it like that ) . I am changing scale and opacity based on position mouse and the center of the picture/div.I am calculating the distance via vektors with and im looping throught the divs/pictures and if the distance is smaller than 100 , it calculates its opacity/scale.But i cam...
function calculateDistance ( elem , mouseX , mouseY ) { return Math.floor ( Math.sqrt ( Math.pow ( mouseX - ( elem.offsetLeft + ( elem.offsetWidth / 2 ) ) , 2 ) + Math.pow ( mouseY - ( elem.offsetTop + ( elem.offsetHeight / 2 ) ) , 2 ) ) ) ; }
Shaky scale animation
JS
I 'm using CollectionFS for managing images . Furthermore I 'm using graphicsmagick gm ( ) for manipulating images.Now I want to crop a already saved image . Therefore on a click event a server-method is called , which does the crop ( ) . But after doing this , in the collection I find an empty image with size=0 update...
Images = new FS.Collection ( `` images '' , { stores : [ new FS.Store.FileSystem ( `` thumbnail '' , { transformWrite : function ( fileObj , readStream , writeStream ) { gm ( readStream , fileObj.name ( ) ) .autoOrient ( ) .resize ( '96 ' , '96 ' + '^ ' ) .gravity ( 'Center ' ) .extent ( '96 ' , '96 ' ) .stream ( ) .pi...
Unexpected empty writestream in collectionFS using graphicsmagick
JS
I have following code : I think Proxy should proxy everything about [ 1,2,3 ] .When I log value , it should read value from [ 1,2,3 ] , so the getter should be triggered.But when I set a breakpoint in the getter , the breakpoint is not hit ? Why do n't console.log and console.table trigger the getter function ?
let p = new Proxy ( [ 1 , 2 , 3 ] , { get : function ( ) { console.log ( 'get ' ) } } ) console.log ( p )
Why does console.log not trigger proxy getter trap ?
JS
This works : But this is causing syntax error : error is : They two should be the same thing , why the first one works , while the second fails ?
alert ( 'foo\ bar ' ) t='test ' ; alert ( ' < tr > < td > < b > ' + t + ' < /b > < /td > \ < td > < /td > < td > ' ) SyntaxError : unterminated string literal
Have problem with multi-line string in javascript
JS
Is this possible ? Example : I want to detect if doing this is possible .
var parts = [ 1,2,3,4,5 ] ; for ( part of parts ) { console.debug ( part ) ; }
Detect for ... of Loop Support in JavaScript
JS
I 'm having some trouble updating nested components in my tree structure . I have created the following minimal example to illustrate the problem : Codesandbox.ioFor completeness sake , this is the component that 's being nested : Nodes in the tree should be selectable on click and I 'd like to toggle the selected stat...
class Node extends React.Component { constructor ( props ) { super ( props ) ; this.state = { selected : props.selected } ; this.toggleSelected = this.toggleSelected.bind ( this ) ; } toggleSelected ( ) { this.setState ( { selected : ! this.state.selected } ) ; } render ( ) { return ( < > < div onClick= { this.toggleSe...
Nested Components not updating their state
JS
I 'm trying to match words that consist only of characters in this character class : [ A-z'\\/ % ] , excluding cases where : they are between < and > they are between [ and ] they are between { and } So , say I 've got this funny string : I need to match the following strings : I 've tried using this pattern : But for ...
[ beginning ] < start > How 's { the } /weather ( \\today % ? ) [ end ] [ `` How 's '' , `` /weather '' , `` \\today % '' ] / [ A-z'/\\ % ] * ( ? ! [ ^ { ] * } ) ( ? ! [ ^\ [ ] *\ ] ) ( ? ! [ ^ < ] * > ) /gm [ `` [ beginning ] '' , `` '' , `` How 's '' , `` '' , `` '' , `` '' , `` /weather '' , `` '' , `` '' , `` \\tod...
Match words that consist of specific characters , excluding between special brackets
JS
I 've built a JavaScript widget that must be embeddable on any third-party site , in any environment . The widget relies on jQuery and jQuery UI . I followed the steps in How to embed Javascript widget that depends on jQuery into an unknown environment to add jQuery in a responsible manner -- works great for embedding ...
( function ( window , document , version , callback ) { var j , d ; var loaded = false ; if ( ! ( j = window.jQuery ) || version > j.fn.jquery || callback ( j , loaded ) ) { var script = document.createElement ( `` script '' ) ; script.type = `` text/javascript '' ; script.src = `` https : //ajax.googleapis.com/ajax/li...
Why does n't jQuery UI see jQuery ?
JS
Why this works ? What are benefits of declaration local functions after return ? Is this good practice ?
function f ( ) { return f1 ( ) ; function f1 ( ) { return 5 ; } } f ( ) ; // returns 5
Declaration after return statement
JS
The Managing arguments section in Bluebird 's article on Optimization killers states that : The arguments object must not be passed or leaked anywhere.In other words , do n't do the following : But do do this : With the introduction of Rest paramters , will passing the rest parameter array still cause optimization issu...
function leaky ( ) { return arguments ; } function not_leaky ( ) { var i = arguments.length , args = [ ] ; while ( i -- ) args [ i ] = arguments [ i ] ; return args ; } function maybe_optimizable ( ... args ) { return args ; } function debounce ( func , wait , immediate ) { let timeout ; return function ( ... args ) { ...
Do rest parameters allow for optimization ?
JS
I 've got array of objects , where I take only locations array . My goal is to merge these locations array to one array , however I fail to do so and get empty array . This is how I do it : what I am doing wrong here ? The result should be [ 'aaaa ' , 'bbbbbb ' , 'cccccc ' , 'ddd ' , 'aaadsad ' , 'sefd ' , 'ffff ' , 'e...
let results = [ { id : ' 1 ' , locations : [ 'aaaa ' , 'bbbbbb ' , 'cccccc ' ] } , { id : ' 2 ' , locations : [ ] } , { id : ' 3 ' , locations : [ 'ddd ' , 'aaadsad ' , 'sefd ' ] } , { id : ' 4 ' , locations : [ 'ffff ' , 'eeee ' , 'sfdsfsd ' ] } , ] ; const locationIds = [ ] .concat.apply ( [ ] , ... results.filter ( ...
Merge arrays to one array after filtering
JS
I have a form with a dependent drop-down . This secondary drop-down is hidden whenever the primary option selected does not have any secondary options , and when the page first loads . Whenever the form is submitted , only the first field gets cleared out , since most of the time the drop-downs remain the same , howeve...
class WarehouseForm ( AppsModelForm ) : class Meta : model = EmployeeWorkAreaLog widgets = { 'employee_number ' : ForeignKeyRawIdWidget ( EmployeeWorkAreaLog._meta.get_field ( 'employee_number ' ) .remote_field , site , attrs= { 'id ' : 'employee_number_field ' } ) , } fields = ( 'employee_number ' , 'work_area ' , 'st...
How to `` load '' dependent drop down upon page load ?
JS
I realise that it is useful ( for performance reasons ) to do something like ... So when the code accesses window , it does n't need to go up the scope chain to finally find window . The same can be done for document , navigator , etc ... But I 'm in the process of rewriting some of the MobiScroll jQuery plugin and fou...
function Abc ( a , b , c ) { var window = window ; function Scroller ( elm , dw , settings ) { ... var elm = elm ; var dw = dw ; ...
What is the point of reassigning argument variables ?
JS
I have read the MDN page on the `` Object.is '' method.It gives an alternative code for the browsers that do not provide this method : The question is simple : when can the second `` if '' be true ? Thank you for your attention .
if ( ! Object.is ) { Object.is = function ( v1 , v2 ) { if ( v1 === 0 & & v2 === 0 ) { return 1 / v1 === 1 / v2 ; } if ( v1 ! == v1 ) { return v2 ! == v2 ; } return v1 === v2 ; } ; }
MDN `` Object.is '' alternative proposal
JS
I have two components . 1 . App component , 2. child component.For better understanding , the code and output is here in stackblitz : https : //stackblitz.com/edit/angular-j9cwzl app.component.ts : child.component.tsWhen I write the id of the child component directly in the template of the App component it renders nice...
import { Component } from ' @ angular/core ' ; @ Component ( { selector : 'my-app ' , template : ` < div id= '' child '' > < /div > < div id= '' { { childComponent } } '' > < /div > ` } ) export class AppComponent { childComponent='child ' ; } import { Component } from ' @ angular/core ' ; @ Component ( { selector : ' ...
How to render a component through the id is stored in variable ?
JS
I have the following Javascript function that should return an array of groups that are in database . It uses $ .getJSON ( ) method to call get_groups.php which actually reads from the database.Unfortunately , this function does not work as expected because groups.push ( response [ i ] ) ; does not fill the var groups ...
function get_groups ( ) { var groups = [ ] ; $ .getJSON ( 'get_groups.php ' , function ( response ) { for ( var i in response ) { groups.push ( response [ i ] ) ; } } return groups ; }
Need help with variable scope in Javascript
JS
In password strategy , there are 4 requirements.It should contains any three of the followinglower case.upper case.numeric.special character.The following regex will match all casesI know I can use '| ' to declare all combinations , however , that will produce a supper long regex . What is the best way to replace '| ' ...
^ ( ? =.*\d ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) ( ? =.* [ ^a-zA-Z0-9 ] ) . { 4,8 } $
The best way to match at least three out of four regex requirements
JS
I am writing my own jQuery navigation submenu script . When you hover over a link in the horizontal nav that has a ul tag , it makes that ul appear . I have a bit of code that adds an arrow to the links in the horizontal nav if it has a submenu . My problem is that it also adds the arrows to the links in the submenu . ...
$ ( document ) .ready ( function ( ) { $ ( 'nav ul li : has ( ul ) ' ) .each ( function ( ) { var listItem = $ ( this ) ; $ ( this ) .find ( ' > a ' ) .each ( function ( ) { var aTag = $ ( this ) ; aTag.append ( ' < img src= '' { img_url } /caret.png '' width= '' 8 '' height= '' 8 '' > ' ) ; aTag.on ( 'mouseover ' , fu...
How to not add arrows to links in my submenu in jQuery ?
JS
I am trying to check if a string contains certain words which I had stored in an array ... however I am a bit newer to javaScript so I do n't exactly know how to check all of the elements inside the Array ... here is an Example : The array above is just an example as I am actually checking if someone sends swearwords i...
const fruits = [ `` apple '' , `` banana '' , `` orange '' ] if ( message.content.includes ( fruits ) ) { executed code } ;
Getting All Elements In An Array ( Javascript )
JS
Below is an example of my parent/child states and the index.html file that renders my angular app . No toastr messages appear in the child states , not sure why . The dependency is included as expected in each controller . config.jsindex.htmlSample controller ( this happens in every child state of 'app ' ) Rendered HTM...
( function ( ) { 'use strict'var app = angular.module ( 'core ' ) ; app.config ( AppRouter ) ; AppRouter. $ inject = [ ' $ stateProvider ' , ' $ urlRouterProvider ' ] ; function AppRouter ( $ stateProvider , $ urlRouterProvider ) { $ urlRouterProvider.otherwise ( '/home ' ) ; $ stateProvider .state ( '/ ' , { templateU...
toastr does n't appear in ui-router child states
JS
In the example code below I want to filter numbersArray based on different intervals . An interval is defined by a combination of 2 arrays with the lower and upper bound of said interval . How do I identify matches or non-matches like below ? If the code works the following test should return true : Assume the arrays c...
const numbersArray = [ 1,2,3,4,5,6,7,8,9,10 ] ; const lowerBound = [ 1 , 4 , 8 ] ; const higherBound = [ 3 , 6 , 10 ] ; matches == [ 2 , 5 , 9 ] ; nonmatches == [ 1 , 3 , 4 , 6 , 7 , 8 , 10 ] ; let numbersArray = [ ] ; let lowerBound = [ ] ; let higherBound = [ ] ; for ( let i = 0 ; i < 1000 ; i++ ) { numbersArray.push...
How to filter an array of numbers using different intervals ?
JS
Friends , I created a function that does an element animate or 'desanimate ' depending on where the scroll of the body or a div is , it 's working ok , how it works ? the first value of the data-animation-time array is the initial value , ie the animator function should be called when the scrollTop pass that value , th...
animate = animate ; desanimate = undo animate ; < li data-animation-time= '' [ 100 , 800 ] '' data-animation-position= '' right '' class= '' list-item one '' > < /li > var animate = function ( target , position ) { target.css ( 'display ' , 'inline-block ' ) ; if ( position === 'right-to-right ' ) { target.animate ( { ...
make animation with scrollTop
JS
I am creating a table looks like this with the codes below : I am trying to use 'Javascript ' to do set condition and compare to value in `` td '' .I am having problem to set different condition for each column . Need help : Eg : I want to set 2 conditions , how do i assign td name/id ? [ Condition 1 ] Highlight , if '...
< style > table , th , td { border : 1px solid black ; } < /style > < script src= '' js/jquery.min.js '' > < /script > < table id='ss ' > < tr > < th > WW < /th > < th > Qty < /th > < th > percentage < /th > < /tr > < tr > < td > WW01 < /td > < td > 1000 < /td > < td > 50 % < /td > < /tr > < tr > < td > WW02 < /td > < ...
Multiple < td > with multiple conditions
JS
I 'm just getting to grips with Angular , but passing around scope is getting the better of me when I try to abstract reusable components into separate modules.I 'm using an Angular Youtube module found here https : //github.com/arnaudbreton/angular-youtube but it 's woefully inadequate so I 'm bolting on new functiona...
angular.module ( 'youtube ' , [ 'ng ' ] ) .service ( 'youtubePlayerApi ' , [ ' $ window ' , ' $ rootScope ' , ' $ log ' , function ( $ window , $ rootScope , $ log ) { var player = $ rootScope. $ new ( true ) ; player.playerContainer = null ; player.create = function ( attrs ) { player.playerId = attrs.id ; player.vide...
How do you call your module 's controller function from an entirely separate module 's controller ?
JS
Imagine this simplified markup : and assume you already have this code : Is there any speed difference for jQuery to lookup `` detail '' this way : vsSince detail is being looked up by ID ?
< div id= '' header '' > < ! -- Other things ... . -- > < div id= '' detail '' > < /div > < /div > var $ hdr = $ ( `` # header '' ) ; var $ detail = $ ( `` # detail '' , $ hdr ) ; var $ detail = $ ( `` # detail '' ) ;
If you select an element in jQuery by ID is there still a speed improvement by giving it a context ?
JS
I have an URL of a live image and I want to display it as a video , but only first frame is show instead of an animation . I use Google Chrome Version 36.0.1985.125.What am I missing ?
< video id= '' one_frame_per_second '' autoplay=autoplay poster= '' http : //ip.address/screensaver/now.jpeg '' > < /video > < script > $ ( document ) .ready ( function ( ) { $ ( ' # one_frame_per_second ' ) .show ( ) ; mtimer = setInterval ( function ( ) { $ ( ' # one_frame_per_second ' ) .attr ( 'poster ' , 'http : /...
Why doesn ’ t my jQuery code update live image loaded in a video element ?
JS
EDIT > > Plunker : http : //plnkr.co/edit/LY7LUAylvKQ3pIv9lhYM ? p=previewI 've implemented jQuery Scroll for Tab-Titles , it works well.If I am at the beginning the arrow on the left side should disappear and when I move right it should be shown . If I am at the end the arrow on the right side should disappear.How cou...
$ ( ' # nextTabBtn ' ) .click ( function ( ) { var $ target = $ ( '.tabBoxMantle ' ) ; if ( $ target.is ( ' : animated ' ) ) return ; $ target.animate ( { scrollLeft : $ target.scrollLeft ( ) + 300 } , 800 ) ; } ) ; $ ( ' # prevTabBtn ' ) .click ( function ( ) { var $ target = $ ( '.tabBoxMantle ' ) ; if ( $ target.is ...
jQuery Scroll : detect end and start
JS
I 'm new to object oriented programming and am slowly learning how to apply it to javascript . So please bear with me . : ) I have two basic objects : '' record '' which contains methods for editing a single record from a recordset . ( create , save , load , etc . ) '' recordList '' which contains methods for outputtin...
control = { } control.record = object.create ( `` record '' ) ; control.recordList = object.create ( `` recordList '' ) ; control.save = function ( ) { this.record.save ( ) ; this.recordList.refresh ( ) ; } ;
What is the proper way to control related objects in javascript ?
JS
Probably irrelevant from a production standpoint , but I 'd like to know why this behaves the way it does . The string literal gets interpreted as an object . I have to callinside the function if I want the expected output . I know strings are objects in javascript ( which is lovely ) but in a simple console.log ( 'abc...
function fancyCallback ( callback ) { callback ( this ) ; console.log ( typeof this ) ; // just to see it really is an object } fancyCallback.call ( 'string here ' , console.log ) ; this.toString ( )
javascript string interpreted as object
JS
I 'm trying to make a little game with JavaScript ( no engine ) and I want to get rid of frame-based animation.I successfully added delta time for horizontal movements ( work fine with 60 or 144fps ) .But I ca n't make it work with the jump , height ( or the strength ) is n't always the same , and I do n't know why.I a...
const canvas = document.getElementById ( 'canvas ' ) , ctx = canvas.getContext ( '2d ' ) , canvas2 = document.getElementById ( 'canvas2 ' ) , ctx2 = canvas2.getContext ( '2d ' ) ; // CLASS PLAYER -- -- -- -- -- -- -- -- -- -- -- -- class Actor { constructor ( color , ctx , j ) { this.c = ctx this.w = 20 this.h = 40 thi...
How to calculate jump based on delta time ?
JS
I 'm trying to make my web app work offline with service workers and ran into a strange problem.I 've defined some shell files for my app like in the guide on MDNInstalling that service worker fails because I get a CORS error for the css file from S3 . I have already confirmed that my CORS settings on the bucket are co...
const cacheName = 'SiMo-v0.1 ' ; const appShellFiles = [ '/index.html ' , '/js/build/map.c6393552f9958cd32710.js ' , 'https : //intermaps-lynx.s3-eu-west-1.amazonaws.com/css/menu.css ' , ] ; self.addEventListener ( 'install ' , ( e ) = > { console.log ( ' [ Service Worker ] Install ' ) ; e.waitUntil ( caches.open ( cac...
Chrome unable to fetch css from s3 in service worker
JS
Can someone please tell me why the last logging of ' x ' equals 0 and not 1 . I thought because it 's declared outside of a function it has global scope and then in the function it 's value is set to 1 and that value would remain as it 's a global ? I know the first ' x ' value inside the function is a global as any va...
var x = 0 ; //global variablefunction y ( ) { x = 1 ; log ( `` 1 . % n `` , x ) ; //1 . 1 var x = 2 ; log ( `` 2 . % n `` , x ) ; //2 . 2 } y ( ) ; log ( `` 3 . % n `` , x ) ; //3 . 0
And I thought I understood scope
JS
I am using Angular UI Router . Please find the code below . index.htmlRouteMainController.jsLogin.htmlLoginController.jsHome.htmlTest1.htmlI am able to Login successfully and getting the menu tab with `` Hello World '' Link . I want to display Menu Tab always and change the below text dynamically.My problem is that whe...
< html lang= '' en '' xmlns= '' http : //www.w3.org/1999/xhtml '' > < head > < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js '' > < /script > < script src= ...
Not able to load ui-view even when the state change
JS
I have a saga which is listening to an action.And when this action is dispatched it performs a blocking call.The problem is that a lot of actions ( same actions ) are dispatched in the same time and my saga ca n't take all the actions . But I need to process each action synchronously.I know this is a known problem in r...
export function* readProducts ( ) { while ( true ) { const { payload : { tags } , } = yield take ( RFID__ADD_PRODUCT ) ; // sequential add of each item for ( const tag of tags ) { yield call ( addProductViaRfid , tag ) ; } } }
How to take multiple actions dispatched with blocking call
JS
I have a JSON array in the format like thisand I have to access each element of it and display it into options in select tag asI am new to JSON and have to do it using javascript/jQuery so any help/guidance will be appreciated .
`` StoreName '' : [ `` 10001 Main ST '' , '' 10002 Part1 '' , '' 10004 MyStore1 '' , '' 10005 M STR '' , `` 10008 Centro '' , '' 10009 MyStore 02 '' , '' 1001 G '' , '' 1001 H '' , '' 10010 Store main ROAD '' , '' 10011 Central M Store '' , '' 10012 En Department '' , '' 10013 M Station '' , '' 10014 Test Center '' , '...
how to display json array elements dynamically into select tag ?
JS
A while ago I created a small cardgame web app for fun . The player plays against the computer and mostly it works fine . Sometimes though the computer player gets into a loop , the point of the game is to lose all your cards and if you do n't have a card to play you take the pile . Sometimes the computer plays x , y ,...
function findLoops ( previousMoves , nextMove , maxPatternLength ) { //Return [ loopLength , loopCount ] or null if there are no loops }
Detect loops in computer player in a cardgame
JS
my problem is described below with examplenumber-1 : if i use console.log ( myString ) ; the output is String { 0= '' f '' , 1= '' o '' , 2= '' o '' } and number-2 : here console.log ( mystring ) ; prints just foohere what is the difference between number-1 and number-2 ? why the ouput is different ?
var myString = new String ( 'foo ' ) ; var myString = new String ( ) ; myString = `` foo '' ;
difference between string object , and primitive string
JS
Is there a way to apply the replace method on Unicode text in general ( Arabic is of concern here ) ? In the example below , whereas replacing the entire word works nicely on the English text , it fails to detect and as a result , replace the Arabic word . I added the u as a flag to enable unicode parsing but that did ...
< ! DOCTYPE html > < html > < body > < p > Click to replace ... < /p > < button onclick= '' myFunction ( ) '' > replace < /button > < p id= '' demo '' > < /p > < script > function myFunction ( ) { var str = `` الشمس والقمر والنجوم، ثم النجوم والنهار '' ; var rep = 'النجوم ' ; var repWith = 'الليل ' ; //var str = `` the...
replace/replaceAll with regex on unicode issues
JS
I have an issue with a data binding inside a directive , which call another directive.Here is the main directive : Here is the other directive : And the html code wich call the main directive : When calling `` other-directive '' , the `` idFromServer '' is not bind , and is `` undefined '' , so it results to diplay `` ...
var app = angular.module ( 'app ' ) ; app.directive ( `` myMainDirective '' , function ( $ http ) { return { scope : { paramId : '= ' } , link : function ( scope ) { $ http.get ( 'some/url/ ' + scope.paramId+ '.json ' ) .success ( function ( data ) { scope.idFromServer = data ; } ) ; } , template : ' < span other-direc...
Angular JS - Data binding in directive is not working
JS
for example , suppose I need to do different things according to combinations of boolean values : cond_0 , cond_1 and cond_2 : it looks as if mapping bit numbers to functions : while the general rule looks like very simple , I do n't know how to write it without if-else , and the current form looks like that : which is...
cond_0 cond_1 cond_2false false false a ( ) ; false false true b ( ) ; ... true true true h ( ) ; 000 : a ( ) 001 : b ( ) ... 111 : h ( ) var f=function ( cond_0 , cond_1 , cond_2 ) { if ( ! cond_0 & & ! cond_1 & & ! cond_2 ) { a ( ) ; } else if ( cond_0 & & ! cond_1 & & ! cond_2 ) ) { b ( ) ; } else if ( ! cond_0 & & ...
How to eliminate if-else when doing different things according to different combinations of boolean value ?
JS
In an example of a very common scenario , where we need to change the style of an entire class of elements , we have a ( simplified and generalized ) code that looks like this : It gets all the div elements from the document , loops through them , and changes the visibility of ones that have class `` HideMe '' to `` hi...
var elements = document.getElementsByTagName ( 'div ' ) ; for ( var i = 0 ; i < elements.length ; i++ ) if ( elements [ i ] .className == 'HideMe ' ) elements [ i ] .style.visibility = 'hidden ' ; document.innerHTML.replace ( /class= '' HideMe '' /mg , 'class= '' HideMe '' style= '' visibility : hidden '' ' ) ; documen...
JavaScript efficient style change on the entire class of elements
JS
So I want to convert : From : To : I tried the following code : Is this the way you to would do it as well ? I believe I 'm not using reduce correctly ? PS : I get the right result ! Just wanted to know if it is the elengant way or not ?
{ emailNotify : { EQ : true } , foo : { bar : false } } [ { 'condition ' : 'EQ ' , 'attribute ' : emailNotify , 'value ' : true } , { 'condition ' : 'bar ' , 'attribute ' : foo , 'value ' : false } ] var fromObj= { emailNotify : { EQ : true } , foo : { bar : false } } ; console.log ( Object.keys ( fromObj ) ) ; var res...
Reduce in Javascript
JS
I 'm trying to display a loading icon while data is loading , and then the data when it 's ready.The problem is I for a few seconds , I can see loading icon AND the data ... Here is my codeMy view : My content is loaded asynchronously . The loading value is set to false at soon as I get the result , so the icon should ...
$ scope.items [ y ] .content.push ( { text : `` , loading : true } ) ; API.getContent ( id , x , y , function ( response , x , y ) { $ scope.items [ y ] .content [ x ] .loading = false ; $ scope.items [ y ] .content [ x ] .text = response.data.text ; } ) ; < i ng-show= '' item.loading '' class= '' fa fa-spinner fa-puls...
condition met ngShow AND ngHide
JS
I have a page that begins as follows : I would like to grab the 12036 number here and to display it within an absolutely positioned DIV at the bottom right of my screen . My intention here is to either to use it as a bookmarklet or as a Greasemonkey script . The purpose of this is that the number represents a PAGE ID t...
< html > < head > < ! -- 12036,2011-11-29/11:02 -- > < title > Products & Services < /title > var x = document.getElementsByTagName ( 'head ' ) .innerHTML ;
Javascript to grab Javascript comments within < head >
JS
I 've been trying to learn javascript by refactoring some Jquery examples in a book into javascript . In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab . This returns an undefined error when I run it . However , I tried replacing tabs [ tabNumber ] .class...
var tabs = document.querySelectorAll ( `` .tabs a span '' ) ; var content = document.querySelectorAll ( `` main .content li '' ) ; for ( var tabNumber = 0 ; tabNumber < = 2 ; tabNumber++ ) { tabs [ tabNumber ] .addEventListener ( `` click '' , function ( event ) { for ( var i = 0 ; i < tabs.length ; i++ ) { tabs [ i ] ...
Trying to make sense of `` this '' in my javascript code ( one thing works , the other does n't )
JS
I 've been testing the following code , but Firefox16 and Chrome22 gives me different outcomes.As far as I can remember , Chrome 's answer is right : Unless called with new , this is always same as the global object window , which leads to a pattern called scope safe constructors .
console.log ( this===window ) ; //false in Firefox and true in Chromeconsole.log ( this.window===window ) ; //true in both Firefox and Chrome ( function ( ) { console.log ( this===window ) ; //false in Firefox and true in Chrome console.log ( this.window===window ) ; //true in both Firefox and Chrome } ) ( ) ;
Why ` this===window ` gives me false ?
JS
I realise JavaScript has no pointers , however I noticed this `` pointer '' behaviour when looping through arrays that contains objects , but not the similar behaviour when an array contains numbers ( for instance ) .Now with an array with objectsWhy these two distinct behaviours ?
var ARR_num = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ; for ( var i = 0 , len = ARR_num.length ; i < len ; i++ ) { var item = ARR_num [ i ] ; item++ ; } console.log ( ARR_num ) ; //Outputs [ 0,1,2,3,4,5,6,7,8,9 ] var ARR_obj = [ { } , { } , { } ] ; for ( var i = 0 , len = ARR_obj.length ; i < len ; i++ ) { var item =...
Why javascript `` for loop '' has different behaviours for different type of objects
JS
I am experimenting with the functional List type and structural sharing . Since Javascript does n't have a Tail Recursive Modulo Cons optimization , we ca n't just write List combinators like this , because they are not stack safe : Now I tried to implement take tail recursively , so that I can either rely on TCO ( sti...
const list = [ 1 , [ 2 , [ 3 , [ 4 , [ 5 , [ ] ] ] ] ] ] ; const take = n = > ( [ head , tail ] ) = > n === 0 ? [ ] : head === undefined ? [ ] : [ head , take ( n - 1 ) ( tail ) ] ; console.log ( take ( 3 ) ( list ) // [ 1 , [ 2 , [ 3 , [ ] ] ] ] ) ; const list = [ 1 , [ 2 , [ 3 , [ 4 , [ 5 , [ ] ] ] ] ] ] ; const safe...
How can I prevent a tail recursive function from reversing the order of a List ?
JS
I 'm trying to send postmessage from the opened window to opener in facebook app browser , but the `` opener window '' never receives messages . What can be the cause of the problem ? Receiver side : Sender side :
window.addEventListener ( 'message ' , function ( e ) { window.console.log ( `` on message : `` + e.data ) ; } , false ) window.opener.postMessage ( 'any Message ' , document.location.origin ) ;
How to receive postmessage inside Facebook in-app browser ?
JS
I am trying to show JSON data in a textbox.Data is in this format : I have tried this : But issue is that if there is no data in Floor then there will a linebreak between floor and city . How to avoid line breaks if there is no data in address line ?
address { `` street '' : '' 1st main Road '' '' building_name '' : '' Florence '' '' Floor '' : '' '' '' city '' : '' New York '' } $ ( ' # id_address ' ) .val ( address.street+'\n'+address.building_name+'\n'+address.Floor+'\n'+address.city ) ;
Jquery fill text area with linebreak and nothin if no data
JS
I have an input with text-overflow : ellipsis . Is it possible to show the beginning of the text on blur ( ) ? Right now it stays at the end of the text where the cursor was.Consider the following GIF trying to demonstrate the issue.First , I focus the < input > and go the beginning of the input Ctrl + Home . Then I go...
$ ( `` input '' ) .on ( 'blur ' , function ( e ) { $ ( this ) .get ( 0 ) .setSelectionRange ( 0,0 ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < input type= '' text '' value= '' A bunch of text text text text text text text text text '' style= '' width :...
`` Rewind '' input on blur ( )
JS
Expanding on this answer I would like to know how to create new modules that belong to the same namespace ( PROJECT ) . Moduleshttp : //jsfiddle.net/sKBNA/
A.init ( ) ; -- will become -- > PROJECT.A.init ( ) ; ( function ( A , $ , undefined ) { A.init = function ( ) { console.log ( `` A init '' ) ; } ; } ( window.A = window.A || { } , jQuery ) ) ; ( function ( B , $ , undefined ) { B.init = function ( ) { console.log ( `` B init '' ) ; } ; } ( window.B = window.B || { } ,...
JavaScript Self-Executing Anonymous Modules
JS
I need to make to redirect the user to another page , in accordance to the language of the browser . For example : if the language of the browser english redirect to site.com/en/.I try to do like this : It 's works but the page is constantly reloaded . How to solve it or prompt another solution ?
$ ( document ) .ready ( function ( ) { var userLang = navigator.language || navigator.userLanguage ; switch ( userLang ) { case 'en ' : window.location.href = window.location.origin + '/en ' ; break ; case 'de ' : window.location.href = window.location.origin + '/de ' ; break ; default : break ; } } ) ;
How to redirect user to different page ?
JS
I want to sort an array.The items in the array have relationships.eg . list [ 5 ] should be before list [ 9 ] but after list [ 3 ] The expected value in the sample is just for testing . It does not really exist.Here 's a sample array with the relationships and an expected index .
var list = [ { id : '0001 ' , before : '0002 ' , expected : 0 } , { id : '0002 ' , before : '0007 ' , after : '0001 ' , expected : 4 } , { id : '0003 ' , before : '0006 ' , after : '0001 ' , expected : 2 } , { id : '0004 ' , after : '0007 ' , expected : 11 } , { id : '0005 ' , before : '0003 ' , after : '0001 ' , expec...
sort an array by relationship in javascript
JS
I have a table of text-checkbox items , each with a description and a checkbox . I now need to add an uber-checkbox that will either clear or check all boxes . The current code , is shown below , with my first attempt at a solution highlighted.I could probably so easily do this with jQuery , but I 'd rather use Angular...
< table width= '' 100 % '' border= '' 0 '' cellspacing= '' 0 '' cellpadding= '' 0 '' class= '' table table-bordered '' > < tr id= '' myBlusteringAttempt '' > < td width= '' 90 % '' > < p > Clear/Check all options < /p > < /td > < td width= '' 10 % '' align= '' center '' valign= '' middle '' > < input type= '' checkbox ...
Toggle all Angular checkboxes in a group
JS
I have the following input : And I want to achieve the following output : I am using jquery and it has a .unwrap ( ) function , but if I go $ ( '.highlight ' ) .unwrap ( ) it removes < p > . : ( Manually hacking the DOM seems like a hassle . Do you know any short solution ?
< p > < span class= '' highlight '' > Some text < b > that can have formatted components too < /b > . < /span > And some more text here of course. < /p > < p > Some text < b > that can have formatted components too < /b > . And some more text here of course. < /p >
How to remove a span in-place ?
JS
x now seems to be an infinitely deep russian-doll type meta array.if you check x [ 0 ] [ 0 ] [ 0 ] ... . as many [ 0 ] indexes as you add , it still returns a one-item array.but is there a finite depth cutoff ? or are new levels procedurally generated when you check ? those are the only two possibilities I can think of...
var x = [ ] ; x.push ( x ) ;
in javascript , what happens if : x = [ ] ; x.push ( x ) ; ?
JS
Consider this situation.What value will x be ? I tried to print it and it showed me undefined . It is intuitive , but is it always so ? Is it in docs ? Second questionWhat should we return from the function that we put into a promise ? Is this value ignored ?
new Promise ( function ( resolve , reject ) { var x = resolve ( 2 ) ; } ) ; new Promise ( function ( resolve , reject ) { resolve ( 2 ) ; return 5 ; } ) ;
Return value of Promise 's resolve/reject functions
JS
i 'm trying to implement a 301 redirect when visiting my `` www '' url to reroute to `` non-www '' . the redirect works on localhost and the project builds fine . when i try to deploy with mup , i get this error : here is the offending code . mup works fine when i remove it.this codes lives in /lib/_reroute-non-www.jsw...
x Invoking deployment process : FAILED -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -STDERR -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - : callback ’ will be initialized after [ -Wreorder ] v8 : :Handle < v8 : :Function > callback ; ^ ../src/heap_output_stream.h:26:29 : warning : ‘ v8 : :Handle < v8 : :Va...
mup deploy errors when using webapp.connecthandlers
JS
I am building a public facing website and I am using a lot of jQuery and jQueryUI . What I have noticed is that most site on internet that use jQuery and jQueryUI do n't have code like this in their pages.I know this is a simplistic example but most sites , for example SO have only one obfuscated js file included for a...
< script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( `` a '' ) .click ( function ( event ) { alert ( `` Thanks for visiting ! `` ) ; } ) ; $ ( `` input : submit '' ) .button ( ) ; } ) ; < /script >
How to Include JavaScript on a Public Facing Website ?
JS
Now , I have three checkbox and only can have one checked at the moment.Also , there is a gray color area will show out when `` Item2 '' was checked.When I check item2 first ( the gray area show ) then check item1 or item3 , the item2 will un-check but the gray color area still show out.How to not show gray area when i...
$ ( document ) .ready ( function ( ) { $ ( `` .registration_info input '' ) .click ( function ( ) { if ( $ ( this ) .prop ( `` checked '' ) ) { $ ( `` .registration_info input : checkbox '' ) .prop ( `` checked '' , false ) ; $ ( this ) .prop ( `` checked '' , true ) ; } } ) ; } ) ; // -- -- -- -- dealer area -- -- -- ...
How to not showing div area when specific checkbox button is not checked ?
JS
I 'm trying to build a web app but I 've encountered a problem . Most of the app 's interfaces consist of lots of buttons and I 've encountered a queer phenomenon whereby I ca n't click some of the buttons ( there 's no clicking animation and the onclick ( ) does n't run ) . I 've noticed that where there are multiple ...
< html > < body > < div style= '' padding-top : 20 % ; '' id= '' div1 '' > < button > Button 1 < /button > < br / > < button > Button 2 < /button > < /div > < script > document.getElementById ( `` div1 '' ) .style.display = `` initial '' ; < /script > < /body > < /html >
Button weirdly not clickable
JS
I have seen on various websites how developers version their css/javascripts files by specifying querystrings similar to : How is that done ? Is it a good practice ? I 've been searching around but apparently , I 'm not looking for the right terms . If it matters , I 'm using ASP.NET.Edit : : I just noticed ( via Fireb...
< head > < link rel= '' stylesheet '' href= '' css/style.css ? v=1 '' > < script src= '' js/helper.js ? v=1 '' > < /head >
How to version files in the < HEAD > section ?
JS
I need to write a function that converts array elements within an array into objects . Although I 've figured out a way to solve the problem by using for-loop , I 'm just wondering if there 's more concise way to write up the solution by using methods such as forEach or map.The problem is ... I need to convert the abov...
var array : [ [ [ 'firstName ' , 'Joe ' ] , [ 'lastName ' , 'Blow ' ] , [ 'age ' , 42 ] , [ 'role ' , 'clerk ' ] ] , [ [ 'firstName ' , 'Mary ' ] , [ 'lastName ' , 'Jenkins ' ] , [ 'age ' , 36 ] , [ 'role ' , 'manager ' ] ] ] ; [ { firstName : 'Joe ' , lastName : 'Blow ' , age : 42 , role : 'clerk ' } , { firstName : '...
Is there a way to solve this problem by using .forEach or .map instead of for-loop ?