lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
JS | How can I convert this string to get 1000000 ? The problem is I always get 10000 : Any suggestions ? | console.log ( parseFloat ( '10.000.000,00'.replace ( ' . ' , ' , ' ) .replace ( / , ( ? = [ ^ , ] * $ ) / , ' . ' ) ) , 'test ' ) ; | Convert float number properly ? |
JS | So i have a form that has custom fields that i add via Field Array from react-hook-form.And everything works but i added drag and drop for the property items ( to reorder them ) and now it would be a big mess to show all these many fields directly so i moved them in a Dialog.Here are the pictures to get the idea what i... | const defaultValues = { name : `` '' , slug : `` '' , description : `` '' , properties : [ ] // field array } function CreateCategoryForm ( ) { const methods = useForm ( { defaultValues } ) ; const { handleSubmit , control , errors } = methods ; const { fields , append , remove , swap } = useFieldArray ( { name : `` pr... | React hook form - Field Array inside Dialog ( Material UI ) |
JS | Before ES6 classes , a function could be used as a constructor : Then , the following code is equivalent to a classic instantiation ( like let thisObj = new MyClass ( `` A '' , `` B '' ) ) : … This technique was a way to know the this object before calling the constructor . But Function.prototype.call ( ) does n't work... | function MyClass ( a , b ) { } let thisObj = Object.create ( MyClass.prototype ) // Here we know the ` this ` object before to call the constructor.// Then , the constructor is called manually : MyClass.call ( thisObj , `` A '' , `` B '' ) let thisObj = Reflect.construct ( MyClass , `` A '' , `` B '' ) ; | Is it possible to know the 'this ' object before calling the constructor ? |
JS | I have an array notes having nine jpg 's on it , and an array items nine label and nine url 's on it.this code has three boxes It selected 3 items randomly from an array items.I have placed the randomly selected item 's label inside 3 boxes , inside < P > tags , and corresponding image on background from array itemsI h... | var array2 = [ ] ; var items = [ { label : ' 1 ' , url : 'https : //via.placeholder.com/150x150.jpg ? text=image1 ' } , { label : ' 2 ' , url : 'https : //via.placeholder.com/150x150.jpg ? text=image2 ' } , { label : ' 3 ' , url : 'https : //via.placeholder.com/150x150.jpg ? text=image3 ' } , { label : ' 4 ' , url : 'h... | Make the selected images same as randomindex selected from array in javascript |
JS | I have a string like this In above string , for each line , I would like to match tags matching ATEAM- [ 0-9 ] * before # finish tag . If any line does not have # finish , all ATEAM tags should be ignored.Here is the non regex solution that works But would like to convert it to Regex solution and this is what I have tr... | var msg = `` ATEAM-3121 ATEAM-31 123 ATEAM-32 # finish \n ATEAM-3211 \n ATEAM-51 ATEAM-52 ATEAM-53 12345677 # finish ATEAM-1000 '' ; msg = msg.split ( `` \n '' ) ; var tickets = [ ] ; msg.forEach ( function ( val ) { var ticks = val.split ( ' ' ) ; for ( var i = ticks.indexOf ( ' # finish ' ) ; i > = 0 ; i -- ) { if ( ... | Regex to match words with condition |
JS | BackgroundRecently I was in a job interview , and someone made me a test : I was confident this was going to alert an array with 7x undefined , or something among those lines . However , it outputs an empty array , as in an array of length 0 . QuestionFor me this is perplexing . Can someone help me explain why this is ... | var array = [ 1 , 2 , 3 ] ; array [ 10 ] = 10 ; alert ( array.filter ( n = > n === undefined ) ) ; | Javascript Array.prototype.filter unexpected output |
JS | I tried multiple approaches and followed quite a lot questions in StkOvfl , and W3 Specifications , but still no idea.I have a form input : Then in my Javascript ( prepareFormData method ) : [ See full gist class here ] : When I console.log ( files ) , I get all the files all fine . But , formData is not working . I al... | < input type= '' file '' multiple accept= '' image/* '' id= '' item-image-upload '' > var files = this.getFiles ( ) ; var formData = new FormData ( ) ; for ( var i = 0 ; i < files.length ; i++ ) { var file = files [ i ] ; if ( ! file.type.match ( 'image . * ' ) ) { continue ; } formData.append ( this.uploadEntityName ,... | Ajax JS/PHP Image Uploader not working |
JS | I 'm testing the following code in Chrome Canary 63 and on Chrome 61 . The goal of the code is to set a method that calls super onto a class instance ( z ) . In my codebase sometimes property blocks are cloned with Object.assign before being added to the instance and whenever this happens the code fails.I 've reproduce... | let Moo = class { bar ( ) { return `` [ bar on Moo ] `` ; } } ; let Zoo = class extends Moo { bar ( ) { return `` [ bar on Zoo ] `` + super.bar ( ) ; } } ; function addProps ( inst , props ) { // Code works if the line below is commented out but otherwise // results in TypeError : ( intermediate value ) .bar is not a f... | TypeError when assigning shallowly cloned object with a method that calls super |
JS | I have a little script that adds a div named `` doge '' using innerHTML when clicking on a button on my page , and on this page there 's a div with a CSS keyframes animation.However , when I click on the button to add the div named `` doge '' on my page , the CSS animation is `` replayed '' . Why ? How can I fix that ?... | function addHtml ( ) { document.getElementById ( `` wow '' ) .innerHTML += ' < div class= '' doge '' > such wow < /div > ' ; } @ keyframes color { 10 % { background : # 4CAF50 ; } 50 % { background : # 3F51B5 ; } 100 % { background : # 009688 ; } } .myDiv { background : # 000 ; color : # fff ; animation : color 1s ; } ... | Why is my animation `` replayed '' when an element is added via innerHTML ? |
JS | In Secrets of Javascript Closures , Stuart Langridge presents a snippet of code to demonstrate the common usage of a closure in an .onclick callback , and paraphrasing : I 've recently stumbled upon Kyle Simpsons ' Speaker Deck New Rules For Javascript and he mentions that saving the scope of this for a closure like va... | link.onclick = function ( e ) { var newa = document.createElement ( `` a '' ) ; var that = this ; document.body.appendChild ( newa ) ; newa.onclick = function ( e ) { that.firstChild.nodeValue = `` reset '' ; this.parentNode.removeChild ( this ) ; } } | How would one reimplement 'var that = this ' to save a scope reference with Object.prototype.bind ( ) ? |
JS | I noticed something very strange about Angular 1.5.6 components . I have a component called scale . I call it : And in my controller : And my component definition : The console log outputs undefined . But if i change x-scale to r-scale in my template and xScale in the binding to rScale , suddenly it works . In fact it ... | < scale x-scale= '' xScale '' > < /scale > $ scope.xScale = 'lin ' . angular .module ( 'myapp ' ) .component ( 'scale ' , { templateUrl : 'analyse/components/scales/scale.tpl.html ' , controller : function ( ) { console.log ( 'in controller and this is ' , this ) ; } , bindings : { xScale : '= ' } , } ) ; | Can not use letter x to start html attribute in Angular |
JS | I am getting error shown in image for the below code : But when I changes round brackets after `` return '' into curly , it runs fine . I mean what 's happening under the hood ? What causes the error to go away ? | handlechange ( event ) { this.setState ( prevState = > { return ( checked : ! prevState.checked ) ; } ) ; } handlechange ( event ) { this.setState ( prevState = > { return { checked : ! prevState.checked } } ) ; } | What is the difference between `` ( ... .. ) ; '' and `` { ... ... } '' in react ? |
JS | I have a forum thread file thread.php that gets topic ID information.Example : thread.php ? id=781I 'm trying to create a unique views setup , but I have no idea if this is actually feasible : thread.php : unique.phpThis will create a new cookie for each different thread . So if the user views 100 threads , they 'll ha... | topicId = < ? php echo $ _GET [ 'id ' ] ; ? > ; if ( $ .cookie ( `` unique '' +topicId ) ! == '' 1 '' ) { $ .cookie ( `` unique '' +topicId,1 , { expires : 1000 , path : '/ ' } ) ; // create cookie if it does n't exist $ .post ( 'unique.php ' , { id : topicId } ) ; // update thread unique views } // connection stuff $ ... | Updating unique views using cookies |
JS | So I have this Display ( ) function which takes events from the Google Calendar and the function returns a list of elements ( each element is associated with a slider ) to be rendered on the screen ( see return statement of Display ( ) function ) and renders them as seen here . So each element comes with a Remove butto... | function Display ( ) { const isMounted = useRef ( true ) ; const [ items , saveItems ] = useState ( [ ] ) ; const [ visible , setVisible ] = useState ( true ) ; const [ fading , setFading ] = useState ( false ) ; useEffect ( ( ) = > { return ( ) = > { isMounted.current = false ; } ; } , [ ] ) ; useEffect ( ( ) = > { ( ... | How to remove HTML div on click using Javascript |
JS | What I 'm trying to doMy goal is to transition a list so that when an item is clicked , it smoothly rises to the top of the list , becoming the title ( see example ) . Realistically , a menu UI would appear below it . I can transition the height of all elements except the one clicked to smoothly animate it to the top o... | //name variables containing JQuery $ ... $ ( '.container ' ) .on ( 'mousedown touchstart ' , function ( ) { $ allContainersExceptThis = $ ( '.container ' ) .not ( this ) ; if ( ! this.isSelected ) { $ allContainersExceptThis.css ( { 'transform ' : 'scaleY ( 0 ) ' } ) ; $ ( this ) .css ( { 'background-color ' : 'orange ... | How can I `` pinch '' an element containing text smoothly ? |
JS | Say , I need to call a function in a custom element , such that when a slider moves in that element the text gets updated ( only for that element ) . The main.js file , On the template side , The error I am getting is , I do not know how to reference the method for that particular object in this.slider.setAttribute ( '... | class OninputClassDemo extends HTMLElement { constructor ( ) { super ( ) ; const shadow = this.attachShadow ( { mode : 'open ' } ) ; this.parent = document.createElement ( 'div ' ) ; this.slider = document.createElement ( 'input ' ) ; this.slider.setAttribute ( 'type ' , 'range ' ) ; this.slider.setAttribute ( 'min ' ,... | Javascript custom element 's oninput function issue |
JS | I have an object named obj that will be used as a basis to create a new array of objects in a certain format.My base object : I created a function getObj ( ) which accepts two arguments lang and the base object obj.SAMPLE SCENARIOSWhen I call : I should get : When I call : I should get : Below is what I tried : | var obj= { `` en '' : [ { `` faq '' : `` faq '' , `` about '' : `` about '' } ] , `` hi '' : [ { `` faq '' : `` aksar-poochhe-jaane-vaale '' , `` about '' : `` hamaare-baare '' } ] } getObj ( `` en '' , obj ) ; [ { `` url '' : `` /en/faq '' , `` links '' : [ { lang : 'en ' , url : '/en/faq ' } , { lang : 'hi ' , url : ... | Selectively create a new array of objects from a base object containing array properties |
JS | I made a site that shows dynamically created HTML using ajax with jQuery.On one part it shows diferent entries from a database table , and on each row there 's a button to delete that specific entry from the database . This is the code that should make that happen : However , when I click the button I get the errorCorr... | $ ( 'body ' ) .on ( 'click ' , '.deleteWaitlist ' , function ( ) { console.log ( `` Clicked on .deleteWaitlist name = `` + $ ( this ) .attr ( 'name ' ) ) ; // Get the varible name to send to your php var i = $ ( this ) .attr ( 'name ' ) ; console.log ( `` $ ( this ) .attr ( 'name ' ) = i '' ) ; $ .post ( { url : `` del... | $ .post ( ) giving bad url string |
JS | When a sparse array is sorted [ 5 , 2 , 4 , , 1 ] .sort ( ) - > [ 1 , 2 , 4 , 5 , empty ] , the empty value is always last even with callback no matter the return statement.I 'm building my own sort method as a challenge and I solved this problem by using filter method since filter skips empty values . Then iterate ove... | const collectUndefined = [ ] ; // remove empty items and collect undefinedconst removeSparse = this.filter ( el = > { if ( el === undefined ) { collectUndefined.push ( el ) ; } return el ! == undefined ; } ) ; const tempLength = this.length ; // reset values but will contain duplicates at the endfor ( let i = 0 ; i < r... | How does native sort method deal with sparse arrays |
JS | I am very new to JQuery and can not process how I can do this . I have a table in my database called user_thoughts . I am trying to implement the infinity scroll feature , which current , should alert ( `` bottom '' ) when the thoughts for a user surpass 10 . Each user can upload a thought and on their profile_page , o... | $ ( document ) .ready ( function ( ) { var load = 0 ; $ ( window ) .scroll ( function ( ) { if ( $ ( window ) .scrollTop ( ) == $ ( document ) .height ( ) - $ ( window ) .height ( ) ) { load++ ; // start AJAX $ .post ( `` inc/ajax.php '' , { load : load } , function ( data ) { $ ( `` .userposts_panel '' ) .append ( dat... | How to get number of rows as a JQuery variable |
JS | Assume you are annoyed by my posts and want to hide all my comments from Stack Overflow . I know how to create a custom CSS to hide my username : Unfortunately CSS does not allow me to refer to the parent element , so this will leave the text of the comment.How can I hide the parent or preceding sibling to that link ta... | a [ href $ = '' what '' ] { display : none ! important ; } | StackExchange blacklist |
JS | I am curious as to why the TypeScript transpiler compiles enums into dictionary lookups instead of simple objects . Here is an example TypeScript enum : Here is the JS code TypeScript emits : My curiosity is wondering why TypeScript does n't simply do this : | enum transactionTypesEnum { None = 0 , OSI = 4 , RSP = 5 , VSP = 6 , SDIV = 7 , CDIV = 8 } var TransactionTypes ; ( function ( TransactionTypes ) { TransactionTypes [ TransactionTypes [ `` None '' ] = 0 ] = `` None '' ; TransactionTypes [ TransactionTypes [ `` OSI '' ] = 4 ] = `` OSI '' ; TransactionTypes [ Transaction... | Why does the TypeScript transpiler compile enums into dictionary lookups instead of simple objects ? |
JS | Hi I have some sort of the following code : Why is it not possible for me to access the card in myfunction . Its telling me that it is undefined . I tried it with setting a this.card = React.createRef ( ) ; in the constructor but that did n't work either . | class First extends Component { constructor ( props ) { super ( props ) } myfunction = ( ) = > { this.card //do stuff } render ( ) { return ( < Component ref= { ref = > ( this.card = ref ) } / > ) } } | How to access ref that was set in render |
JS | I have two classes with nested content , ex : How do I add the class active on the first tab-pane for each tab-content ? | < div class= '' tab-content '' > < div class='tab-pane ' > < /div > < div class='tab-pane ' > < /div > < /div > < div class= '' tab-content '' > < div class='tab-pane ' > < /div > < div class='tab-pane ' > < /div > < /div > | Selecting from same class the first child and adding a class name |
JS | so what I 'm trying to do is draw a bar chart below a bar chart i already have created.so this is the scale i have initially usedThis splits the SVG into 5 pieces theoretically , but the problem is it does n't expand vertically just horizontally.I 've tried to change the range multiple time , but to no avail.this is a ... | this.visScale = d3.scaleBand ( ) .domain ( [ 'Q1 ' , 'Q2 ' , 'Q3 ' , 'Q4 ' , 'OT ' ] ) .range ( [ this.dims.margins.left , this.dims.width - this.dims.margins.right ] ) .paddingInner ( 0.1 ) ; | Drawing bar charts vertically after each other d3.js |
JS | I 'm developing 8 puzzle game using javascript , I shuffle the tiles by shuffling the puzzle tiles arrayI want to give the user the option to choose difficulty : easy , medium , hard , How can I implment this ? Update : I will explain a little bit my implmentation . ( this is typescript ) The puzzle array is an array o... | var shuffleArray = ( array ) = > { var currentIndex = array.length , temporaryValue , randomIndex ; while ( 0 ! == currentIndex ) { randomIndex = Math.floor ( Math.random ( ) * currentIndex ) ; currentIndex -= 1 ; temporaryValue = array [ currentIndex ] ; array [ currentIndex ] = array [ randomIndex ] ; array [ randomI... | How to adjust randomization level javascript |
JS | Given this query string : How can I extract the values from only these param types 'product_cat , product_tag , attr_color , attr_size ' returning only 'mens-jeans , shirts , fall , classic-style , charcoal , brown , large , x-small ? I tried using a non-capturing group for the param types and capturing group for just ... | ? cgan=1 & product_cats=mens-jeans , shirts & product_tags=fall , classic-style & attr_color=charcoal , brown & attr_size=large , x-small & cnep=0 ( ? : product_cats=|product_tags=|attr\w+= ) ( \w| , |- ) + | Javascript get query string values using non-capturing group |
JS | An external API returns a JSON result of the following form : Here , the keys `` 1.0 '' , `` 2.3 '' , `` 3.6 '' should really be taken as strings denoting a discrete categorisation , not as values along a continuous axis . It is therefore perfectly valid for this API to return these keys as strings.However ... ( you ca... | { `` data '' : { `` 1.0 '' : 'foo ' , `` 2.3 '' : 'bar ' , `` 3.6 '' : 'baz ' } } let myObject = { `` data '' : { `` 1.0 '' : 'foo ' , `` 2.3 '' : 'bar ' , `` 3.6 '' : 'baz ' } } console.log ( myObject.data ) for ( let k in Object.keys ( myObject.data ) ) { console.log ( k , myObject.data [ k ] ) } // { // 1.0 : 'foo '... | JavaScript casts keys with numerical strings to Numbers ... but Object.keys ( ) does n't |
JS | I 've created a simple modal that is allowed to be closed when you click outside of the content area . This is by design but it has an unintended side-effect . If I click anywhere in the content area ( for example in a text field ) and drag the mouse to beyond the content area and then release the click it will close t... | var modal = document.getElementById ( `` modal-container '' ) ; function openModal ( ) { modal.classList.add ( `` active '' ) ; } function closeModal ( ) { modal.classList.remove ( `` active '' ) ; } window.onclick = function ( event ) { if ( event.target == modal ) closeModal ( ) ; } html , body { margin : 0 ; height ... | Prevent modal from closing when click did n't initiate outside of content ? |
JS | I have implemented a HTTPs ( onCall ) function that throws some errors to the client or return true if the work is successfully completed . The problem is that I do n't see why to return true ( because when I throw the errors I do n't return false ) .As HTTP protocol requires to return a response to the client to finis... | exports.function = functions .region ( `` us-central1 '' ) .runWith ( { memory : `` 2GB '' , timeoutSeconds : 120 } ) .https.onCall ( async ( data , context ) = > { // Lazy initialization of the Admin SDK if ( ! is_function_initialized ) { // ... stuff is_uploadImage_initialized = true ; } // ... asynchronous stuff // ... | What should I return in an https callable function if it does n't expect to return nothing |
JS | I have an element with a a script for a mouseover to show an image . I ca n't change the HTML , so is it possible to disable the javascript in the link , but still keep the link for the href intact ? I cant use the id of the a element since it is n't unique . HTML : | < div class= '' container '' > < a id= '' a211094 '' onmouseout= '' etim ( ) ; '' onmouseover= '' stim ( '/imgs/7c24b548-4f4c-418e-ad4f-53c73cf52ace/250/250 ' , event , this.id ) ; '' href= '' /products/Computers/Desktops/Acer/Acer-Aspire-TC-705W-Towermodel-1-x-Core-i3-41 ? prodid=211094 '' > < img src= '' '' alt= '' '... | Disable javascript in a element |
JS | I have a string `` I am a robot , I have been named 456/m ( 4 ) . Forget the name ( it does not mean anything ) '' Now I would like to extract all words from this stringfor this I use the regular expression : it returns me all the words in the string except that there is a word `` 456/ ( 4 '' instead of `` 456/ ( 4 ) '... | /\b [ \w\S ] +\b/g | javascript regexp for word boundary detection with parenthesis |
JS | I currently have an array of strings that are numbers I am attempting to remove the commas so my data returns 0 : `` 1431417 '' , 1 : 1838127 ... After removing commas I am then mapping this array to convert it to an array of numbers and not strings . But when console.logging the finalArray that should return an array ... | data.dataArr = [ 0 : `` 1,431,417 `` 1 : `` 1,838,127 `` 2 : `` 679,974 `` 3 : `` 2,720,560 `` 4 : `` 544,368 `` 5 : `` 1,540,370 `` ] let data = { dataArr : [ `` 1,431,417 `` , `` 1,838,127 `` , `` 679,974 `` , `` 2,720,560 `` , `` 544,368 `` , `` 1,540,370 `` ] } ; //removing commaslet arrData = data.dataAr... | Javascript - Removing commas from an array of string numbers |
JS | I want to code some sort of state machine with different transitions . But something strange happens , when I want to select an item.The last two lines are very interresting - the same index , first hardcoded and the second stored within a variable . Why does the first return the right result ( false ) and the other un... | var transitions = { `` on '' : { `` false '' : '' true '' , `` true '' : '' false '' } } console.log ( attr ) ; // onconsole.log ( transitions [ attr ] ) ; // Object { false= '' true , true= '' false '' } console.log ( current_val ) ; // `` true '' console.log ( typeof current_val ) ; // stringconsole.log ( transitions... | Strange Javascript behavior - js object |
JS | As far as I know , The logical & & works like the followingThis code , will assign 42 to foo only if the first condition gets evaluated to true . So in this example , foo will keep its current value.I 'm wondering why this snippet does n't work at all : Now , foo gets the value from test assigned . I 'm very confused .... | var test = false ; var foo = test & & 42 ; var test = `` '' ; var foo = test & & 42 ; | & & evaluation issue |
JS | Here is my javascript code , I 'm getting error Uncaught SyntaxError : Unexpected token ILLEGAL at Line no 37 I was trying to append the options to `` select '' list from a json , my code seems to be have no syntax error . but chrome is throwing one . | 31 set_options_list = function ( selctelm , json ) { 32 $ ( selctelm ) .empty ( ) ; 33 $ .each ( json , function ( k , val ) { 34 $ ( selctelm ) .append ( 35 $ ( `` < option > < /option > '' ) .text ( val ) .val ( val ) 36 ) 37 } ) ; 38 } | What 's the error in my javascript code ? |
JS | I have a < span > element as follows : And I am reading this < span > like this : it returns the above output , but I want to convert it to string . If I use : it just returns : How could I get a pure string representation of my < span > ? | < span style= '' position : absolute ; top : -42px ; right : 2px ; z-index : 100 ; '' data-ng-click= '' DeleteImageProperties ( img.vehicleId , img.vehiclePhotoId , img.fileName ) '' > × < /span > var outerHTML = itemelement [ 0 ] ; outerHTML.toString ( ) [ object HTMLSpanElement ] | Javascript string representation of HTML element |
JS | I am getting a Javascript object req.files . This object can have multiple files under it . req.files is an object and not an array.So of if user adds three files , the object will look like : where file0 , file1 etc is another object.User can add upto 15 files . How can I check loop over such objects & read informatio... | req.files.file0req.files.file1req.files.file2 | Generate javascript object name by appending string to object |
JS | First project - need to pull from nested arrays for a quiz but loop is stuck somehow on the second position in the array and is skipping the first . also is stuck in an infinite loop -My logic is that if i = 0 from the start it should run the first prompt then finish the loop adding 1 to the i variable , then run the s... | var quiz = [ [ `` what color is the sky ? '' , `` blue '' ] , [ `` what color are most apples ? `` , `` red '' ] , [ `` what color is coffee ? '' , `` black '' ] ] ; var i ; for ( i = 0 ; i < 3 ; i++ ) { if ( i = 0 ) { var ans1 = prompt ( quiz [ 0 ] [ 0 ] ) ; } else if ( i = 1 ) { var ans2 = prompt ( quiz [ 1 ] [ 0 ] )... | Why is my for loop stuck on the second option ? |
JS | I need to create a variable variable name in JS ... I want the result to be `` 1 '' fiddle here : http : //jsfiddle.net/mR6BH/ | obj = { } ; obj.fooonex = { } ; obj.fooonex.start = 1 ; obj.fooonex.end = 2 ; a = `` foo '' ; b = `` one '' ; c = `` x '' ; test = a + b + c ; alert ( obj.test.start ) ; | Variable Variable in JS |
JS | I have one button that gets style from .btn-1 . : In the script , I have three variables , combining them in one string to create the gradient color on the button : And then I want to apply this `` color '' variable to the background-image , so that the button have a different gradient color.I tried two different ways ... | < a id= '' button1 '' class= '' btn btn-1 '' > Hover me < /a > < br > var color1 = `` # fdceaa '' ; var color2 = `` # FFFFFF '' ; var color3 = `` # FFFFFF '' ; var color = 'linear - gradient ( to right , ' + color1 + ' 0 % , ' + color2 + ' 51 % , ' + color3 + ' 100 % ) ' document.querySelector ( '.btn.btn-1 ' ) [ 'back... | Dynamically changing the CSS of a button , using JavaScript , and custom variables |
JS | With Crockford 's definition : and ECMA-262 's introduction of Object.create ( ) , we now can set a new object a 's hidden prototype property to point to another object b for pure prototypal inheritance . But it is limited to a new object , and Javascript still wo n't allow something likefor an existing object a in the... | if ( typeof Object.create ! == 'function ' ) { Object.create = function ( o ) { function F ( ) { } F.prototype = o ; return new F ( ) ; } ; } a.__proto__ = b ; | In Javascript , why ca n't we set prototypal inheritance arbitrarily ? |
JS | I have a few spans : And operations on them : But JSON.stringify return empty array . How can I count the number of occurrences of data-id at a given SPAN the easiest way and next get it to string ? I would like to send this data to API.Fiddle : https : //jsfiddle.net/x7thc59v/ | < span class= '' first '' data-id= '' 1 '' / > < span class= '' second '' data-id= '' 4 '' / > < span class= '' second '' data-id= '' 2 '' / > < span class= '' third '' data-id= '' 5 '' / > const spans = document.querySelectorAll ( 'span ' ) ; const list = [ ] ; spans.forEach ( function ( span ) { if ( typeof list [ sp... | How to send array of objects with keys to API ? |
JS | I created a circular graphic that is mainly based on pure HTML and CSS . A little JavaScript and JQuery is added for curving text and interaction that is planned for later on.The problem I have is , that when I click on the upper right element , it is covered in party by the upper left element . So when I check which e... | $ ( document ) .ready ( function ( ) { function textRotation ( ) { new CircleType ( document.getElementById ( 'demo1 ' ) ) .radius ( 185 ) ; new CircleType ( document.getElementById ( 'demo2 ' ) ) .radius ( 185 ) ; new CircleType ( document.getElementById ( 'demo3 ' ) ) .radius ( 185 ) ; } textRotation ( ) ; $ ( ' # de... | How would I target an element that is visible but beneath another element ? |
JS | I 've recently been reading into Javascript 's Map datatype ( NOT the map ( ) array method ) .MDN ReferenceI 've read and followed various tutorials/articles showing the similarities and differences between Maps , Arrays and 'standard ' Objects . One unique property of Maps is that you can use any datatype as a key , i... | // Create an objectconst objAsKey = { foo : 'bar ' } const map = new Map ( ) // Set this object as the key of a Mapmap.set ( objAsKey , 'What will happen ? ' ) key : { foo : `` bar '' } value : `` What will happen ? '' | What is a practical use of objects as keys within JS Map dataype ? |
JS | Following are two ways to define BW.Timer . Can someone tell me what the difference is ? I am not certain the first is even valid , but if it is valid , what is different about using the myfunc= ( function ( ) { } ( ) ) syntax ? And ... | BW.Timer = ( function ( ) { return { Add : function ( o ) { alert ( o ) ; } , Remove : function ( o ) { alert ( o ) ; } } ; } ( ) ) ; BW.Timer = function ( ) { return { Add : function ( o ) { alert ( o ) ; } , Remove : function ( o ) { alert ( o ) ; } } ; } ; | What is the difference in the following JS syntax ? |
JS | I 'm starting with react and I have an array of objects called arrayToFilter I want to apply multiple filters to , ideally when a user changes the filter select options all filters should be applied to the array and the results returned into a filteredResults array to show , I already have each filter function and thei... | const [ arrayToFilter , setArrayToFilter ] = useState ( [ /*array of objects to apply filters to*/ ] ) ; const [ filteredResults , setFilteredResults ] = useState ( [ /*array of filtered objects*/ ] ) ; const [ categoryOptions , setCategoryOptions ] = useState ( [ 1,2,3 ] ) ; const [ selectedCategoryOptions , setSelect... | React : apply multiple filters to array |
JS | Good morning ! I am preparing my database for use HighMaps with Laravel5 , I receive this JSON form since Laravel.Higchamps needs the following format : How could I send the format data that Highmaps need ? The sql in controller is this : | [ { `` hc-key '' : '' es-vi '' } , { `` hc-key '' : '' es-cs '' } , { `` hc-key '' : '' es-lo '' } , { `` hc-key '' : '' es-z '' } ] var data = [ { 'hc-key ' : 'es-pm ' , value : 0 } , { 'hc-key ' : 'es-va ' , value : 1 } , { 'hc-key ' : `` , value : 52 } ] ; $ provincias= DB : :table ( 'provincia ' ) - > lists ( 'hc-k... | Highmaps Graphics with Laravel5 |
JS | I 'm like most of novice web developers in most cases use jQuery , but more often I started to use clean js . So from here is my question : is it god practice to use clean js in jQuery scope , for example if i need to get elements class i can do this like : But what is the best way ? | jQuery ( 'div # grid a ' ) .click ( function ( event ) { event.preventDefault ( ) ; console.log ( this.getAttribute ( 'class ' ) ) ; console.log ( this.className ) ; console.log ( jQuery ( this ) .attr ( 'class ' ) ) ; } ) ; | What is the best way to get elements attributes ? |
JS | I 'm trying to encrypt some text using window.crypto : However I get this error AES key data must be 128 or 256 bits . I 'm using PBKDF2 to create a 256 bit key from a password and I specify a key length of 256 : But I end up getting this key edi5Fou4yCdSdx3DX3Org+L2XFAsVdomVgpVqUGjJ1g= after I exportKey it and convert... | await crypto.subtle.encrypt ( algorithm , key , dataArrayBuffer ) .catch ( error = > console.error ( error ) ) ; window.crypto.subtle.deriveKey ( { `` name '' : `` PBKDF2 '' , `` salt '' : salt , `` iterations '' : iterations , `` hash '' : hash } , baseKey , { `` name '' : `` AES-GCM '' , `` length '' : 256 } , // < -... | window.crypto returns 352 bit key instead of 256 ? |
JS | I want to find text inside div parent with table , if i write any text inside my search bar i want to show only the result and the rest of the divs hidde , i have differents td that i want search in the four cells ( left to rigth ) the last cell is not importantThis is my HTML : And this is my Script : My example only ... | < div class= '' caja-orden-curso '' alt= '' 3 '' > < div class= '' contenido-curso '' > < table id= '' perrito '' border= '' 1 '' style= '' width:98 % '' > < tr > < td width= '' 220 '' height= '' 100 '' > < div id= '' vehicle_type '' class= '' top-order '' > 36624 < /div > < /td > < td width= '' 200 '' > < div id= '' s... | How to find text inside table with div parent |
JS | I have set up this jsfiddle : http : //jsfiddle.net/386er/dhzq6q6f/14/ } In the moveCell function , I pick a random cell , request its current x and y coordinates and then add or subtract its width or height , to move it to an adjacent cell.What I am wondering about : If you watch the cells move , some will only move p... | var moveCell = function ( direction ) { var cellToBeMoved = pickRandomCell ( ) ; var currentX = cellToBeMoved.x.baseVal.value ; var currentY = cellToBeMoved.y.baseVal.value ; var change = getPlusOrMinus ( ) * ( cellSize + 1 ) ; var newX = currentX + change ; var newY = currentY + change ; var selectedCell = d3.select (... | Why do some cells not move entirely |
JS | I 've come across a situation where I need to filter elements created by the 'ng-repeat ' directive , but I 've applied a custom filter that swaps one character by another and vice versa , for each created element.Then , if I search for the new character that was swapped , the filter wo n't find it - unless I search fo... | < div ng-app= '' myApp '' ng-init= '' person= [ { firstName : 'Johnny ' , lastName : 'Dowy ' } , { firstName : 'Homem,25 ' , lastName : 'Cueca , Suja ' } , { firstName : 'Alleria.Donna ' , lastName : 'Windrunner ' } ] ; '' > First Name : < input type= '' text '' ng-model= '' firstName '' > < br / > The persons 's objec... | Filter by name after applying a filter that changes characters |
JS | I have a HTML form that submit to a JavaScript , the data is processed and a POST request is sent to a PHP script.when I arrive at the conditionand the condition are satisfied.Code does n't go in.continues to decrement the month and when it gets to -2 , it still performs five iteration and then the code arette not offe... | var xmlHttp = new XMLHttpRequest ( ) ; xmlHttp.onreadystatechange = function ( ) { if ( xmlHttp.readyState == 4 & & xmlHttp.status == 200 ) { if ( contentElt & & xmlHttp.responseText ) { var ajaxData = JSON.parse ( xmlHttp.responseText ) ; var processedResultCount = parseInt ( ajaxData [ 0 ] ) ; totalResultCount += pro... | JavaScript does not take an account of the conditions exit , while variables are nevertheless equal to the output condition |
JS | Is there any way at all to ether get , access or eventually console.log u ? Is there any code I could put inside x that might make u vulnerable / accessable from the outside ? Edit : I mean without returning u `` directly '' . Is there any way of accidentally exposing u ? | var x= ( function ( ) { var u=1 ; } ) ( ) ; console.log ( x.u ) ; // undefined | Is there a clever way to access a variable inside a wrapped function ? |
JS | The following javascript code , allows you to access the global object ( window/worker ) .Is there a way by which I can ensure that the inner this always gets a reference to Outer 's context.I know i can do but that results in this being undefined.EditI know about bind , but what if the inner function is nested . for i... | ( new function Outer ( ) { console.log ( this ) ; /* The object */ ( function ( ) { // This function could be a 3rd Party function console.log ( this ) ; /* window ! ! */ } ) ( ) ; } ) ; ( new function Outer ( ) { 'use strict ' ; console.log ( this ) ; /* The object */ ( function ( ) { // This function could be a 3rd P... | Protect the global reference in javascript |
JS | I have a variable I need to drop into a javascript file and ca n't seem to get any results . I 've tried making the .js into a php and adding an echo but it does n't work.I have a file that calls this in itInside of file.php I have this lineEverything works perfect when I replace the php with an actual color ( # FFFFFF... | < script type= '' text/javascript '' src= '' /file.php '' > < /script > style : { color : ' # < ? php echo $ _SESSION [ 'colorOne ' ] ; ? > ' } | PHP variable in Javascript file |
JS | The code below will get different in Browser and Node.js.Result of browser is a.Result of Node.js is b.Although this code style is anti-pattern , the code still can be run in environment.How to explain it ? FYI.Node.js environment Link : https : //repl.it/CgWhNative Browser environment Link : https : //repl.it/CgWjThes... | if ( 1 ) { function foo ( ) { return ' a ' ; } } else { function foo ( ) { return ' b ' ; } } console.log ( foo ( ) ) ; | JavaScript function declarations in Native browser and Node.js , get differnt results |
JS | I am trying to get focus inside a particular ‘ section ’ inside a div on mouse click . I have written the following lines of code : The sections are added inside a for loop inside the div based on some if statements.There are five sections of the class ‘ my-section-class ’ inside the div and $ ( ' # my-div-id ' ) .chil... | $ ( ' # my-div-id ' ) .children ( '.my-section-class ' ) .on ( { 'mousedown ' : function ( e ) { var $ item = $ ( this ) ; $ item.focus ( ) ; } } ) ; | Control not coming inside divobject.children ( ) .on ( { 'mousedown ' ... } ) ; |
JS | I 've found a lot of similar questions but they explain how to remove duplicate objects . In this case , I need to create a new array that does n't include objects which were found in two arrays.The expected result for the previous sample of data should be : | const firstArray = [ { firstName : 'John ' , lastName : 'Doe ' } , { firstName : 'Sara ' , lastName : 'Connor ' } , { firstName : 'Mike ' , lastName : 'Hunt ' } , { firstName : 'Steve ' , lastName : 'Irvine ' } ] ; const secondArray = [ { firstName : 'John ' , lastName : 'Doe ' } , { firstName : 'Sara ' , lastName : 'C... | How to return only non-duplicated objects from 2 arrays |
JS | We are struggling with a strange issue in using setTimeout function in Javascript at the React.As using codes inside the setTimeout , it runs much slower than running the codes without the setTimeout ! As a comparison , the performance is resulted in : Using setTimeout : 1391 ms without using setTimeout : 15 msIn API c... | import React , { useState } from `` react '' ; import ReactDOM from `` react-dom '' ; function App ( ) { const [ value , setValue ] = useState ( `` '' ) ; const [ time , setTime ] = useState ( `` '' ) ; const startSample = ( ) = > { const startTimeStamp = new Date ( ) .valueOf ( ) ; for ( let i = 0 ; i < 5000 ; i++ ) {... | setTimeout runs its callback codes much slower than without it |
JS | The following code is meant to be a short example for a simple construct of a reusable object . This is a very simple , one level depth object , put as many props and methods as you like and just assign them.Here is an example of this use : As this imaginative object , is actually not as simple as I did use in my code ... | function someDesiredReusableType ( optionally , pass , ctor , pars , here ) { //core obj to return var DesiredTypeCrtor = { propSkiingLocation : `` canada '' , OrderTickets : function ( optionally ) { var tryRoomWView = optionaly ; print ( `` Dear `` + ctor + '' , your request for `` + propSkiingLocation + `` is now be... | Proper approach for complex / nested JavaScript-object creation within another object |
JS | I have an array of day ranges , like this : [ `` Mon-Tue '' , `` Mon-Wed '' , `` Mon-Thu '' , `` Mon-Fri '' , `` Mon-Sat '' , `` Mon-Sun '' , `` Tue-Mon '' , `` Tue-Wed '' , `` Tue-Thu '' , `` Tue-Fri '' , `` Tue-Sat '' , `` Tue-Sun '' , ... ] What I need is to create a large object which maps each one of these strings... | var object = { 'Mon-Tue ' : [ 'Mon ' , 'Tue ' ] , 'Mon-Wed ' : [ 'Mon ' , 'Tue ' , 'Wed ' ] , } var days = [ 'Mon ' , 'Tue ' , 'Wed ' , 'Thu ' , 'Fri ' , 'Sat ' , 'Sun ' ] | Generate day-of-the-week objects from an array of strings |
JS | Before asking this question , i searched in google and i found this post.Then i thought , before line X the structure similar like this : After the x line , I thought it was like this : But when i wrote bye in firefox developer tools i saw thisHow is it possible ? When i wrote let bye = sayBye ; is the sayBye coppied ? | let sayBye = function ( ) { console.log ( ` Bye ` ) ; } let bye = sayBye ; sayBye = null ; // Xbye ( ) ; // Y sayBye -- -- -- -- -- -- -- - | | = > function ( ) { ... . } |bye -- -- -- -- -- -- -- -- -- - sayBye MEMORY | = > function ( ) { ... . } |bye -- -- -- -- -- -- -- -- -- - let sayBye = function ( ) { console.lo... | How to keep JavaScript function expressions in memory ? |
JS | I 'm working on a bootstrap based webpage and in my CSS file I have the following code : it applies gradient as a background to my page , however I have also two other gradients : andand now I want to apply one of those 3 gradients randomly when user refreshes the page ( so e.g . first he sees the 2nd gradient , then h... | body { height : 100 % ; background : # 3a7bd5 ; /* fallback for old browsers */ background : -webkit-linear-gradient ( to left , # 3a7bd5 , # 3a6073 ) ; /* Chrome 10-25 , Safari 5.1-6 */ background : linear-gradient ( to left , # 3a7bd5 , # 3a6073 ) ; /* W3C , IE 10+/ Edge , Firefox 16+ , Chrome 26+ , Opera 12+ , Safar... | How can I set different gradients as background , each time user refreshes ? |
JS | I 've seen this done alot in JavaScript and I do remember finding out why but I ca n't remember the answer.I 'm guessing it 's something to do with scope and a function being called outside the `` class '' but why would one do this ( preferably outlining an example ) : | function myClass ( ) { var self = this ; // ... this.myArray = [ ] ; this.myFunc = function ( ) { alert ( self.myArray.length ) ; } ; } | Why would you create a variable with value this |
JS | I am trying out a more functional style with Javascript using Lodash and compose . I notice that I sometimes need a function that returns a value . So was wondering what this was called so I can find out if Lodash actually has this method.Example : Instead of : | var returnFn = function ( i ) { return function ( ) { return i ; } ; } ; _.compose ( doSomething , returnFn ( { foo : 'bar ' } ) ; _.compose ( doSomething , function ( ) { return { foo : 'bar ' } ; } ) ; | What do you call a function that takes a value and returns a function that returns that value ? |
JS | I want to get all the keys in an array of objects . Initially I just grabbed the first object in the array and used : But when I looked closer at the data I noticed that the first row did n't contain all the needed keys . In the following example the third item contains all the keys but you might have a case where gett... | var keys = Object.keys ( tableData [ 0 ] ) ; var tableData = [ { first : '' jeff '' , last : '' doe '' , phone : `` 2891 '' } , { first : '' sarah '' , phone : '' this '' , county : `` usa '' } { first : '' bob '' , last : '' brown '' , county : `` usa '' , phone : `` 23211 '' } ] ; | Efficent way to get all keys in unorganized array of objects |
JS | I 'm new to JavaScript and am trying to understand how to use namespaces to avoid naming conflicts . So far , the two most popular methods I 've found for creating namespaces are these : Method 1 : Method 2 : Is the difference that the second method allows you to have private methods and variables , since only what is ... | var MYAPPLICATION = { calculateVat : function ( base ) { return base * 1.21 ; } , product : function ( price ) { this.price = price ; this.getPrice = function ( ) { return this.price ; } ; } , doCalculations : function ( ) { var p = new MYAPPLICATION.product ( 100 ) ; alert ( this.calculateVat ( p.getPrice ( ) ) ) ; } ... | What 's the difference between these namespacing methods ? |
JS | I 'm currently working on a web game that will also be available as a desktop application via electron . I 'd like to simply not require ( 'electron ' ) if I am building the web version of the game.My .yml file that I use with build is as follows : If my build command was something like node main.js true , I could just... | cmd : browserify { PROJECT_PATH } /js/main.js > { PROJECT_PATH } /js/bundle.js & & { PROJECT_PATH } /index.htmlname : 'web'targets : electron : cmd : browserify { PROJECT_PATH } /js/main.js > { PROJECT_PATH } /js/bundle.js & & electron { PROJECT_PATH } if ( passedBoolean ) { const { app , BrowserWindow } = require ( 'e... | How can I require different modules in Javascript based on my YML build file ? |
JS | I have updated my Node.Js into version 7.6.0 and running google chrome version 57.0 on the other hand.When I run this snippet of javascript code , I get two different result like below : result on chrome : result on node.js : Recording to https : //nodejs.org/en/docs/es6/ I even used the -- harmony flag but the result ... | 'use strict ' var obj = { id : `` awesome '' , cool : function coolFn ( ) { console.log ( this.id ) ; } } ; var id = `` not awesome '' ; obj.cool ( ) ; //awsome setTimeout ( obj.cool , 100 ) ; awesomenot awesome awesomeundefined | Why there is different outputs in running JavaScript on web and nodejs ? |
JS | I am trying to build a custom drop-down having collapsible options.Each option inside the drop-down will have sub options which when selected will give me the value.On an abstract , the drop-down should look like below : Considering above idea , I have tried my approach through a fiddle.But my snippet does not resemble... | function myFunction ( ) { var x = document.getElementById ( `` myDIV '' ) ; if ( x.style.display === `` none '' ) { x.style.display = `` block '' ; } else { x.style.display = `` none '' ; } } .main-div { display : inline-block ; padding : 15px ; width : 180px ; cursor : pointer ; border : 1px solid salmon ; } .inner-di... | How to build a collapsible options inside a dropdown with plain JavaScript |
JS | Was just going through the source code for Laravel Mix ( webpack setup ) to get some inspiration on setting up my own webpack when I came across this.I ca n't figure out what the point of this is but I trust Taylor would n't include anything superfluous just for the sake of it . Surely any of these are just as good ? o... | rules.push ( ... [ ] .concat ( newRules ) ) rules.concat ( newRules ) rules.push ( ... newRules ) | What , why ! ? Tricky JS code spread ... and [ ] .concat |
JS | I 'm looping over an array and modifying the contents of the array , but I do n't get the results I expect . What am I missing or doing wrong ? I have two groups of divs ( one with class attacker , and other enemy ) with three elements each . I am trying to select one element from each side by making a border around it... | < div id= '' army1 '' > < div class= '' attacker '' > < img src= '' img/Man/Archer.jpg '' / > < div class= '' hp '' > < /div > < /div > < br > < div class= '' attacker '' > < img src= '' img/Man/Knight.jpg '' / > < div class= '' hp '' > < /div > < /div > < br > < div class= '' attacker '' > < img src= '' img/Man/Soldie... | I 'm looping over an array and modifying the contents of the array , but I do n't get the results I expect . |
JS | I just ran across some jQuery that looks like this : This appears to be binding to the 'click.add ' event . I use custom events myself and think they 're awesome , but doing git grep on our code base does n't reveal any place where a custom event called click.add is triggered , and in any case , this behavior is trigge... | $ ( '.add-row ' ) .live ( 'click.add ' , function ( ) { // do something } | This appears to be a class on a Javascript event . What is it ? |
JS | I am trainee front end developer and I am working on some demo.It is working for onclick mouse event but it is not working for both onclick and onmouseover . I need an onclick option and also an onclick + mouseover option.Here is my html file : Here is my Javascript file : and the css file : My question is : how I use ... | < html > < head > < link rel= '' stylesheet '' type= '' text/css '' href= '' MyStyle.css '' > < script src= '' myScript.js '' > < /script > < title > Main page < /title > < /head > < body onload= '' init ( ) '' > < canvas id= '' can '' height= '' 100 '' width= '' 100 '' > < /canvas > < br / > < input id= '' btn '' type... | Mulitiple mouseevent use in one time in javascript |
JS | I have a function like that : Do I have any guarantee that name , capacity , and port will be initialized one after the other ? Otherwise , the buffer will be read in the wrong order.I could of course fall back on : | parsers [ 1 ] = function ( buf ) { return { type : `` init '' , name : buf.readUTF8String ( ) , capacity : buf.readUInt32 ( ) , port : buf.readUInt16 ( ) } ; } parsers [ 1 ] = function ( buf ) { var ret = { type : `` init '' } ; ret.name = buf.readUTF8String ( ) ; ret.capacity = buf.readUInt32 ( ) ; ret.port = buf.read... | Are the elements of a javascript object initialized in a specific order ? |
JS | I would like to test if a logger increments correctly ( using Jest ) . Looking at the code below this means I would like check if the increment ( 1 ) ( meaning the content of the void myMethod ) is getting called.I tried three different Options . Every Option results in the messageActually either Option 1 or Option 2 i... | // myScript.tsimport dd from 'datadog-metrics ' ; export class MyClass { private bufferedMetricsLogger : dd.BufferedMetricsLogger ; constructor ( bufferedMetricsLogger : dd.BufferedMetricsLogger ) { this.bufferedMetricsLogger = bufferedMetricsLogger ; } public myMethod ( myInput : String ) : void { this.bufferedMetrics... | How to test void method with Jest |
JS | I have a great little hamburger navigation menu almost working , but there is some weird behavior that happens only after I resize the window twice . The hamburger button does what it should if I load the page when the window is narrow ( width < 800px ) , or if I load when wide ( width > 800px ) and resize to narrow . ... | // media query event handlerif ( matchMedia ) { var mq = window.matchMedia ( `` ( max-width : 800px ) '' ) ; mq.addListener ( function ( ) { WidthChange ( mq ) ; } ) ; WidthChange ( mq ) ; } ; // media query change /function WidthChange ( mq ) { if ( mq.matches ) { $ ( `` # hamburgerDiv '' ) .show ( ) ; $ ( `` .hamburg... | Why is my hamburger menu toggling twice instead of only once after two screen resizes ? |
JS | I 'm displaying a horizontal line using css : Can I space be insterted a specific position on this line ? So becomes | .horizontalLineBottom { border-bottom : solid # 6E6A6B ; border-width:1px ; } ______________________________________________ ______________________________ ___ | Insert space at position in border line |
JS | I am fairly new to html/javascript and I am trying to get a focus on to a text/word inside of a html element when user inputs values into a text box.so if the user inputs `` text '' into the input box , it should match the text and focus on to it | < input type= '' text '' id= '' search '' > < input type= '' button '' id= '' button '' onsubmit= '' searchKey '' value= '' Find '' > < div > < p > some text here < /p > < /div > | Trying to focus on text inside a html element by user input |
JS | Is there any real-time usage of this property from the javascript developer 's perspective ? | var func1 = function ( ) { } console.log ( func1.name ) ; // func1 | How useful is Function.name property ? |
JS | I spent a lot of time trying to catch a bug in my app . Eventually I set apart this piece of code which behavior seems very strange to me.What 's the reason behind it ? Why it acts so ? How to avoid this type of bugs in code ? | var Model = Backbone.Model.extend ( { myProperty : [ ] } ) ; var one = new Model ( ) ; var two = new Model ( ) ; one.myProperty.push ( 1 ) ; console.log ( two.myProperty ) ; //1 ! ! | Pushing to properties in Backbone |
JS | Have a look at this : jsFiddle.Assuming the expected result is what I expected ... Example 1When calling b ( ) , the property of an Object , this becomes the property 's Object , here it 's the parent a . It produces the expected result.Example 2eval ( ) is meant to adopt its execution context of where it is called , i... | var a = { b : function ( ) { console.log ( this ) ; } } // Example 1a.b ( ) ; // a// Example 2 eval ( ' a.b ( ) ' ) ; // a // Example 3setTimeout ( ' a.b ( ) ' , 100 ) ; // a// Example 4setTimeout ( a.b , 100 ) ; // Window// Example 5var c = a.b ; c ( ) ; // Window | Why does ` this ` change when passing the function argument as string or reference ? |
JS | I have the following code which gives a beep when the ( mobile ) device is nudged slightly : It works fine , but not at all when the device is locked . Is there any way I can detect this while the device is locked ? | let audio = new Audio ( 'ack.mp3 ' ) ; function handleMotionEvent ( event ) { let x = event.accelerationIncludingGravity.x ; let y = event.accelerationIncludingGravity.y ; if ( Math.abs ( x ) + Math.abs ( y ) > 2.2 ) { audio.play ( ) ; } } window.addEventListener ( `` devicemotion '' , handleMotionEvent , true ) ; | devicemotion does n't seem to register when device is locked |
JS | Is there a name for this ? Here 's an example of what I 'm trying to say : So obviously both i and j are set to 1 . But is there a name for this practice ? Also , in terms of good coding standards , is this type of thing generally avoided ? Can I also get an example or explanation of why it is/is n't good practice ? | var i = 0 ; var j = 0 ; i = j = 1 ; | In Javascript , is there a name for the following : variable = variable = value ; |
JS | I want to write a regexp that will filter any username which : Starts with number or letter ( not case sensitive ) Can include - but can not contain more than one in a rowexample u-s-e-r✔ us-er✔ us -- er✖Also username can not start with - or end with -example -user✖ user-✖It also needs to be at least 1 character ( lett... | ^ [ a-zA-Z\d ] ( ? : [ a-zA-Z\d ] |- ( ? = [ a-zA-Z\d ] ) ) { 0,38 } -username_username___us_ernameus_erusername-1user -- name132uname -- uname1234-username-user -- nameav34axc-1234567890A1234567890B1234567890C1234567890D Usernamea-aaBcBaC1-11-2-3-4q-1-2-3q-q-q-q-qusername123username123username31231234user-name13-13q1-... | Writing regular expression that will filter entered username |
JS | Today I came across the strange behaviour in Javascript . Below is the codereturns `` '' .Why it behaves so ? | return `` '' & & false | Javascript : Strange behaviour ` empty string ` AND ` false ` returns empty string |
JS | So , I 've read the MDN disclaimers and warnings , I 've read a great answer on the subject , but there 's still something I want to know . This question actually came from an answer I gave to another question , here.Let 's say I decide to do the dirty deed . Something that I will regret for the rest of my life . Somet... | let proto = Object.getPrototypeOf ( Function.prototype ) ; Object.setPrototypeOf ( Function.prototype , { iBetterHaveAGoodReasonForDoingThis : `` Bacon ! `` } ) ; //just to prove it actually workedlet f = ( function ( ) { } ) ; console.log ( f.iBetterHaveAGoodReasonForDoingThis ) ; // Quick , hide the evidence ! ! Obje... | Will a JavaScript environment eventually recover after changing the [ [ Prototype ] ] of an object ? |
JS | I was wondering if anyone has any ideas on how to make my code more streamlined so it 's not so heavy . | var t ; $ ( `` .sn-fresh '' ) .mouseenter ( function ( ) { $ ( `` .um-cat '' ) .hide ( ) ; clearTimeout ( t ) ; $ ( `` # ultra-menu , # um-fresh '' ) .fadeIn ( 600 ) ; } ) ; $ ( `` .sn-salt '' ) .mouseenter ( function ( ) { $ ( `` .um-cat '' ) .hide ( ) ; clearTimeout ( t ) ; $ ( `` # ultra-menu , # um-salt '' ) .fadeI... | Make jQuery code simpler |
JS | I am trying to write a program that takes an input ( library , authorName ) and returns the title of books the author wrote.The library looks like this : My code looks like this : The output looks like this : Bill Gates , The Road AheadThe problem : No matter what author I will input into searchBook it returns Bill Gat... | let library = [ { author : 'Bill Gates ' , title : 'The Road Ahead ' , libraryID : 1254 } , { author : 'Carolann Camilo ' , title : 'Eyewitness ' , libraryID : 32456 } , { author : 'Carolann Camilo ' , title : 'Cocky Marine ' , libraryID : 32457 } ] ; let library = [ { author : 'Bill Gates ' , title : 'The Road Ahead '... | Program does not enumerate in JavaScript |
JS | This may seem like a weird question , but I do not really see many use cases for useEffect in React ( I am currently working on a several thousand-lines React codebase , and never used it once ) , and I think that there may be something I do not fully grasp.If you are writing a functional component , what difference do... | // without useEffectconst MyComponent = ( ) = > { [ data , setData ] = useState ( ) ; if ( ! data ) fetchDataFromAPI ( ) .then ( res = > setData ( res ) ) ; return ( { data ? < div > { data } < /div > : < div > Loading ... < /div > } ) } // with useEffectconst MyComponent = ( ) = > { [ data , setData ] = useState ( ) ;... | When and why to useEffect |
JS | I have such JSON data : I need to select newest version of MacOS in this array . How to implement in better ? I 've tried to remove all alpha-numeric values and convert versions of mac to integers but it might not work in some situations ( for example 101213 will be bigger then 10135 ) . Will really appreciate your hel... | var jsondata = [ { data : 'MacOS Sierra 10.12.13 ' } , { data : 'MacOS Sierra 10.12.5 ' } ] ; | Javascript check for latest version of OS in JSON |
JS | Can you name an instance the same as its constructor name ? ? As it seems , this replaces the Function Object with the new instance ... which means this is a good Singleton.I have n't seen anyone using this , so I guess , there are downsides to this that I am unaware of ... Any thoughts ? | var myFunc = new function myFunc ( ) { } ; | Can you name an instance the same as its constructor name ? |
JS | Chrome on iOS appears to create an XMLHttpRequest object when you include an external JavaScript file . It seems to assign this object to a global variable with the identifier a , overwriting anything you may have already had in there.Test case : HTML file ( test.html ) : External JavaScript file ( test.js ) : The XMLH... | < ! -- ... -- > < script > var a = 1 ; // Value is not important for this demonstration < /script > < script src= '' test.js '' > < /script > < ! -- ... -- > setTimeout ( function ( ) { document.write ( a ) ; // [ object XMLHttpRequest ] a.onreadystatechange = function ( ) { document.write ( a.readyState ) ; // Alterna... | Can I stop Chrome from eating my global property ? |
JS | Ηello ! I hope this is an acceptable sort of question.Going through some code used for signal processing I came upon an odd function : This function is called towards the end of a fourier transform calculation to swap indexes in the real+imaginary pair of arrays : My question is : what the heck is kInd doing ? I 've ru... | let kInd = ( k1 , pow ) = > { let k2 = 0 ; let k3 = 0 ; for ( let i = 0 ; i < pow ; i++ ) { k3 = k1 > > 1 ; k2 = 2 * ( k2 - k3 ) + k1 ; k1 = k3 ; } return k2 ; } ; let fft = samples = > { let pow = Math.log2 ( samples.length ) ; // ` samples.length ` is expected to be 2^int // ... a bunch of code to generate ` rBuff ` ... | Odd function used for signal processing ? |
JS | In jQuery , is there another way to write this ? Version 1Version 2I 'm used to coding like this ... but I want to know if there are much effective , readable , cool way of writing it ... like toggling , chaining ... best practices I do n't know ^^I appreciate you sharing it ! ^^ | $ ( `` # date_filter-enable '' ) .click ( function ( ) { $ ( `` # search_dates '' ) .removeClass ( `` hidden '' ) ; } ) ; $ ( `` # date_filter-disable '' ) .click ( function ( ) { $ ( `` # search_dates '' ) .addClass ( `` hidden '' ) ; } ) ; $ ( `` input [ id^=date_filter- ] '' ) .click ( function ( e ) { var clicked =... | jQuery shortcuts / technique for toggling classes |
JS | Can someone help me in understanding the reason why someone would iterate when it 's value is equal to it ? for example i.e in the above code , what could be the reason for doing the same ? | let subStyle = { width : 300 , height : 50 , borderRadius : 20 , backgroundColor : theme.primaryBlue } ; subStyle = { ... subStyle , backgroundColor : theme.primaryWhite , borderWidth : 2 , borderColor : ' # 707070 ' } subStyle = { ... subStyle , backgroundColor : theme.primaryWhite , borderWidth : 2 , borderColor : ' ... | iterating and storing object equal to itself |
JS | I have an array of objects that looks like this : Using lodash how to transform it into something that looks like this : The logic is as follow : Every question has a combination of 2 choices where every choice is of different type example ( car and food ) .Combination of different types should occur only twice ( car ,... | [ { type : 'car ' , choices : [ 'audi ' , 'honda ' , 'bmw ' , 'ford ' ] , } , { type : 'drink ' , choices : [ 'soda ' , 'water ' , 'tea ' , 'coffee ' ] , } , { type : 'food ' , choices : [ 'chips ' , 'pizza ' , 'cookie ' , 'pasta ' ] , } ] [ { question : [ { drink : `` tea '' } , { car : `` bmw '' } ] } , { question : ... | JavaScript transform array of objects into another using lodash |
JS | Is there any difference between them ? I 've been using both the ways but do not know which one does what and which is better ? Is there any difference between defining these functions ? Something like i++ and ++i ? | function abc ( ) { // Code comes here . } abc = function ( ) { // Code comes here . } | which is the better way of defining a function ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.