lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | Hey I am using highcharts as my basic graph library.I would like to add points dynamically to a graph , according to highcharts API documentation , I should use the addPoint method.I have tried to use this method , but in every try , the graph always added the point to the end of the series and not to the middle of the... | $ ( function ( ) { $ ( ' # container ' ) .highcharts ( { series : [ { data : [ 29.9 , 71.5 , 106.4 , 129.2 , 144.0 , 176.0 , 135.6 , 148.5 , 216.4 , 194.1 , 95.6 , 54.4 ] } ] } ) ; // the button action var i = 0 ; $ ( ' # button ' ) .click ( function ( ) { var chart = $ ( ' # container ' ) .highcharts ( ) ; chart.serie... | append point in the middle of graph |
JS | Is there any way to access the target object 's length property when using the forEach loop over an unnamed array ? | # I 'd like to be able to do something like : [ 1 , 2 , 3 ] .forEach ( n , i ) - > console.log n is < ( arr.length - 1 ) | Access to unnamed array in Array.forEach |
JS | I 'm going through a JavaScript tutorial and I 'm able to complete it . But the problem is that I do n't understand what one of the lines is doing . I have a function setAge ( ) and then later after creating a susan object I set one of the properties to that object as the name of the function ? I do n't understand why ... | var setAge = function ( newAge ) { this.age = newAge ; } ; var susan = new Object ( ) ; susan.age = 25 ; susan.setAge = setAge ; //how the hell does this work ? // here , update Susan 's age to 35 using the methodsusan.setAge ( 35 ) ; | Noob Concern : JavaScript function usage |
JS | See this code : The first script attempts to let-declare foo via a destructuring assignment . However , null ca n't be destructured , so the assignment throws a TypeError.The problem is that then the foo variable is declared but uninitialized , so if in the 2nd script I attempt to reference foo , it throws : And let va... | < script > let { foo } = null ; // TypeError < /script > < script > // Here I want to assign some some value to foo < /script > foo = 123 ; // ReferenceError : ca n't access lexical declaration ` foo ' before initialization let foo = 123 ; // SyntaxError : redeclaration of let foo | Take let variable out of temporal dead zone |
JS | As we all know , since jQuery 1.7 : has become , essentially : All live events are n't directly bound to the elements in the selector , but delegate bound to the document.This , I assume , is because elements that would match 'someSelector ' in the future , are n't present in the DOM , so ca n't have event handlers bou... | $ ( 'someSelector ' ) .live ( 'click ' , fn ( ) ) ; $ ( document ) .on ( 'click ' , 'someSelector ' , fn ( ) ) ; | Upgrading from .live ( ) to .on ( ) for single page applications |
JS | My HTML is : The output of this code is : If I double click the word , it 's selecting the complete word , like this : But I want to select the letters based on the INS tag data-idEx : - if I double click the 111 I want to select only 111 like this : How to modify the default double click selection to JavaScript select... | < p > < ins data-id= '' 1 '' > 111 < /ins > < ins data-id= '' 2 '' > 222 < /ins > < /p > var containerid = $ ( e.currentTarget ) ; if ( window.getSelection ) { var range = document.createRange ( ) ; range.selectNode ( containerid ) ; var sel = window.getSelection ( ) sel.removeAllRanges ( ) ; sel.addRange ( range ) ; } | Double click word JavaScript window.getSelection in two INS tag |
JS | I am running qunit Test using html file in one file and that html file i am running from phantom js.When I am running html file through browser i am getting output in console but when i am trying to run using phantom js i am not getting the console output in another js file from where i am calling html file.I am provid... | < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > JUnit reporter for QUnit < /title > < link rel= '' stylesheet '' href= '' qunit.css '' > < script src= '' qunit.js '' > < /script > < script > QUnit.config.reorder = false ; < /script > < script src= '' qunit-reporter-junit.js '' > < /script >... | How to take the console output of html file into phantomjs |
JS | Why does it delegate to old prototype of a.x and not the newerone ? Why is a.y throwing undefined through it is set in prototype ? | function A ( ) { } A.prototype.x = 10 ; var a = new A ( ) ; alert ( a.x ) ; // 10A.prototype = { x : 20 , y : 30 } ; alert ( a.y ) // undefined | why is a.y undefined here ? |
JS | Q : Mentally , how do you read these two statements ? | myObj.FirstName = 'Phillip ' , myObj.LastName = 'Senn ' ; for ( var X in myObj ) // FirstName LastNamefor each ( var X in myObj ) // Phillip Senn | What does each mean in JavaScript ? |
JS | Consider this HTML template with two flat x-elements and one nested.How to initialise ( fire constructor ) all custom elements in cloned from fooTemplate document fragment without appending it to DOM , neither by extending built-in elements with is= '' x-element '' ; either entire fragment.Note that script executes wit... | < template id= '' fooTemplate '' > < x-element > Enter your text node here. < /x-element > < x-element > < x-element > Hello , World ? < /x-element > < /x-element > < /template > class XElement extends HTMLElement { constructor ( ) { super ( ) ; } foo ( ) { console.log ( this ) ; } } customElements.define ( ' x-element... | Initialisation of Custom Elements Inside Document Fragment |
JS | The testMyNumber function seems to think numbers in the second position do not match.Why do 4 and 10 return the default case ? Is there a way to make this work ? | function testMyNumber ( number ) { switch ( number ) { case 6 : return number+ '' is 6 '' ; break ; case ( 3 || 4 ) : return number+ '' is 3 or 4 '' ; break ; case 9 || 10 : return number+ '' is 9 or 10 '' ; break ; default : return number+ '' is not in 3,4,6,9,10 '' ; break ; } } ; console.log ( testMyNumber ( 6 ) ) ;... | Why does the logical OR operator in switch cases behave strangely ? |
JS | I am trying to save a string to an external file using JavaScript . Below is what I am executing.This code works perfectly using Chrome . However with Firefox , it stops just prior to the `` # '' . When I look at the resulting output file I see the following : Results in Chrome look like this 1111 # 1111 Results in Fir... | var mytext = `` 1111 # 1111 '' var a = document.body.appendChild ( document.createElement ( `` a '' ) ) ; a.download = `` My_output.html '' ; a.href = `` data : text/html , '' + mytext ; a.click ( ) ; | Hashtag within string breaks JavaScript |
JS | I am working on an Angular application using PrimeNG Full Calendar component , this one : https : //primefaces.org/primeng/showcase/ # /fullcalendarThat is based on the Angular FullCalendar component , this one : https : //fullcalendar.io/Here you can find my entire code : https : //bitbucket.org/dgs_poste_team/soc_cal... | import { Component , OnInit , ViewChild , ElementRef } from ' @ angular/core ' ; import { EventService } from '../event.service ' ; import dayGridPlugin from ' @ fullcalendar/daygrid ' ; import timeGridPlugin from ' @ fullcalendar/timegrid ' ; import listPlugin from ' @ fullcalendar/list ' ; import interactionPlugin , ... | Why am I obtaining this strange behavior trying to use different color for different event type dragged into a PrimeNG FullCalendar component ? |
JS | Should I always be using instanceof and typeof to check types egor is it acceptable to leave out the instanceof and trust that the argument is valid ? I wonder because this is the only weakly typed language I have used , so I am slightly uncomfortable with not always knowing the type of the object being acted upon . | addRow : function ( rowBefore ) { if ( rowBefore instanceof Y.PopulateList.makeRow ) { this.allRows [ row.toString ( ) ] = row ; row.altered = true ; Y.DragAndDrop.addNewDrag ( row.rowDiv ) ; node.insert ( row.rowDiv , 'after ' ) ; } else { console.log ( 'not adding a makeRow ' ) ; } } , | In JavaScript , how much trust should I have that function arguments are of the correct type ? |
JS | This code best demonstrates my confusion.Whoa , wait , what 's going on ? 1.Why am I getting different results ? I only used 1 selector and am referencing one element.2.Why are n't the object reference jWrapped and the object from $ ( ' # tableTab ' ) producing the same result ? 3.Furthermore jWrapped and jWrapped [ 0 ... | var nativeObj , jWrapped , jSelector ; //WIAT = `` What I Am Thinking '' nativeObj = $ ( ' # tableTab ' ) [ 0 ] ; //WIAT : unwrap the jQuery object created by the selector and get the native DOM objectjWrapped = $ ( nativeObj ) ; //WIAT : wrap up the native DOM object again ... should be equal to $ ( ' # tableTab ' ) j... | Why is jQuery 's .data method behaving like this ? ( Possible bug ? ) |
JS | I have a form , which has many image urls - the back-end persists url strings and the images are uploaded directly to S3 . I 'd like to use Bacon.js streams to handle disabling/enabling the form 's submit button while uploads are in-progress.I 've tried various approaches ( using a stream of streams of Bacon.fromPromis... | function toResultStream ( promise ) { return Bacon.fromPromise ( promise ) } var deferreds = $ ( ' a ' ) .asEventStream ( 'click ' , function ( event ) { event.preventDefault ( ) ; var deferred = $ .Deferred ( ) ; // simulate upload setTimeout ( function ( ) { deferred.resolve ( true ) ; } , _.random ( 200 , 1600 ) ) s... | Using Bacon.js to disable submit button while deferreds are `` pending '' |
JS | Consider that I create some custom elements with HTML5There are many type of juice elements . And I want to select them with a single instruction with jQuery using their suffix . I try that but it does not work : If i take them one by one this work.But there are many of these custom element suffixed by juice . How can ... | < orange-juice > ... < /orange-juice > < apple-juice > ... < /apple-juice > < banana-juice > ... < /banana-juice > $ ( ' $ =juice ' ) .html ( 'juice ' ) ; //the .html instruction is not important $ ( 'orange-juice ' ) .html ( 'juice ' ) ; //this work $ ( 'apple-juice ' ) .html ( 'juice ' ) ; //this work $ ( 'banana-jui... | JQuery - Select custom elements by suffix or prefix of their tagName |
JS | http : //jsfiddle.net/nicktheandroid/6BAfH/1/The list-elements are sorted accordingly by the number in their span . Why is it that the last few numbers are out of order ? I 'm confused.JqueryHTML | function sortEm ( a , b ) { return parseInt ( $ ( 'span ' , a ) .text ( ) ) < parseInt ( $ ( 'span ' , b ) .text ( ) ) ? 1 : -1 ; } $ ( 'li ' ) .sort ( sortEm ) .prependTo ( $ ( 'ul # test ' ) ) ; < ul id= '' test '' > < li > Cups < span > 12 < /span > < /li > < li > Plates < span > 18 < /span > < /li > < li > Forks < ... | Simple sorting by number script , 3 lines , does n't sort last few li 's correctly , why ? |
JS | I am trying to use esbuild to bundle and minify my files in an npm project . It is minimizing every file that I pass in , but it is not bundling . It gives me the error that I must use 'outdir ' when there are multiple files . However , this gives me back all of those files , minimized , in a folder . This is not the b... | let { build } = require ( `` esbuild '' ) ; let files = [ `` file1.js '' , `` file2.js '' ] ; build ( { entryPoints : files , outdir : `` ./views/dashboardPage/bundle '' , minify : true , bundle : true } ) .catch ( ( ) = > process.exit ( 1 ) ) ; | esbuild not bundling files |
JS | Is the following function legal and portable ? Sometimes I want to write a callback that does n't use the leftmost parameters so I wonder what is the most concise way to do so.Conclusion : function ( _1 , _2 , x ) is probably as short as it gets then . | function ( _ , _ , x ) { return x ; } | Am I allowed to repeat function parameter names in Javascript ? |
JS | I am implementing a function that compares two JavaScript objects for `` deep '' equality . The skeleton of this function , right now , looks like this : The question is what to put where it says // ? ? ? cyclic reference detected . Ideally , I would like to be able to say that these objects are deep-equal : and these ... | function check_equal ( actual , expected ) { var stack = [ ] ; function check_equal_r ( act , exp ) { if ( is_scalar ( act ) || is_scalar ( exp ) ) { assert ( act === exp ) ; } else if ( stack.indexOf ( act ) == -1 ) { assert ( have_all_the_same_properties ( act , exp ) ) ; stack.push ( act ) ; for ( var k of Object.ge... | Detect whether cyclic reference in object A is structurally the same as cyclic reference in object B |
JS | I have an array of objects similar to the following : These objects represent the start and end point of lines and as such , { start : 1 , end : 2 } and { start : 2 , end : 1 } represent the same line.I am trying to remove all duplicate lines from the array and can not find an efficient or elegant way to do it . I have... | var routeArr = [ { start : 1 , end : 2 } , { start : 1 , end : 3 } , { start : 1 , end : 4 } , { start : 2 , end : 1 } , { start : 3 , end : 1 } , { start : 4 , end : 1 } ] ; for ( var i = 0 , numRoutes = routeArr.length ; i < numRoutes ; i++ ) { var primaryRoute = routeArr [ i ] ; for ( var j = 0 ; j < numRoutes ; j++... | Removing equivalent but unique objects from a Javascript array |
JS | I 'm working with MomentTimezone for time manipulation in the browser.I am using TypeScript and Lodash too.I have some accountTimezone set on the window containing the authenticated user 's preferred timezone . I am trying to create a helper method localMoment ( ) that will accept any of the many signatures of moment.t... | const localMoment = partialRight ( moment.tz , window.accountTimezone ) ; const localMoment = ( ... args ) : Moment = > moment.tz ( ... args , window.accountTimezone ) ; | Working around unset `` length '' property on partial functions created with lodash 's partialRight |
JS | From a question asked over here about replacing ordinary text within a string into a URL ... . I want to make it work if the link text is surrounded by < br/ > tags . This is the code I am using so far which does 'linkify ' text within an element that appears to be a hyperlink : Of course the problem is that if the lin... | function linkify ( inputText ) { var replacedText , replacePattern1 , replacePattern2 , replacePattern3 ; //URLs starting with http : // , https : // , or ftp : // replacePattern1 = / ( \b ( https ? |ftp ) : \/\/ [ -A-Z0-9+ & @ # \/ % ? =~_| ! : , . ; ] * [ -A-Z0-9+ & @ # \/ % =~_| ] ) /gim ; replacedText = inputText.r... | How to make this string replacement code work with ` < br/ > ` tags ? |
JS | This Javascript MD5 implementation has me confused.In the global space , the author declares a var : Later on , the following method appears : The line that I do n't understand is : What is the author trying to accomplish here ? | var hexcase = 0 ; function rstr2hex ( input ) { try { hexcase } catch ( e ) { hexcase=0 ; } var hex_tab = hexcase ? `` 0123456789ABCDEF '' : `` 0123456789abcdef '' ; var output = `` '' ; var x ; for ( var i = 0 ; i < input.length ; i++ ) { x = input.charCodeAt ( i ) ; output += hex_tab.charAt ( ( x > > > 4 ) & 0x0F ) +... | Unclear Javascript snippet |
JS | I know that to find if a variable is undeclared in javascript , I can use if ( typeof variable === 'undefined ' ) . If I declare a variable as undefined ( var variable = undefined ) , the if statement still returns true . Is it possible , in JavaScript , to find the difference between undeclared variables and variables... | const variable = undefinedif ( typeof variable === 'undefined ' ) { console.log ( ' '' variable '' is undefined ' ) } if ( typeof undeclaredVariable === 'undefined ' ) { console.log ( ' '' undeclaredVariable '' is undefined ' ) } | How to check if a variable is undefined versus it is undeclared in javascript ? |
JS | I was looking for some micro optimizations of some JavaScript legacy code I was revisiting and noticed that in most frequently called for loops , counters were declared once in the global scope , outside the functions using them . I was curious whether that was indeed an optimization therefore I have created the follow... | var tmp = 0 ; function test ( ) { let j = 0 ; function letItBe ( ) { for ( j = 0 ; j < 1000 ; j++ ) { tmp = Math.pow ( j , 2 ) ; } } function letItNotBe ( ) { for ( let l = 0 ; l < 1000 ; l++ ) { tmp = Math.pow ( l , 2 ) ; } } console.time ( `` let it be '' ) ; for ( var i =0 ; i < 10000 ; i++ ) { letItBe ( ) ; } conso... | Why does declaring a counter variable outside of a nested function make a loop 5x slower ? |
JS | I try to add the < style type= '' text/css '' > < /style > to head using jquery.I tried like thisPreviously , i have this type of That above style worked when I tried this with jquery like this : but i get error in editor itself . Here is the picI think i messup something : ( http : //jsfiddle.net/jSvUE/Any suggestion ... | $ ( `` < style type='text/css ' > < /style > '' ) .appendTo ( `` head '' ) ; < style type= '' text/css '' > img { -moz-animation : .6s rotateRight infinite linear ; -webkit-animation : .6s rotateRight infinite linear ; } @ -moz-keyframes rotateRight { 0 % { -moz-transform : rotate ( 0deg ) ; -moz-transform-origin:50 % ... | Integrate style tag using css |
JS | I am developing a PhoneGap + Parse application.I have a login page and a logout button . I call the following code on logout button click.I get the following message in my browser console . What does this mean ? What should be corrected for the logout functionality to work properly ? | $ ( ' # signout ' ) .click ( function ( event ) { $ ( `` : mobile-pagecontainer '' ) .pagecontainer ( `` change '' , `` # signin '' , { reload : true , transition : 'flow ' , changeHash : true } ) ; Parse.User.logOut ( ) ; console.log ( 'logged out ' ) ; } ) ; POST http : //192.168.2.2:3000/proxy/https % 3A % 2F % 2Fap... | PhoneGap Parse JS logout function returns 404 |
JS | I have three select tags with values in it . If I select Unlimited in one of the values I want the rest of the two select tags to auto-switch to the same value ( Unlimited ) and gets disabled.If I select the option Unlimited from the first select tag the second and thirds value should switch to Unlimited and inputs sho... | < script src= '' //stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js '' > < /script > < script src= '' //cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js '' > < /script > < link rel= '' stylesheet '' href= '' //stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css '' > < div cla... | How to disable multiple select tag when selecting one ? |
JS | Goal : I 'm looking for a way in javaScript/jQuery to size a textarea so that it initially shows all of its text content , hide the vertical scrollbar , and show the resize handle.The code that is below , first shows the textarea with some content , but not enough that the vertical scrollbar appears . This would be fin... | const text = 'This is a line of text ' ; var $ textarea = $ ( ' # example ' ) ; var i = 0 ; $ textarea.val ( $ textarea.val ( ) + text ) ; for ( var l = i + 5 ; i < l ; ++i ) $ textarea.val ( $ textarea.val ( ) + `` \r\n '' + text + ' ( ' + i + ' ) ' ) ; function doIt ( This ) { if ( This.innerText ! == 'Click Me Again... | How can I auto fit/resize a html5 textarea element to fit the initial content ? |
JS | Below is a code that adds the amount if the CategoryId is the same and creates a new line item per CategoryId . Which would result in the array below : But I want to add a new condition which is Type , How do I get the results below ? I could not find a solution on the linked question . | self.OriginalLineItems = [ { CategoryId : 'Cat1 ' , Amount : 15 , Type : 'TypeA ' } , { CategoryId : 'Cat1 ' , Amount : 30 , Type : 'TypeA ' } , { CategoryId : 'Cat1 ' , Amount : 20 , Type : 'TypeB ' } , { CategoryId : 'Cat2 ' , Amount : 10 , Type : 'TypeA ' } , { CategoryId : 'Cat2 ' , Amount : 5 , Type : 'TypeB ' } ]... | Sum of Javascript value if two conditions are met |
JS | I have a few dynamic pages and I want to alter certain elements before the page has fully rendered.My snippet is something likeI do not have access to change the content server side.Where is the best place to put the snippet to have the code run before the page it has rendered ? Rather , is putting the javascript in ei... | document.body.getElementById ( `` change '' ) .innerHTML = `` < img src ... '' ; | where is the best place to place a javascript snippet to alter the DOM of a page before it renders |
JS | I am using ColorPicker Plugin . I initialized the plugin with following code : Now my problem is that $ ( this ) is not working in onchange event . Help me out please ? | $ ( `` .colorpic '' ) .ColorPicker ( { color : ' # 0000ff ' , onShow : function ( colpkr ) { $ ( colpkr ) .fadeIn ( 500 ) ; return false ; } , onHide : function ( colpkr ) { $ ( colpkr ) .fadeOut ( 500 ) ; return false ; } , onChange : function ( hsb , hex , rgb ) { $ ( this ) .css ( 'backgroundColor ' , ' # ' + hex ) ... | $ ( this ) is not working |
JS | At the top of my functional component , these values are set which are not used only in styles , and that 's what 's bothering me : I use some of those variables in my styles ... I would like to move my styles to another file which would hold this styling and would be related with some class name for example '.divWrapp... | const testWidth = 100 ; const testHeight = 100 ; < divstyle= { { borderBottom : 0 , width : ` $ { testWidth } px ` , width : 'auto ' , paddingRight : 0 , paddingLeft : 0 , paddingTop : 20 , } } > .wrapper { borderBottom : 0 , paddingRight : 0 , paddingLeft : 0 , paddingTop : 20 , } < div className= '' wrapper > | React - How to avoid this kind of inline styling |
JS | I am storing the following data attribute for select elements for loading the options.My questions is what is the best way when need to store many data attributes for a single DOM element ? Is it better to have single data attribute having the JSON data or having separate data attributes for each value needed . | < select name= '' DependsOn_Field '' data-load='automatic ' data-source='web.module ( ) .fields ' data-value='name ' data-display='label ' data-filter='exclude_single ' id='DependantField ' > < /select > | Is storing JSON in data attriibute recommended over having seperate data attributes ? |
JS | I have a div with 10 HTML elements . How could I get the reference of all these 10 elements and toggle a class on them on click ? SCSS : I can do this very easily by using jQuery as follows : What is the angular way of doing it ? I tried using the @ ViewChild and access the parent div but I was unable to add the class ... | < div > < some-element class= '' hawk '' > < /some-element > < some-element class= '' hawk '' > < /some-element > < some-element class= '' hawk '' > < /some-element > < some-element class= '' hawk '' > < /some-element > < some-element class= '' hawk '' > < /some-element > ... < /div > < div class= '' trigger '' ( click... | How to get the reference of all elements in a div in Angular 2 ? |
JS | addGeoJson is not working in google map for my file please check below code that I am using in javascriptI have downloaded this file from hereyou can check my JSON file Sensitive_Areas_Nitrates_Rivers.jsonalso , you can check this link with polygonI have used below JSON format so you can check it { `` type '' : `` Feat... | //create the mapmap = new google.maps.Map ( document.getElementById ( 'map-canvas ' ) , { zoom : 6 , center : { lat:49.79 , lng : -8.82 } } ) ; // Load GeoJSON.var promise = $ .getJSON ( `` Sensitive_Areas_Nitrates_Rivers.json '' ) ; //same as map.data.loadGeoJson ( ) ; promise.then ( function ( data ) { cachedGeoJson ... | Google Maps - addGeoJson is not working for my file |
JS | So as I was reading about ~ , Performs the NOT operator on each bit . So I tried : But when I tried , it returns -1 . Is n't 11111111111111111111111111111111 is 4294967295 in decimal ? | 0 = 00000000000000000000000000000000 so ~0 should be~0 = 11111111111111111111111111111111 | Why does ~0 is -1 ? |
JS | I found this cool way of using the Array.prototype.filter method to remove all non-numbers from a string , but am not entirely sure how it 's using the Number prototype to achieve this : When I check typeof Number I get back 'function ' . What is going on here ? Adding further to my confusion is that if I replace Numbe... | var arr = '75number9 ' ; arr.split ( / [ ^\d ] / ) .filter ( Number ) ; // returns [ 75 , 9 ] arr.split ( / [ ^\d ] / ) .filter ( String ) ; // returns [ 75 , 9 ] [ `` 75 '' , `` '' , `` '' , `` '' , `` '' , `` '' , `` 9 '' ] | How does 'Number ' in Array.prototype.filter ( Number ) work ? |
JS | This is about a classifieds website ... I use PHP and MySql to insert records into a db.I have a HTML form , and users must fill in this form to proceed.Below is the form inputs and the validation made on each input ( javascript ) : Name ( Only letters allowed ) Tel ( Only numbers allowed ) Email ( Special email-regexp... | var alphaExp = /^ [ a-zA-ZåäöÅÄÖ\s\- ] + $ / ; var numExp = /^ ( ? = ( ? : \D*\d ) { 0 } ) [ \d - ] { 0,20 } $ / ; var num_only = /^ [ 0-9 ] + $ / ; var emailExp = /^ [ \w\-\.\+ ] +\ @ [ a-zA-Z0-9\.\- ] +\ . [ a-zA-z0-9 ] { 2,4 } $ / ; var textExp = /^\s* ( [ \wåäö\-\* ] [ ^\w ] * ) { 3 } . * $ /gmi ; var headlineExp =... | Do I need to check for sql injection even on validated inputs ? |
JS | Say I 'm making a Tab + Panel component called TabsPanels . I want to ensure that I 'm getting the same number of Tab and Panel components , like so : Is there any way to do this ? If there was some utility function likeThat 's obviously bad , but you get what I 'm saying . Then you could do | type TabsPanelsProps = { tabs : Tab [ ] ; panels : Panel [ ] ; } < TabsPanels tabs= { [ < Tab/ > , < Tab/ > ] } panels= { [ < Panel/ > ] } // Error : tabs.length and panels.length do not match/ > PropsAreEqual < T , K1 , K2 , P > whereT = typeK1 = key 1K2 = key 2P = the property to be equal PropsAreEqual < TabsPanelsPr... | TypeScript : Require that two arrays be the same length ? |
JS | I am working on BitWise AND operator in javascript.I have two 32 bit nunber when I and them bitwise 4294901760 & 4294967040 I got -65536 as a result although the result should be 4294901760.Can any one please guide me am I missing something ? Or what is the correct way to do it.Thanks | 4294901760 ( 11111111 11111111 00000000 00000000 ) and4294967040 ( 11111111 11111111 11111111 00000000 ) | Bitwise & in javascript not returning the expected result |
JS | This a little thing that i started at work two days ago thinking it would be a quick little brain problem then ill get back to eating my lunch . However im struggling . I want to get an array of all valid hexadecimal color codes . Without crashing the browser preferably.This is what i came up with so far.Bare in mind i... | app.directive 'randomColor ' , ( ) - > link : ( scope ) - > scope.colors = new Array col = 0x0 while col < = 0xFFF if ( col > 0x111 & & col < 0xFFF ) scope.colors.push ' # ' + col col++ autocolor = ( hexcode ) - > colorChange = ( ) - > $ ( `` # colorvomit '' ) .append ( `` < span style='padding : 1px 10px 1px 10px ; ba... | How to get every valid hex code in javascript |
JS | I would like to post on my Wordpress blog using API.Since I 'm in a Javascript application I would do that using this language.I have made some searches and I have found node-wpapi package , that uses Wordpress XML-RPC protocol . Everything works , except posting article with media or featured image.It does create post... | const responseUploadImage = await wp.media ( ) .file ( './tempImage.jpg ' ) .create ( { title : 'My awesome image ' , alt_text : 'an image of something awesome ' , caption : 'This is the caption text ' , description : 'More explanatory information ' } ) ; const responsePostCreation = await wp.posts ( ) .create ( { titl... | Adding posts with media using Wordpress API and Javascript library |
JS | I have two objects like this : I need to merge them inside a single array like thisI have tried using lodash union and map but no luck . | let obj1 = { slotIDs : [ `` 5e0301f353ee2a0546298f15 '' ] } let obj2 = { slotIDs : [ `` 5e0301f353ee2a0546298f15 '' , `` 5e03050453ee2a0546298f1c '' ] } let newObj = [ `` 5e0301f353ee2a0546298f15 '' , `` 5e03050453ee2a0546298f1c '' ] | How to merge two arrays which are inside individual objects as property |
JS | I am creating a calendar with events using reactjs , Now when the calendar shows the current month , when I click next its shows the April month if I click again next I get the following error . TypeError : Can not read property 'eventSlots ' of undefined.The error appears in a function where I try to get days with the... | getDaysWithEvents ( ) { // Get all the days in this months calendar view // Sibling Months included const days = this.getCalendarDays ( ) ; // Set Range Limits on calendar this.calendar.setStartDate ( days [ 0 ] ) ; this.calendar.setEndDate ( days [ days.length - 1 ] ) ; // Iterate over each of the supplied events this... | Reactjs : TypeError : Can not read property 'eventSlots ' of undefined |
JS | I stumbled upon this block of code and do n't really see the need for returning a function when the outer function does n't take any arguments ? Am I missing something or can it be rewritten as : | var percent = ( function ( ) { var fmt = d3.format ( `` .2f '' ) ; return function ( n ) { return fmt ( n ) + `` % '' ; } ; } ) ( ) var percent = function ( n ) { return d3.format ( `` .2f '' ) ( n ) + `` % '' ; } | What value does this Javascript function factory add ? |
JS | Why does ( unexpectedly ) return instead ofThe non-greedy operator seems to be doing nothing ... | / < .+ ? > e/.exec ( `` a < b > c < d > e '' ) [ `` < b > c < d > e '' ] [ `` < d > e '' ] | unexpected non-greedy JS regular expression result |
JS | If the arguments is just an object with a length property , then why does it seem to behave differently from other non-array objects with respect to , say , Array.prototype.slice.For example , the following code first alerts `` undefined '' , and then alerts `` foo '' . Why do these differ ? | ( function ( a ) { var myobj = { 0 : `` foo '' } ; var myobjarray = Array.prototype.slice.call ( myobj ) ; var argumentsarray = Array.prototype.slice.call ( arguments ) ; alert ( myobjarray.shift ( ) ) ; alert ( argumentsarray.shift ( ) ) ; } ) ( `` foo '' ) ; | Given that `` arguments '' is not a true array , why does Array.prototype.slice.call ( arguments ) work , but Array.prototype.slice.call ( someobject ) not work ? |
JS | Let 's say I have a class Test with around 10-20 methods , all of which are chainable.In another method , I have some asynchronous work to do.Since every other method is chainable , I feel like it would be weird for the user if this sole method isn't.Is there a way for me to maintain the chainable theme of my Class ? I... | let test = new Test ( ) ; console.log ( test.something ( ) ) ; // Testconsole.log ( test.asynch ( ) ) ; // undefined since the async code is n't done yetconsole.log ( test.asynch ( ) .something ( ) ) ; // ERROR > My goal is to make this test.asynch ( ( ) = > something ( ) ) test.asynch ( ) .then ( ( ) = > something ( )... | Keep object chainable using async methods |
JS | I have code like this , then I was confused on how to loop the array familyto print each member under person . | function Person ( name , age ) { this.name = name ; this.age = age ; } var family = [ ] ; family [ 0 ] = new Person ( `` alice '' ,40 ) ; family [ 1 ] = new Person ( `` bob '' ,42 ) ; family [ 2 ] = new Person ( `` michelle '' ,8 ) ; family [ 3 ] = new Person ( `` timmy '' ,6 ) ; | Javascript using constructor inside in Array |
JS | I am trying to make a Chrome extension that parses through a website looking for keywords , then replacing those keywords with buttons . However , when I change the text the image path becomes corrupted.Image of current results : | // This is a content script ( isolated environment ) // It will have partial access to the chrome API// TODO // Consider adding a `` run_at '' : `` document_end '' in the manifest ... // do n't want to run before full load// Might also be able to do this via the chrome API console.log ( `` Scraper Running '' ) ; var ke... | Change matching words in a webpage 's text to buttons |
JS | For example , take a look at my simple implementation of a stack : By using this method , I can make sure that no one is able to ( accidentally or intentionally ) manipulate `` private '' fields such as min and head . I can also make use of private functions such as Node ( ) which does n't need to be exposed . I have r... | var MyStack = ( function ( ) { var min ; var head ; // Constructor function MyStack ( ) { this.size = 0 ; } MyStack.prototype.push = function ( val ) { var node = new Node ( val ) ; if ( typeof min === 'undefined ' || val < min ) { min = val ; } ++this.size ; if ( typeof head === 'undefined ' ) { head = node ; } else {... | Is using closures to emulate encapsulation a bad idea ? |
JS | This is kind of a 'best practices ' question , but I still think there may be a correct answer.I have a directive with six configurable options . Should I set up six different attributes on the directive ( like below ) : or , should I pass a configuration object into a single attribute ( like below ) : Is this just pre... | < my-directive my-width= '' 300 '' my-height= '' 300 '' my-status= '' true '' my-foo= '' yes '' my-bar= '' no '' > < /my-directive > < my-directive my-options= '' options '' > < /my-directive > | Should I use a single object or individual values as attributes in an Angular directive ? |
JS | Solved : I 've got the @ EdnilsonMaia answer and adapted it http : //codepen.io/anon/pen/QNGroXI have a layout where there are a chain of users like so : When the user resizes the the window the number of users per line decrease and the chain need to be rearranged increasing the number of lines and decreasing the numbe... | Window -- -- -- -- -- -- -- -- -- -O - O - O - O - O | | |O - O - O - O - O || |O - O - O | -- -- -- -- -- -- -- -- -- O = user- = chain ( icon ) function log ( msg , debug ) { debug = typeof debug ! == 'undefined ' ? debug : true ; if ( debug ) { console.log ( msg ) ; } } $ ( document ) .ready ( function ( ) { $ ( win... | Rearrange chain based on window width |
JS | I have an array of objects that holds each `` actionButton '' id , selector and callbackWhat I 'm trying to do is calling a function with a specific parameter from the array ( the id ) every time a selector is clicked.But this code is not working ; it looks like every time the callback function is called the value of i... | var actionButtons = [ { id : '' 0 '' , selector : '' ._55ln._qhr '' , callback : undefined } , { id : '' 1 '' , selector : '' ._22aq._jhr '' , callback : undefined } , . . . ] ; for ( var i=0 ; i < actionButtons.length ; i++ ) { $ ( document ) .on ( 'click ' , actionButtons [ i ] .selector , function ( ) { makeAction (... | How to pass a specific array element for a callback of event |
JS | I have a < p > tag inside a < div > which I 've set the following properties on : If the < p > tag contains a lot of text then some of it will be cut off.My goal is to detect what the first word not being shown is.For example , in the following scenario : the function would return the word `` explode '' .I know from th... | div { height : 105px ; width : 60px ; overflow : hidden ; } div { height : 105px ; width : 60px ; overflow : hidden ; } < div > < p > People assume I 'm a boiler ready to explode , but I actually have very low blood pressure , which is shocking to people. < /p > < /div > | Detect word the causes overflow |
JS | Possible Duplicate : How do I get jQuery to select elements with a . ( period ) in their ID ? I tried to run the following code : example hereAnd # info-mail.ru as I understood interpreted as id= '' info-mail '' and class= '' ru '' , but I have the following structure : How can I shield `` . '' char in selector stateme... | $ ( ' # info-mail.ru .domain-info ' ) .toggle ( ) ; < div id= '' info-mail.ru '' > < p class= '' domain-info '' > Some cool info Some cool info Some cool info Some cool info < /p > < /div > | How to shield `` . '' char ? |
JS | in chrome 47 and nodejs v0.12new Function ( 'myArg ' , 'return `` my function body '' ; ' ) gives the following results : why is there comments /**/ in the function arguments ? | function anonymous ( myArg /**/ ) { return `` my function body '' } | why new Function ( ) return comments /**/ in arguments ? |
JS | While testing JavaScript ES6 's new template strings ( in Firefox , if it matters ) , I noticed some inconsistencies in their types.I defined a custom function , like this : First , I tested the function `` normally '' , using parentheses around the template string.As expected , this yielded a type of string and Hello ... | function f ( a ) { console.log ( typeof ( a ) ) ; console.log ( a ) ; } f ( ` Hello , World ! ` ) f ` Hello , World ! ` | Inconsistent type for JavaScript ES6 template strings |
JS | I 'm new to functional programming and I 'm trying rewrite some code to make it more functional-ish to grasp the concepts . Just now I 've discovered Array.reduce ( ) function and used it to create an object of arrays of combinations ( I 've used for loop before that ) . However , I 'm not sure about something . Look a... | const sortedCombinations = combinations.reduce ( ( accum , comb ) = > { if ( accum [ comb.strength ] ) { accum [ comb.strength ] .push ( comb ) ; } else { accum [ comb.strength ] = [ comb ] ; } return accum ; } , { } ) ; const sortedCombinations = combinations.reduce ( ( accum , comb ) = > { const tempAccum = Object.as... | Is mutating accumulator in reduce function considered bad practice ? |
JS | I have React class with two main elements . Canvas and video.I get video stream and render it at 30fps to canvas.So far so good.But I faced a problem with mobile Safari . Looks like it keep every Canvas object ever created in memory.After several pictures was taken Safari crashes with `` out of memory '' .I already do ... | class GetImage extends Component { constructor ( ) { super ( ) ; this.constraints = { video : { width : { ideal : 2048 } , height : { ideal : 1080 } , facingMode : { exact : 'environment ' } } } } componentDidMount ( ) { setVideo ( this.video , this.constraints , this.readyToPlayVideo ) } capture = ( ) = > { const { vi... | Mobile safari out of memory during video capturing |
JS | I have made a simple code for capturing a certain group in a string : code : The result were : But wait a minute , Why he didnt try the bbb222ccc part ? I mean , It saw the aaa111bbb but then he should have try the bbb222ccc ... ( That 's greedy ! ) What am I missing ? Alsolooking athow did it progressed to the second ... | / [ a-z ] + ( [ 0-9 ] + ) [ a-z ] +/gi ( n chars , m digts , k chars ) . var myString='aaa111bbb222ccc333ddd ' ; var myRegexp=/ [ a-z ] + ( [ 0-9 ] + ) [ a-z ] +/gi ; var match=myRegexp.exec ( myString ) ; console.log ( match ) while ( match ! = null ) { match = myRegexp.exec ( myString ) ; console.log ( match ) } [ ``... | Regex in Javascript not as greedy as it should ? |
JS | I have made a like button powered by ajax and I have defined a function that it refresh the text . Now I want to change it for updating from font awesome fa-heart-o to fa-heart and viceversa . How can I do it ? see the code belowbase.htmland button like htmlThank you for your help . | < script > $ ( document ) .ready ( function ( ) { function updateText ( btn , newCount , iconClass , verb ) { verb = verb || `` '' ; $ ( btn ) .html ( newCount + ' < i class= '' ' + iconClass + ' '' > < /i > ' + verb ) btn.attr ( `` data-likes '' , newCount ) } $ ( `` .like-btn '' ) .click ( function ( e ) { e.preventD... | Toggle icon on Like with Javascript |
JS | Are there any cases whereis that ever possible in JS ? : ) | x == y //falsex === y //true | Can === hold when == does n't ? |
JS | I want to create a Class and make it available on my controllers . I do n't want to use helpers in this particular case because I 'm planning to create an npm package later with this code . I do n't want to create a package now , because I do n't want my code to be public.I 've tried adding this code inside a file in t... | console.log ( 'Hook executed ! ' ) ; module.exports = class Test { constructor ( ) { console.log ( 'Object created ! ' ) ; } } const test = new Test ( ) ; | Create a Class to be used on controllers |
JS | If you update text input model `` sg.Value '' , checkbox shoud be checked , but model `` sg.AnswerId '' is not set.How to get : Change text input - > Set checkbox model ? Checkbox must become checked and it 's model updated , when i typing in input . | < label > < input type= '' checkbox '' ng-model= '' sg.AnswerId '' ng-true-value= '' ' { { answer.Id } } ' '' ng-checked= '' sg.Value ! = undefined '' > < input type= '' text '' placeholder= '' Your text '' ng-model= '' sg.Value '' > < /label > | Change input - > change checkbox model without click |
JS | what is the fastest way to check for a valid DateTime ? I need to take into account not just that the string cointains year , month , day , hour and minute , but also that the datetime is valid , eg : 2017-02-29 10:00 should be considered not valid because it is 29th in a non leap year.I have an array of string element... | for ( let i = 0 ; i < length ; i++ ) { let el = datetimes [ i ] ; let d = moment.utc ( el , `` YYYYMMDDHHmm '' ) ; d.isValid ( ) ; } | Node.js - What is the fastest way to check if a string represents a valid datetime for a big number of elements ? |
JS | I was having problem when updating my list to ng-repeat in view and $ scope. $ apply came to the rescue . I am concerned about the watchers . Is it a good practice to use $ scope. $ apply ( ) frequently ? Since I am having many views in application which must be updated immediately on button click.PS : Any alternatives... | function onRefreshList ( ) { vm.showLoader = true ; GetDataService.getVotes ( someParams ) .then ( function ( res ) { if ( res ) { vm.showLoader = false ; vm.voteList = res ; //voteList will be updated on click of Refresh list $ scope. $ apply ( ) ; //working fine with this } } ) .catch ( function ( res ) { vm.showLoad... | Is it a good practice to use $ scope. $ apply ( ) frequently ? |
JS | I have an angular ng-repeat like bellow , This will create output like below , But i need to repeat < div class= '' row '' > also which contain two < div class= '' col-md-6 '' in each row.This output needs like Is it possible to do with this usingng-repeat ? | < div class= '' row '' > < div class= '' col-md-6 '' ng-repeat= '' ( index , data ) in mydata '' > < -- my content -- > < /div > < /div > < div class= '' row '' > < div class= '' col-md-6 '' ng-repeat= '' ( index , data ) in mydata '' > < -- my content -- > < /div > < div class= '' col-md-6 '' ng-repeat= '' ( index , d... | Trouble with ng-repeat angular js |
JS | I have the following code.When I run this code then alert ( 5 ) is coming when the page loads . If I writethen the alert only appears when we click on the button . Why does it behave like this ? | < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01 Transitional//EN '' `` http : //www.w3.org/TR/html4/loose.dtd '' > < html > < head > < script type= '' text/javascript '' src= '' jquery-1.4.2.min.js '' > < /script > < script type= '' text/javascript '' > function myFun ( ) { alert ( 5 ) } $ ( document ) .ready ( functi... | Difference between ` .click ( handler ( ) ) ` and ` .click ( handler ) ` |
JS | I 've seen IIFE 's written : as well as : They seem to work the same in any context I 've used them , though in cases I 've been told one way is right and the other is wrong , vice versa . Does anyone have any solid reason or logic as to it being written one order over the other ? Is there some cases where there could ... | ( function ( ) { console.log ( `` do cool stuff '' ) ; } ) ( ) ; ( function ( ) { console.log ( `` do more cool stuff '' ) ; } ( ) ) ; | Immediately Invoked Function Expression : Where to put the parenthesis ? |
JS | I am facing a drop down menu made of ul and li elements : I know two ways of modifying a dropdown menu with Chromeless : andbut because of the structure of the menu with ul and li , I am unable to use these.I also tried to click on the menu and then press the tab key as many times as necessary to select the correct opt... | < ul class= '' o_dropdown_theme_values '' > < li class= '' '' tabindex= '' -1 '' > < label class= '' myclass '' tabindex= '' 0 '' > Category 1 < /label > < /li > < li class= '' '' tabindex= '' -1 '' > < label class= '' myclass '' tabindex= '' 0 '' > Category 2 < /label > < /li > ... < /ul > .evaluate ( ( dropDownValue ... | How to manipulate a dropdown menu made of ul and li elements in Chromeless |
JS | I 'm wondering if I can use $ ( this ) as well as a class selector before running a function on them.So rather than doing ; Do something more like ; Whereas really , the above will select 'this ' within the context of '.closed'Regards , | $ ( this ) .toggleClass ( 'open ' ) ; $ ( '.closed ' ) .toggleClass ( 'open ' ) ; $ ( this , '.closed ' ) .toggleClass ( 'open ' ) ; | Is it possible to select $ ( this ) AND use selectors in jQuery |
JS | This is the tracking code for Google Analytics : You can see that the function is inside parentheses.Why do you think is that ? | var _gaq = _gaq || [ ] ; _gaq.push ( [ `` _setAccount '' , `` UA-256257-21 '' ] ) ; _gaq.push ( [ `` _trackPageview '' ] ) ; ( function ( ) { var ga = document.createElement ( `` script '' ) ; ga.type = `` text/javascript '' ; ga.async = true ; ga.src = ( `` https : '' == document.location.protocol ? `` https : //ssl '... | What 's the role of the parentheses in the following piece of code ? |
JS | my simple game created with P5.js consists in a ball that falls affected by a gravity force and bounces on the ground . I would like to add a `` compression '' animation to the ball when it touches the ground so that it should look more realistic.How can I do that without making it look weird ? the code is this : | function Ball ( ) { this.diameter = 50 ; this.v_speed = 0 ; this.gravity = 0.2 ; this.starty = height / 2 - 100 ; this.endy = height - this.diameter / 2 ; this.ypos = this.starty ; this.xpos = width / 2 ; this.update = function ( ) { this.v_speed = this.v_speed + this.gravity ; this.ypos = this.ypos + this.v_speed ; if... | How to add a bounce compression animation to a ball in P5 ? |
JS | I have got a bootstrap grid with dynamically generated images.If the last element is alone in the row it should be centered.And if there are two elements in row , the second element should float right.This is what I want : Two elements in row : One element in row : HTML Code : This is what I get : Two elements in row :... | A B DE F GH I A B DE F G H < div class= '' row '' > < div class= '' col-md-4 '' > < img src= '' img.jpg '' / > < /div > < div class= '' col-md-4 '' > < img src= '' img.jpg '' / > < /div > < div class= '' col-md-4 '' > < img src= '' img.jpg '' / > < /div > < div class= '' col-md-4 '' > < img src= '' img.jpg '' / > < /di... | Behaviour of last elements in grid |
JS | I have a simple problem that I just ca n't seem to figure out . In the code below I get an error ( test_str is not defined ) because the line defining `` var str= '' is spread across two lines . After the word `` fox '' there is a CR LF and I guess my javascript engine in my browser thinks I want a new statement there ... | < html > < head > < script > function test_str ( ) { str = `` The quick brown fox jumped over the log . `` ; alert ( str ) ; } < /script > < /head > < body > < a href='javascript : void ( 0 ) ; ' onclick='test_str ( ) ; ' > Test String < /a > < /body > < /html > | Defining a long string with javascript |
JS | Context : I am developing hybrid app with Cordova 6 and SAPUI5 Framework ( for now only need to worry about Android ) .What I want : Copy/move a file to a path fast . Maybe getting a FileEntry from a File/Blob object from a FileUploader on sapui5.Input : FileUploaderOutput : File ObjectSo I get the file when I select i... | sap.ui.getCore ( ) .byId ( 'file-uploader-id ' ) .oFileUpload.files [ 0 ] ; var sPath = URL.createObjectURL ( oFile ) ; var pCopyFrom = new Promise ( ( resolve , reject ) = > { window.resolveLocalFileSystemURL ( sPath , resolve , reject ) ; } ) ; var pCopyTo = new Promise ( ( resolve , reject ) = > { var sExternalCache... | Copy file to a path with Cordova Hybrid app |
JS | For a laugh I have put a Google-esk barrel roll on one of my sites.All works fine on the first click of the selected element , but it wo n't fire again after that.I have tried .click , .on ( 'click ' , function ( ) { } ) and neither work.Any ideas on how to fix and why this is happening ? Basic jsFiddle hereSource code... | < html > < head > < title > Roll Me < /title > < style type= '' text/css '' > < /style > < script > $ ( function ( ) { $ ( ' # roll ' ) .on ( 'click ' , function ( ) { $ ( 'body ' ) .css ( { `` -moz-animation-name '' : `` roll '' , `` -moz-animation-duration '' : `` 4s '' , `` -moz-animation-iteration-count '' : `` 1 '... | Click event lost after css animation |
JS | What I generally need is simple - opensource library with function that will turn given wiki mark up string into html . If you can write such function - please post it here . It shall be tolerant to html objects inserts like YouTube videos , mathml and TeX inside that string ( much alike math.stackexchange ) So is ther... | Header 1========Header 2 -- -- -- -- # Header 1 # # # Header 2 # # # # # # # # Header 6=Header1 ? = = Header1 ? = < iframe src= '' http : //player.vimeo.com/video/20344220 '' width= '' 400 '' height= '' 225 '' frameborder= '' 0 '' > < /iframe > < p > < a href= '' http : //vimeo.com/20344220 '' > Drawing Inspiration < /... | Is there any JavaScript function in some library for turning simple wiki mark up ( given as multi line string ) into html ? |
JS | I found this javascript very strange , when I run on my console browser it gives me an alert with the following message 'Always be wary of Javascript containing quotes . No quotes = safe ! ' I am very curious about it ( really does n't even know if this is a thing , is it useful for something ? ) If any of you would li... | for ( A in { A:0 } ) { alert ( unescape ( escape ( A ) .replace ( /u . { 8 } /g , [ ] ) ) ) } ; | Hidden JavaScript Payload |
JS | I am using the ClipboardJS library to copy text that is attached to a button using the data-clipboard-text attribute . I am also using jQuery 's .load ( ) function to dynamically pull in HTML content . This content includes copies of the Copy text buttons . When the 'fresh ' buttons are loaded using jQuery , the button... | jQuery ( document ) .ready ( function ( e ) { // AJAX .load function for sendout post content e ( `` .sendout-link '' ) .click ( function ( ) { var post_url = e ( this ) .attr ( `` href '' ) ; e ( `` # sendout-container '' ) .html ( ' < div class= '' loading '' > Loading ... < /div > ' ) ; e ( `` # sendout-container ''... | Bind Clipboard JS event to button after using jQuery load/Ajax function |
JS | I came to a code that contains these linesI struggle to understand what is actually going on , and how to use the returning object . If I understand it correctly , data will now be an object that should be initialized like thisBut I do n't understand the following lines and why Object.create ( ) is used instead of the ... | var data = function ( ) { function Metadata ( ) { /*some initialization here*/ } Metadata.prototype = Object.create ( Backend.prototype ) ; Metadata.prototype.constructor = Metadata ; return Metadata ; } var d = new data ( ) Metadata.prototype = Object.create ( Backend.prototype ) ; Metadata.prototype.constructor = Met... | Understanding prototype object creation with 'Object.create ( ) ' instead of 'new ' keyword |
JS | This happens only in Firefox.Important : I am saving the caret 's position with rangy.saveSelection ( ) : when click the content editable divon keyupwhen adding an external html element ( as a node ) to the content editable divI need the position saved constantly through multiple means to be able to insert html element... | < div class= '' input__boolean input__boolean -- no-focus '' > < div @ keydown.enter.prevent @ blur= '' addPlaceholder '' @ keyup= '' saveCursorLocation ( $ event ) ; fixDelete ( ) ; clearHtmlElem ( $ event ) ; '' @ input= '' updateBooleanInput ( $ event ) ; clearHtmlElem ( $ event ) ; '' @ paste= '' pasted '' v-on : c... | Caret disappears in Firefox when saving its position with Rangy |
JS | i try to figure out what the best practice for this situation.2 context : SPORT todos & HOME todos.so 2 action files : and 2 reducer fileshave an official solution for this situation ? i do n't want to repeat my self.the reducer have the same functionality | export const SPORT_ADD_TODO = ` [ SPORT ] ADD TODO ` export const HOME_ADD_TODO = ` [ HOME ] ADD TODO ` homeReducer ( state , action ) { switch ( action.type ) { case HOME_ADD_TODO : return Object.assing ( { } , state , { todos : action.payload } ) default : return state ; } } sportReducer ( state , action ) { ... . } | redux reduce boilerplate for actions and reducer |
JS | I am trying to create a video conference web app using peer/getUserMedia.Currently , when I send the unique ID to the video conference , I am able to hear/see anyone who joins my session.However , only the first person who joins my session can communicate/see me.I want to make it so the other users can see/hear every u... | < html > < body > < h3 id= '' show-peer '' > < /h3 > < div style= '' display : grid ; justify-content : space-around ; margin:10px ; '' > < div style= '' width : 300px ; height : 200px ; transform : scale ( -1 , 1 ) ; border : 2px solid ; display : grid ; margin-bottom : 5 % ; '' id= '' ourVideo '' > < /div > < div sty... | Video/Audio communication |
JS | Intro : I have some legacy code that creates a singleton : And for test purposes I need to generate new instances to inject them as dependeces.Question : Is there any way to generate new instances of the singleton without modifying the original code ? What I 've done : I came with a solution : add the class as a proper... | define ( [ 'backbone ' , 'MyModel ' ] , function ( Backbone , MyModel ) { var MyCollection = Backbone.Collection.extend ( { model : MyModel , initialize : function ( ) { // ... } } ) ; return new MyCollection ( ) ; } ) ; initialize : function ( ) { this.ClassObject = MyCollection ; // ... } var myCollection = require (... | Create new instance from singleton |
JS | I have problems getting the name of the constructor when using ES6 classes in Firefox . In Chromium it works fine , but Firefox seem to have some kind of bug ? In Firefox I only get an empty string back . Anyone that knows of a workaround ? | class MyClass { } let a = new MyClass ( ) ; console.log ( a.constructor.name ) ; | Firefox ES6 , get class constructor name |
JS | could anybody please explain the difference between the following snippets..and I understand we use return function to access variables defined in the parent function and this is a self-executing function but in the first case the first function does nothing but return the other function . I have seen this type of func... | var a = function ( ) { return function ( ) { //some code } } ( ) ; var a = function ( ) { //some code } var session = ( function ( ) { return $ { session } } ) ( ) ; var session = $ { session } ; | Javascript function return value |
JS | I am trying to make a ball move slowly towards my mouse.Im using paper.js which is a simple animation library . Using this i have a ball moving on screen . These are some of the properties of the ball : balls [ 0 ] .vector.angle is its direction . 0 = right , 90 = down , 180 = left etc and everything in betweenballs [ ... | canvas.addEventListener ( `` mousemove '' , function ( e ) { var a = balls [ 0 ] .point.y - e.clientY ; var b = balls [ 0 ] .point.x - e.clientX ; var angleDeg = Math.atan2 ( a , b ) * 180 / Math.PI ; } ) ; var distance = Math.sqrt ( a*a + b*b ) ; var maxSpeed = 20 ; balls [ 0 ] .vector.length = ( distance/30 > maxSpee... | Make a ball on a canvas slowly move towards the mouse |
JS | This code should increment the tag with ID results every 3000 milliseconds instead the while loop is running and returning the final result . For example instead of changing the text to 1 , 2 , 3 , 4 , 5 , ..n , it is changing the text to n. How would one have the loop update the text field every 1000 milliseconds with... | while ( counterInc < counter ) { window.setTimeout ( function ( ) { $ ( ' # results ' ) .text ( counterInc ) ; } , 3000 ) ; counterInc++ ; } | While loop only returning final result |
JS | I need to mock call a function in JavaScript . For this , I 'm `` saving '' the function in a temporary variable , update the target with a new function block , calling the target and then restoring the old function : This works as expected : the function gets overwritten and then successfully restored . My thought was... | var myObject = { myIntProp : 1 , myFunc : function ( value ) { alert ( value + 1 ) ; } } ; myObject.myFunc ( 2 ) ; var tmp = myObject.myFunc ; myObject.myFunc = function ( value ) { alert ( value - 1 ) ; } ; myObject.myFunc ( 2 ) ; myObject.myFunc = tmp ; myObject.myFunc ( 2 ) ; function FunctionSwapper ( target , newF... | Overwrite and restore a function |
JS | When I am running this , it returns NaN . If I do not parseFloat , I 'm getting 2 strings added . What am I missing ? I would say that my result should always be a float ? | function calculate ( i ) { var result = 0.0 ; $ j ( `` .t '' + i + `` input '' ) .each ( function ( ) { var number = $ j ( this ) .val ( ) ; number = number.replace ( `` , '' , `` . `` ) ; if ( parseFloat ( number ) ! = NaN ) { result = parseFloat ( result ) ; number = parseFloat ( number ) ; result += number ; } } ) ;... | Javascript Float + Float = String ? |
JS | One of my friends was taking an online quiz and he asked me this question which I could not answer.If we assume that functions are hoisted at the top along with var variables , let 's try this one.Here is a JSBin Demo and JSBIN Demo2 to play with.PS : If we remove function global ( ) { } from test ( ) , then it runs fi... | var global = false ; function test ( ) { global = true ; return false ; function global ( ) { } } console.log ( global ) ; // says false ( As expected ) test ( ) ; console.log ( global ) ; // says false ( Unexpected : should be true ) var foo = 1 ; function bar ( ) { return foo ; foo = 10 ; function foo ( ) { } var foo... | Scope of variables ( Hoisting ) in Javascript |
JS | I have an if statement that has over 100 different if's.at the minute im using something similar to this ... I want to build one for counties in the uk , so if a user selects 'london ' in the dropdown , the next field is populated with the postcode for london.My problem is however , I could build it as my above example... | $ ( 'select ' ) .on ( `` change '' , function ( ) { if ( $ ( this ) .val ( ) === 'tennis ' ) { $ ( '.sport ' ) .val ( 'raquet ' ) ; } else if ( $ ( this ) .val ( ) === 'soccer ' ) { $ ( '.sport ' ) .val ( 'goal ' ) ; } if ( $ ( this ) .val ( ) === 'snooker ' ) { $ ( '.sport ' ) .val ( 'cue ' ) ; } } ) ; | Managing a massive IF statement in jQuery |
JS | I 'm the author of next-translate library , and I 'm working on an experimental version to which I get an error with React 16.14.0 and I do n't understand why it happens . Upgrading React to version 17 then it works fine , but I do n't want to force everyone who uses the new version of my library to migrate their React... | { `` compilerOptions '' : { `` strict '' : false , `` module '' : `` es6 '' , `` target '' : `` es5 '' , `` jsx '' : `` react '' , `` removeComments '' : true , `` moduleResolution '' : `` node '' , `` esModuleInterop '' : true , `` declaration '' : true , `` lib '' : [ `` esnext '' , `` dom '' ] , `` allowJs '' : true... | React 16.14.0 : Error was not caught ReferenceError : exports is not defined |
JS | Suppose you have function which takes a union type and then narrows the type and delegate to one of two other pure functions.Assume that fnForString ( ) and fnForNumber ( ) are also pure functions , and they have already themselves been tested.How should one go about testing foo ( ) ? Should you treat the fact that it ... | function foo ( arg : string|number ) { if ( typeof arg === 'string ' ) { return fnForString ( arg ) } else { return fnForNumber ( arg ) } } | Testing pure function on union type which delegates to other pure functions |
JS | I want to determine if string has at least 2 same elements from the arrayI 'm not sure what is gon na be better : a regex or a function ? Any would be fine.I tried this : But it only detects if there at least 1 elements from array , not 2 . | const array = [ `` ! `` , `` ? `` ] ; const string1 = `` ! hello '' ; // should return falseconst string2 = `` ! hello ? `` ; // should return falseconst string3 = `` ! hello ! `` ; // should return trueconst string4 = `` hello ? ? `` ; // should return trueconst string5 = `` hello ? test ? foo '' ; // should return tr... | Determine if string has at least 2 same elements from an array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.