lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
UPDATE : Many asked why not using [ arr [ 0 ] , arr [ 1 ] ] . The problem is I have to pass this array to a method , which I do n't have access Angular Material Table . And I do n't want to call the method over and over again . I already processed the arr array and I do n't want to process pointer array to reflect the ...
const arr = [ { prop : 3 } , { prop : 4 } , ] ; const pointer = [ arr [ 0 ] , arr [ 1 ] ] ; // I want pointer to point to be an array containing the first and second elements of arr arr.splice ( 0 , 0 , { prop : 1 } ) ; // arr = > [ { prop:1 } , { prop:3 } , { prop:4 } ] console.log ( pointer ) ; // [ { prop : 3 } , { ...
Javascript array referencing an array position ( not an element )
JS
As a C # programmer , I have a bit of a habit of making things private that can and should be private , and I always get a weird feeling when a JS type exposes all its private parts to me ( and that feeling is not 'aroused ' ) . Say I have a type that has a draw method , which internally calls drawBackground and drawFo...
Foo = function ( ) { this.draw ( ) ; } ; Foo.prototype.draw = function ( ) { this.drawBackground ( ) ; this.drawForeground ( ) ; } ; Foo.prototype.drawBackground = function ( ) { } ; Foo.prototype.drawForeground = function ( ) { } ; Foo = ( function ( ) { var constructor = function ( ) { this.draw ( ) ; } ; var drawBac...
Javascript : should I be hiding my implementations ?
JS
Given two Date objects , how to properly set the month of the first object to the month of another ? I 'm facing a task of copying day , month and year from one Date object to another . Copying day and year works as intended , the problem comes up when I 'm trying to copy the month.Using b.setMonth ( a.getMonth ( ) ) r...
let a = new Date ( 2018 , 1 , 12 ) ; let b = new Date ( ) ; console.log ( a ) ; console.log ( b ) ; console.log ( '==== ' ) ; console.log ( a.getMonth ( ) ) ; console.log ( b.getMonth ( ) ) ; b.setMonth ( a.getMonth ( ) ) ; console.log ( '==== ' ) ; console.log ( a.getMonth ( ) ) ; console.log ( b.getMonth ( ) ) ; b.se...
How to copy the month value from one Date object to another ?
JS
Can someone assist me - why we have this behavior in JS snippet ? Why only `` foo '' is printed ? fiddleEDITok , this is because of automatic semi-colon insertion , BUTdo we have some ways to force JS to not execute this cases ? I mean , can we do something that will throw error here ? EDIT2Looks like best suggestion i...
var foo = function ( ) { return { hi : console.log ( `` foo '' ) } } var foo1 = function ( ) { return { hi : console.log ( `` foo1 '' ) } } foo ( ) ; foo1 ( ) ;
JS Strange behavior
JS
I 'm looking at some code that looks likeOr in some other casesIs there any difference between these andAre there any circumstances where the behavior would be different ? ( For example , is the behavior different if this or someObj is null or is n't actually an object , or f is n't actually a function ? I ca n't think...
this.f.call ( this ) ; this.someObj.f.call ( this.someObj ) ; this.f ( ) ; this.someObj.f ( ) ;
Is there a difference between x.f.call ( x , ... ) and x.f ( ... ) ?
JS
I have a main stopwatch with 4 mini-stopwatches for each step . After a finished time , here is an example of how the timers should look : The mini-timers should add up to the main timer , as they do in this case . With my current timer , it always seems to be .02 milliseconds off , so they would add up to 00 : 14 . 55...
MAIN : 00 : 14 : 57 -- -- -- -- -- -- -- -- -- -MINI1 : 00 : 04 . 17MINI2 : 00 : 06 . 40MINI3 : 00 : 02 . 54MINI4 : 00 : 01 . 46 class Stopwatch { constructor ( opts ) { this.isOn = false ; this.time = 0 ; this.elem = opts.elem ; } start ( ) { this.offset = Date.now ( ) ; this.interval = setInterval ( ( ) = > this._upd...
Stopwatch with breakpoints not adding up correctly
JS
I have an object I created with this snip-it that looks like this : And this works fine : but this does notCould someone please tell me how to fix this or even what to call it when you chain methods like this ?
... var steps = new Array ( ) ; this.createStep = function ( ) { steps.push ( new step ( ) ) ; return steps [ steps.length-1 ] ; } ; this.getSteps = function ( ) { return steps ; } ; //returns Array this.removeStep = function ( pos ) { steps.splice ( parseInt ( pos ) , 1 ) ; } ; // integer possition zero base this.inse...
Stacking up methods in Javascript
JS
I 'm trying to create a Regex javascript split , but I 'm totally stuck . Here 's my input : I want the output array after the split ( ) to be ( I 've removed the \n for readability ) : My current regular expression is : This works , but there is one problem : the timestamps get repeated in extra elements . So I get : ...
9:30 pmThe user did action A.10:30 pmWelcome , user John Doe . ***This is a comment11:30 amThis is some more input . [ `` 9:30 pm The user did action A . `` , `` 10:30 pm Welcome , user John Doe . `` , `` ***This is a comment '' , `` 11:30 am This is some more input . '' ] ; var split = text.split ( /\s* ( ? = ( \b\d+ ...
Regular expression javascript split
JS
i know there has many answer for unique arraybut they ca n't handle with array of arraywhat i want issource arraythe returnarr-unique can handle object [ ] , but ca n't handle array of arraySet ca n't toofail code===================updatei create a module for this array-hyper-unique , but did n't use json stringify bec...
[ 1 , 0 , true , undefined , null , false , [ ' a ' , ' b ' , ' c ' ] , [ ' a ' , ' b ' , ' c ' ] , [ ' a ' , ' c ' , ' b ' ] , { a : { b : 2 } } , { a : { b : 2 } } , { a : { b : 3 } } , { a : { b : undefined } } , { a : { } } , { a : { b : 3 , c : undefined } } , ] [ 1 , 0 , true , undefined , null , false , [ ' a ' ...
Get all unique values in an array ( remove duplicates ) fot nest array / object
JS
I have object like this : I 'm trying to remove property from this object by using another object as selector . For example : So delete ( delSelector , myObject ) should return : Please note that I 'm not looking for solution using the `` .dot '' selector eg : delete ( 'first.sub.prop2 ' , myObj ) like shown in this th...
var myObj = { first : { sub : { prop1 : `` some text '' , prop2 : `` some more text '' } , sub2 : { prop1 : `` Something '' , prop2 : `` Something2 '' , } } , second : { stuff : `` More stuff ... lots of stuff '' } } var delSeletor = { first : { sub : { prop2 : `` '' } } } var myObj = { first : { sub : { prop1 : `` som...
JavaScript deep remove object property by using another object as selector
JS
Hi I am starting to learn reactjs . So after understanding the basics Im starting to work on database connectivity using reactjs . In the code Im trying to get the userId and Password to establish a DB connectivity and trying to list the tables available in the DB . In the Login.js I have create a form ( userId and Pas...
import React from 'react ' ; import TableContent from './tables ' ; class Login extends React.Component { constructor ( ) { super ( ) ; this.state= { showComponent : false , } ; // this.buttonClick = this.buttonClick.bind ( this ) ; } buttonClick ( event ) { event.preventDefault ( ) ; this.setState ( { showComponent : ...
Accessing the data from one component to another component
JS
There is some destructuring going on here : But , what does [ a ] : b do : what does the brackets with colon do ? In my case , a is supplied as one of the props with a string value .
const { [ a ] : b } = this.props
What does the es6 { [ a ] : b } destructuring mean ?
JS
In this view data mathjax is working well but when we add enter in textarea it is not going new line . when we post something like this
a ) Ab ) Bc ) Cthen it display a ) A b ) B c ) CI want to display it like in data-mathjax-binda ) Ab ) Bc ) Chow to solved this ? < div class= '' question-title-preview '' > < span data-mathjax-bind= '' question.titleDisplay '' > < /span > < /div >
how to render html view in data-mathjax-bind in angularjs
JS
I have following sorted array of numbers ( they can repeat e.g 21 ) And want to get following ( sorted ) array of strings with rangesfor consecutive numbers a , a+1 , a+2 , ... , a+n=b w must create string `` a-b '' e.g for 6,7,8 we want to get `` 6-8 '' , for `` alone '' numbers we want to get only that number e.g . f...
let a = [ 1,2,3,4,7,8,12,15,21,21,22,23 ] let r = [ `` 1-4 '' , '' 7-8 '' , '' 12 '' , '' 15 '' , '' 21-23 '' ] let a = [ 1,2,3,6,7,8,12,15,21,21,22,23 ] ; let right=a [ 0 ] ; let left=a [ 0 ] ; let result= [ ] ; for ( let i=1 ; i < a.length ; i++ ) { for ( let j=1 ; j < a.length ; j++ ) { if ( a [ i ] < a [ j ] ) resu...
Create string ranges from sorted array of integers
JS
I have a system simple tags box , the problem is that if I add the same word , Example : php , and php , the label is duplicated with the same word.Code complete.the only problem is the duplication of the label ( tags ) , to the add a word same like .
$ ( function ( ) { // DOM ready // : : : TAGS BOX $ ( `` # tags input '' ) .on ( { focusout : function ( ) { var txt = this.value.replace ( / [ ^a-z0-9\+\-\.\ # ] /ig , '' ) ; // allowed characters if ( txt ) $ ( `` < span/ > '' , { text : txt.toLowerCase ( ) , insertBefore : this } ) ; this.value = `` '' ; } , keyup :...
How to avoid duplication of tags ?
JS
My React app uses requires relative to the root of my JS file using Webpack 's resolve.root . I.e . my file structure contains the following : In AppContainer.react.js , I have : This works client-side . Now I 'm trying to make it isomorphic . If I require AppContainer.react.js in my server.js , it says components/App....
components App.react.jscontainers AppContainer.react.js import App from 'components/App.react ' ; css/html/js/ components/ App.react.js containers/ AppContainer.react.js main.js < - requires AppContainerpublic/server/ server.js < - requires AppContainer
Isomorphic React with Webpack 's resolve.root option
JS
I 'm trying to understand how to handle some events with javascript , in particular if a specific event is triggered the current function calls another function . At onLoad the javascript creates the first select the data from the first object . Then if I select the voice with value `` Iphone '' is called another funct...
//global objectsvar product = [ { name : `` Samsung '' } , { name : `` Iphone '' } , { name : `` Alcatel '' } , { name : `` Sony '' } ] var productPrice = [ { name : `` Samsung '' , price : 190 } , { name : `` Iphone '' , price : 290 } , { name : `` Alcatel '' , price : 65 } , { name : `` Sony '' , price : 330 } ] var ...
How to correctly handle a call function in a function with javascript
JS
I have three buttons that when clicking show and individual div but this is done in reactjsWhen I click any of the buttons it shows all bus , tram and train data - how do I get them to just show one thing at a time and making sure that the other states are closed . I am really missing something here and need a pointer ...
import React , { Component } from 'react ' ; export class ModeExtended extends Component { constructor ( ) { super ( ) ; this.busButton = this.busButton.bind ( this ) ; this.trainButton = this.trainButton.bind ( this ) ; this.tramButton = this.tramButton.bind ( this ) ; this.state = { isHidden : false , } } busButton (...
Creating show and hide sections with buttons in reactjs
JS
I have the following code : When I output usboxshadow to the console , I get what I should : ( the -webkit-box-shadow property ) However , when I retrieve the property with Jquery.css ( ) , I get a very different result : First , where did the extra 0px come from in each of the arguments ? Second , why is the rgba alph...
var oneHeight = Math.ceil ( 0.012*window.innerHeight ) .toString ( ) + '' px '' ; var usboxshadow= '' 0px `` +oneHeight+ '' 0px rgba ( 0,140,255,1 ) , 0px `` +oneHeight+ '' 25px rgba ( 0,0,0 , .7 ) '' ; console.log ( usboxshadow ) ; $ ( `` .unselected '' ) .css ( `` -webkit-box-shadow '' , usboxshadow ) ; 0px 20px 0px ...
-webkit-box-shadow not changing properly with javascript
JS
I have a button , when pressed has to call a function from an external php file and load it in a new page.When I click the `` SHOW '' button on my index.php page , it shows me the message hold in `` mesaj '' , but displays it in index.php page ( that I don ` t want ! ) .What I want to accomplish is when I click on the ...
< input type = `` button '' class= '' btn btn-primary '' id = `` show '' onClick = `` show ( ) '' value = `` SHOW '' / > function show ( ) { database ( ) ; $ sql = `` SELECT title FROM ` Articles ` `` ; $ titleSql = mysql_query ( $ sql ) or die ( `` Could not select articles : '' ) ; $ html = ' < html > < body > < div ...
How to set the href ?
JS
If I have the following code : I know it 's absolutely necessary to do : To free up myClassInstance and its data property for GC . However , what should I do with myobj.num and myobj.str ? Do I have to give them a value of null too ? Does the fact that they 're primitive change anything regarding GC ?
function MyClass ( ) { this.data = { // lots of data } ; } var myClassInstace = new MyClass ( ) ; var myobj = { num:123 , str : '' hello '' , theClass : myClassInstance } ; myobj.theClass = null ;
Is it necessary to nullify primitive values for grabage collection ?
JS
I 'm trying to run this regex but it stuck my console . Why ?
var str = `` Шедевры православной музыки - 20 золотых православных песен '' ; str.match ( /^ ( ( [ \u00C0-\u1FFF\u2C00-\uD7FF ] + [ ^a-z\u00C0-\u1FFF\u2C00-\uD7FF ] * ) + ) [ a-z ] + [ ^\u00C0-\u1FFF\u2C00-\uD7FF ] * $ /i ) ;
Why this code stuck node.js - Bug on Javascript ?
JS
I have made a customized control for the Wordpress Customizer and I would like to set my control inside a script ( Instafeed.js ) , to change the limit number.Following this answer this is how I did it so farFunctionsCould anyone tell me where is the mistake ? I 've been searching for this for a while .
< script type= '' text/javascript '' > var userFeed = new Instafeed ( { get : `` , tagName : `` , clientId : `` , limit : var imglimit = < ? php echo json_encode ( $ imglimit ) ; ? > ; , } ) ; userFeed.run ( ) ; < /script > $ wp_customize- > add_setting ( 'imglimit ' , array ( 'default ' = > `` , 'section ' = > 'sectio...
Using Wordpress Customizer in Javascript
JS
I was playing around with objects and constructors and stuff like that , and I was wondering if there was a way to bind a value to a variable based on how it was originally defined . I have the following code : typescriptI was wondering if there is a way , inside the set function of the $ this variable , to detect how ...
let cr = `` create '' , ap = `` apply '' , $ this = { set : ( prop , value ) = > { this [ prop ] = value ; } } ; function creator ( ) { this. $ = ( array : Object [ ] ) = > { array.forEach ( ( kp : Object ) = > { let key = Object.keys ( kp ) [ 0 ] ; let val = kp [ Object.keys ( kp ) ] ; $ this [ key ] = val ; creator.c...
Is there a way to force a javascript element to redefine itself based on how it was originally defined ?
JS
I have a function that joins an array of objects with a conditional separator.Usages : How can the above getSegmentsLabel function be written in a purely functional way without mutating variables ? We can use lodash functions .
function getSegmentsLabel ( segments ) { var separator = '- ' ; var segmentsLabel = `` ; var nextSeparator = `` ; _.forEach ( segments , function ( segment ) { segmentsLabel += nextSeparator + segment.label ; nextSeparator = segment.separatorUsed ? separator : ' ' ; } ) ; return segmentsLabel ; } var segments = [ { lab...
How to implement array joins in functional way ?
JS
I have this HtML and java script code below . Its suppose to do this : when i click on yes , the textarea box that says why i like cs is suppose to show up and when i click on no , vice versa . but its not doing it , any help ?
< ! DOCTYPE html > < html lang = `` en '' > < head > < meta charset= '' utf-8 '' > < title > forms.html < /title > < h1 > Welcome < /h1 > < link rel= '' stylesheet '' href= '' http : //code.jquery.com/ui/1.10.3/themes/smoothness/jqueryui.css '' > < script src= '' http : //code.jquery.com/jquery-1.9.1.js '' > < /script ...
How to toggle in Javascript / jQuery
JS
I am trying to remove a property from an object using the spread operator . Traditionally I have done this : In the above situation , the removed property ( prop1 ) will no longer exist within the rest object.Suppose there is a more intricate property that I would like to remove , such as an object within the object.Wh...
const original_object = { prop1 : 'string1 ' , prop2 : 'string2 ' } ; const { prop1 , ... rest } = original_object ; const original_object = { prop1 : 'string1 ' prop2 : { prop3 : 'string3 ' , prop4 : 'string4 ' } } const { *remove prop3 of prop2 only here* , ... rest } = original_object ; console.log ( prop3 ) ; // = ...
Removing targeted parameter from Object in ES6 using spread operator
JS
i am new at angularJS , i want to check my page is dirty or not . i know how to check dirty form but not whole page ( like i am using directive in this form ) .is there any way to check directive part is dirty or not ? like in my page i have directive for star rating . in that if i change rating then i want to check th...
< form name= '' reviewForm '' > < div class= '' row '' > < div class= '' form-group col-lg-12 col-md-12 col-sm-12 col-xs-12 '' > < div > < table class= '' rwd-table table-responsive table-bordered table-striped '' > < tbody > < tr data-ng-repeat= '' review in reviewModifyData.review.KeyAreaList '' > < td class= '' mywi...
Is there any way to check the whole page is dirty or not ?
JS
I 'm using a jQuery plugin , it gets data from an url , fetches , calculates and writes some data in a div.I want to copy this div contents to another div , when that functions do its work.for example : when i ran that code , i did n't have new contents in # div2 .
$ ( `` # div1 '' ) .myfunction ( ) ; // it gets and calculates data and adds to # div1 . it needs 2-3 seconds to be donevar contents = $ ( `` # div1 '' ) .html ( ) ; // when myfunction ( ) done , copy contents $ ( `` # div2 '' ) .html ( contents ) ;
when a function 's work is completed
JS
I have 4 input fields to let user input the importance ( rankings ) of these 4 companies in a specific Area , as shown below : The input fields are not required and should be integer from 1 to 4 ( suppose there are NO duplicates ) , user can not jump ranking which means the ranking need to be unique and continuous . Fo...
< table > < tr > < th > < /th > < th > Area 1 < /th > < /tr > < tr > < td > Company A < /td > < td > < input type= '' text '' name= '' text1 '' id= '' text1 '' > < /td > < /tr > < tr > < td > Company B < /td > < td > < input type= '' text '' name= '' text2 '' id= '' text2 '' > < /td > < /tr > < tr > < td > Company C < ...
jQuery - Implement unique continuous ranking
JS
While doing code reviews , I 've recently come across such kind of code blocks : Here pieces is an array of arrays . Note that due to certain constraints we can not await all Promises at once , hence this sort of chunking.In my feedback , I write that this appears to be an anti-pattern as we are also awaiting Promises ...
const promises = [ ] ; const data = [ ] ; for ( let piece of pieces ) { for ( let chunk of piece ) { promises.push ( execute ( chunk ) ) ; //execute returns a promise which is not yet fulfilled } data = await Promise.all ( promises ) ; } const data = [ ] ; for ( let piece of pieces ) { const promises = [ ] ; for ( let ...
How much is the performance overhead for awaiting an already fulfilled Promise ?
JS
Explain the problemSo i noticed that on using someElement.innerHTML the DOM Nodes count increases.I guess that the reference is killed but the memory is still allocated until the garbage collector deletes the object.Example ( HTML ) : Example ( JavaScript ) : What i tried so farI tried to use someElement.textContent.I ...
< html > < head > < meta charset= '' utf-8 '' > < link rel= '' stylesheet '' href= '' test.css '' > < script src= '' script.js '' > < /script > < /head > < body onload= '' startTimer ( ) '' > < div id= '' timeContainer '' > Time Goes Here < /div > < /body > < /html > var timer ; var body ; var oldTime = `` '' ; var tim...
Setting innerHTML increases HTML nodecount
JS
While reading code from a JS Editor ( Tern ) , I have come across various uses for the for-loop as seen in the snippets below : code snippet 1 @ lines 463-468 : code snippet 2 @ lines 97-100On the same note , I also have come across a for-loop with an empty body e.g : I am trying to understand what happens in code exec...
for ( ; ; ) { /* some code */ } for ( var i = 0 ; ; ++i ) { /* some code */ } for ( var p ; p ; p = someValue ) /* empty body */ ;
Understanding JavaScript for-loop better
JS
I am trying to create a menu that contains right triangles formed together to form a square . This is what I envision : This is what I hope to achieve : Can be dynamically generated through javascript.Scales to parentClip an image as background for each triangle ( can not be CSS ) Link to a site for each triangleUpdate...
< div class= '' menu-box '' > < svg id= '' menu '' style= '' border : black solid 1px '' width= '' 100 '' height= '' 100 '' viewbox= '' 0 , 0 , 100 , 100 '' > < polygon class = `` top '' points= ' 0,0 0,100 100,0 ' fill= '' none '' stroke= '' red '' / > < text x= '' -18 '' y= '' 68 '' fill= '' black '' transform= '' ro...
Create Triangle Menu
JS
I am wanting to experiment with some of the new ECMAScript 5 features . I would like to do some stuff similar to some code I found when googling : Is any of this possible at all yet ? ?
var obj = { } ; Object.defineProperty ( obj , `` value '' , { value : true , writable : false , enumerable : true , configurable : true } ) ; ( function ( ) { var name = `` John '' ; Object.defineProperty ( obj , `` name '' , { get : function ( ) { return name ; } , set : function ( value ) { name = value ; } } ) ; } )...
Is ECMAScript 5 available yet in any of the browsers ?
JS
How does javascript if condition determines its value ? , see this example : Why do I get to point //2 while 'bar ' at //1 is false ? As I can see bar value gets calculated in almost the same way the if condition , or it does n't ?
< script type= '' text/javascript '' > var bar = ( `` something '' == true ) ; alert ( bar ) ; // 1if ( `` something '' ) { alert ( `` hey ! `` ) ; // 2 } < /script >
how does if condition evaluates its value in javascript
JS
win points to window . NS is a temporary namespace for this post . I thought that if I wanted access to setTimeout , I could just copy over the function reference as such : However , execution will throw an error : To fix this error , I just did : However , I do n't know why this fixed it . I do n't know what language ...
NS.setTimeout = win.setTimeout ; NS_ERROR_XPC_BAD_OP_ON_WN_PROTO : Illegal operation on WrappedNative prototype object @ ... NS.setTimeout = function ( arg1 , arg2 ) { return win.setTimeout ( arg1 , arg2 ) ; } ;
How can function references be executed properly ( 1 ) ?
JS
I am playing with let in Node.JS ( requires the flags -- harmony and -- use-strict ) . As I understand , the let statement allows for block scoped declarations . Consider the following : How many block scopes are involved ? In which block scope does i live in ? Am I correct in thinking that for this example to work , t...
let a ; for ( let i = 0 ; i < 3 ; i += 1 ) { console.log ( i ) ; } { // block # 1 let a ; { // block # 2 ( contains ` i ` ) let i ; for ( i = 0 ; i < 3 ; i += 1 ) { // block # 3 console.log ( i ) ; } } }
Do for loops implicitly create a block ?
JS
I have the following code where I loop through img elements and want to randomly apply slideUp ( ) , slideDown ( ) , slideLeft ( ) and slideRight ( ) effects on them : with slideUp ( ) and slideDown ( ) it works fine , as they are jQuery methods . The problem occurs when i try to call my methods : slideLeft ( ) and sli...
var sliderEffects = [ `` slideUp '' , `` slideDown '' , `` slideLeft '' , `` slideRight '' ] ; function slideLeft ( ) { console.log ( `` slide left '' ) ; } function slideLeft ( ) { console.log ( `` slide right '' ) ; } function randomFrom ( items ) { return items [ Math.floor ( Math.random ( ) *items.length ) ] ; } //...
loop through img elements and randomly apply slide effects ( up , down , left , right )
JS
I read several articles on js inheritance already ( this one , this one , this one , etc . ) In this article from Mozilla , `` classic '' inheritance is shown as this : ( I uniformized examples ) However in this article I see : Moreover I have also seen this : And I also experimented and could n't find the use of const...
// inherit Basefunction Derived ( ) { ... } Derived.prototype = new Base ( ) ; < -- -- -- -Derived.prototype.constructor = Derived ; < -- -- -- - // inherit Basefunction Derived ( ) { ... } Derived.prototype = Object.create ( Base.prototype ) ; < -- -- -- -Derived.prototype.constructor = Derived ; Derived.prototype = B...
What is the correct prototype affectation in javascript inheritance ?
JS
I was under the impression that in order to get the value from < select > you essentially had to do this : But I ran into some code today that simply does document.getElementById ( 'my-select ' ) .value , which seems to work perfectly fine in Chrome and Firefox.Has this changed recently , or has it always been this way...
var sel = document.getElementById ( `` my-select '' ) ; var val = sel.options [ sel.selectedIndex ] .value ;
Get value of < select > the modern way ?
JS
I want to show a Persian variable , but it is displayed as individual letters س ر م ا ی ه instead of سرمایه . Can someone solve this ? Here 's my code : JSFiddle
function createFormula ( ) { var value = ' ` a*b/ ( 5+9 ) -6+8/9+9+ '' سرمایه '' /895+9+ ' + ' '' ' + ' c ' + ' '' ' + ' ` ' ; document.querySelector ( ' # formula ' ) .textContent = value ; MathJax.Hub.Queue ( [ `` Typeset '' , MathJax.Hub , 'formula ' ] ) ; } //show س ر م ا ی ه insted سرمایه < script src= '' https : ...
How to use Persian variable in MathJax ?
JS
I have a JavaScript function where someone can pass anything in , and I iterate over each of its keys using thesyntax . However , this results in an error if they pass a primitive ( string or number ) ; the correct behavior is for the function to act the same way on those as it would on an object with no keys.I can do ...
for x in obj
Check whether it 's safe to iterate over a JavaScript variable
JS
I 'm not new to JavaScript , but I never could understand a certain thing about its prototypal inheritance.Say we have Parent and Child `` classes '' ( functions Parent and Child that create objects ) . To be able to create Children , we first need toHere is the difficulty : by assigning the prototype to Child , we get...
Child.prototype = new Parent ( ) ; RedButton.prototype = new Button ( FOR_PROTO_ONLY ) ;
Prototypal inheritance in JavaScript : I do n't usually need calling the constructor of Parent object assigned to Child.prototype
JS
Need a little help with my jquery hereI want all my button with a name starting with `` my- '' and finishing with `` -press '' to have a `` click '' event.Buttons dynamically added to DOM should have the same event .
< input type= '' button '' id= '' my-button-x-press '' name= '' my-button-x-name-press '' / >
Jquery selectors
JS
For better knowledge of what a function is using , etc.Might also be faster for variable lookups if not accessing the global scope ? Suppose I have : in the global scope . Is it possible to wrap the function below such thatwould not have access to `` a '' and the global namespace and return
a = 5 ; b = 5 ; function go ( ) { console.log ( a ) ; } Uncaught ReferenceError : a is not defined
Is it possible to write a JS function with no access to global variables ?
JS
I have searched for this question and no existing answer seems to apply . Consider the following : What is the best way to sort the objects in this array by their date and still keep the `` english '' representation of their key ? Note : The key is used as a chart label.Everywhere I look array.sort is used , but that '...
[ { 'August 17th 2016 ' : [ 75 ] } , // 75 is the length of the array which contains up to 75 objects ... { 'August 1st 2016 ' : [ 5 ] } , { 'August 28th 2016 ' : [ 5 ] } , ... ] [ { 'August 1st 2016 ' : [ 5 ] } , { 'August 17th 2016 ' : [ 75 ] } { 'August 28th 2016 ' : [ 5 ] } , ... ]
How to sort array of objects where keys are dates
JS
This is my code : I thought there is no problem at all but SonarQube gives me a critical error : TypeError can be thrown as `` key '' might be null or undefined here . The word key in key.split ( ' _ ' ) is highlighted . Indicating variable key can be undefined/null here.I tried to pass in something like { [ undefined ...
const a = function ( obj ) { for ( let key in obj ) { if ( ! obj.hasOwnProperty ( key ) ) { continue ; } console.info ( key.split ( ' _ ' ) ) ; } } ; a ( { a_b : 123 } ) ;
Can For-In loop result an undefined or null ?
JS
Array of objects to be filteredI need to filter the array using multiple parameters using JS filter method.I have got a partial solution and could not get the expected output ( stuck on it ) .Here , the filter should also work with multiple values for a single attribute.Eg. , age=54,23 or model=Android , Apple etc.Simp...
[ { `` name '' : `` Apple '' , `` age '' : 24 , `` model '' : `` Android '' , `` status '' : `` Under development '' , } , { `` name '' : `` Roboto '' , `` age '' : 24 , `` model '' : `` Apple '' , `` status '' : `` Running '' , } , . . . . ]
How to create a multi-filter function to filter out multiple attributes using JS ?
JS
I have an array of objects , something like this : What needs to be accomplished is summing x from the array1 with x from the array2 that have the same index . Same goes for y and z . The final result should be a new array of objects containing the summed values . Something like this : Note : All arrays are the same le...
const data = [ // array1 [ { x : 1 } , { y:2 } , { z:3 } ] , [ { x : 1 } , { y:2 } , { z:3 } ] , [ { x : 1 } , { y:2 } , { z:3 } ] ] , [ // array2 [ { x : 1 } , { y:2 } , { z:3 } ] , [ { x : 1 } , { y:2 } , { z:3 } ] , [ { x : 1 } , { y:2 } , { z:3 } ] ] [ [ { totalXOne : 2 } , { totalYOne : 4 } , { totalZOne : 6 } ] ,...
Iterating over an array of objects , summing values with the same index , and returning a new array of objects
JS
Let 's say I make a call to local storage like so : And immediately afterwards , the user closes their web browser . What will be the result of Will the bigJsonObject be partially written ? Or will the whole write fail ? Is their any way to guarantee that there will be no partial writes ?
window.localStorage.setItem ( `` key '' , bigJsonObject ) ; window.localStorage.getItem ( `` key '' )
What happens if a write to localStorage is canceled ?
JS
Currently I have 3 arrays : I would like to merge all the array into one object instead and I tried using for loop but got an error instead : The end result I want to achieve :
var idArray = [ 13 , 24 , 35 ] ; var dateArray = [ 20181920 , 20181120 , 20172505 ] ; var contentArray = [ `` content1 '' , `` content2 '' , `` content3 '' ] ; var finalObj = { } ; for ( var y = 0 ; y < dateArray.length ; y++ ) { finalObj [ y ] .id = idArray [ y ] ; finalObj [ y ] .date = dateArrayArrange [ y ] ; final...
Combine Array ( s ) into single object in JavaScript
JS
Recently I started learning JavaScript through Nicholas C. Zakas ' book Professional JavaScript For Web Developers and I came across some questions that I could not solve by myself.As the title says , that 's all about named arguments and arguments object in JavaScript functions.E.g . we have this piece of code : The b...
function doAdd ( num1 , num2 ) { arguments [ 1 ] = 10 ; alert ( arguments [ 0 ] + num2 ) ; } doAdd ( 10 , 20 ) ; function doAdd ( num1 , num2 ) { arguments [ 1 ] = 10 ; num2 = 40 ; alert ( arguments [ 0 ] + arguments [ 1 ] ) ; } doAdd ( 10 , 20 ) ;
Named arguments and the arguments object in JavaScript
JS
From MDN ( https : //developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random ) : Math.random Returns a floating-point , pseudo-random number in the range [ 0 , 1 ) that is , from 0 ( inclusive ) up to but not including 1 ( exclusive ) , which you can then scale to your desired range.But then , ...
Math.min ( max , Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ) ; Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ;
Should I consider the 1 in 2^62 possibility of getting the excluded upper-bound when using ` Math.random ( ) ` ?
JS
Is Body.json ( ) faster than JSON.parse ( responseText ) for JSON received from fetch ? Theoretically Body.json ( ) can start decoding JSON as soon as it receives the first bytes from the ReadableStream from fetch . Is this how it works ? Or does it wait until all bytes are received ? So , is there a difference between...
const response = await fetch ( url ) ; const json = await response.json ( ) ; const response = await fetch ( url ) ; const text = await response.text ( ) ; const json = JSON.parse ( text ) ;
Is ` Body.json ( ) ` faster than ` JSON.parse ( responseText ) ` for JSON received from ` fetch ` ?
JS
This is a named function expression with the name test . Inside , I assign 123 to a variable , also named test . Then test is logged . The function prints its body in the console , but not 123 . What is the reason for such behavior ? Where does my explanation of function execution fail ? Start of function execution : t...
( function test ( ) { test = 123 ; console.log ( test ) ; } ( ) ) ;
Why can ’ t I assign values to a variable inside a named function expression with the same name ?
JS
1 : Why is the result of foo & & baz not 1 ? Because true is 1.2 : There are two pluses in the console.log ( foo + +bar ) ; , what 's the meaning of them ?
var foo = 1 ; var baz = 2 ; foo & & baz ; // returns 2 , which is true var foo = 1 ; var bar = ' 2 ' ; console.log ( foo + +bar ) ;
Could you explain these two javascript examples ?
JS
I am just curious if there is such a thing as a 'local scope object ' in JavaScript . If you invoke a function , it has a context ( this ) , which is the object it has been called on ( function f ( ) { return this ; } ; obj.f = f ; obj.f ( ) ; //returns obj ; ) , and a scope , which is created on every function call . ...
var globalScopeVar = 1 ; ( function ( ) { var localScopeVar = 2 ; } ) ( ) ; window.globalScopeVar ; // 1 ( function ( ) { var localScopeVar = 2 ; localScope.localScopeVar ; // 2 } ) ( ) ;
Local scope object
JS
I have this sort of lazy initialization code in my program : I understand that it is not safe , due to a possible race condition if I have the next code : getUserSomehow ( ) will be called two times instead of one.How to avoid this situation ?
let user = null ; let getUser = async ( ) = > { if ( ! user ) { user = await getUserSomehow ( ) ; } return user ; } ; // one place of the programlet u1 = await getUser ( ) ; ... // another place of the program running during getUserSomehow ( ) for u1 still has n't finishedlet u2 = await getUser ( ) ;
What is a canonical safe way of async lazy initialization in javascript ?
JS
I have an array with numbers in the range of 0 - 100 . I need to find all the same numbers and add 1 to them.my code worked well with arrays like [ 100 , 2 , 1 , 1 , 0 ] but when I came across this [ 100 , 6 , 6 , 6 , 5 , 5 , 5 , 5 , 5 , 4 , 4 , 4 , 3 , 3 , 2 , 2 , 2 , 2 , 1 , 1 , 0 , 0 ] my code let me down.Expected R...
const findAndChangeDuplicates = ( arr : any ) = > { for ( let i = arr.length - 1 ; i > = 0 ; i -- ) { if ( arr [ i + 1 ] === arr [ i ] & & arr [ i ] < = 5 ) { arr [ i ] += 1 ; } else if ( arr [ i - 1 ] === arr [ i ] & & arr [ i ] > = 5 ) { arr [ i ] -= 1 ; findAndChangeDuplicates ( arr ) ; } } return arr ; } ;
Find all the same numbers in the array
JS
I 'm writing a function that draws an image to a canvas element pixel by pixel . I noticed that there was a point , where the function suddenly took way longer to process than before - specifically going from a 338x338 pixel canvas to a 339x339 pixel canvas.Putting a similar looking function into jsfiddle , I get the s...
var ary1 = [ ] ; var ary2 = [ ] ; var mapData = { } ; var colorMatrix = { } ; for ( var i = 0 ; i < ( 338 * 338 ) ; i++ ) { ary1.push ( [ i , i + 2 ] ) ; } for ( var i = 0 ; i < ( 339 * 339 ) ; i++ ) { ary2.push ( [ i , i + 2 ] ) ; } //Light operationfunction test ( i , j ) { return Math.floor ( ( i * j + i + j ) / j )...
Very high processing difference between two almost similar while loops
JS
I 'm working on a placeholder function in jquery . Right now , I just want the form element to change its value to whatever its placeholder is . I tried the following code : But it does n't work . After testing it a little , I realized the problem is with using $ ( this ) in that context . How can I change this so that...
$ ( 'input : text ' ) .val ( $ ( this ) .attr ( 'placeholder ' ) ) ;
Can you use jQuery 's $ ( this ) in a one-line code to modify elements ?
JS
I have this little problem with jQuery . I want to remove an specific text from textarea . Check my codes : Textarea values : i tried this : The codes above only works if the text in each line is unique with no matching characters from other lines.Now the problem is the codes above removes the first letter from aa , in...
aaaaaa $ ( `` # id_list '' ) .val ( $ ( `` # id_list '' ) .val ( ) .replace ( `` a '' , `` `` ) ) ;
Replacing an exact text from textarea
JS
I have the following html code : I need to submit a form on the click of op 1 , op 2 , op 3 , op 4 , op 5 , op 6 . In other word , the last li , cant submit the form. ` In this the code Im trying to make this happen : But this .ranges ul li , will get all the li . How Can I make it ignore the last one ?
< div class= '' ranges '' > < ul > < li > Op 1 < /li > < li > Op 2 < /li > < li > Op 3 < /li > < li > Op 4 < /li > < li > Op 5 < /li > < li > Op 6 < /li > < li > Op 7 < /li > < /ul > gData.on ( 'click ' , '.ranges ul li ' , function ( e ) { gFilter.find ( 'form ' ) .submit ( ) ; } ) ;
Make Javascript function ignores the last li to submit form
JS
I do have Multilanguage support in my application and would like to implement translation for the angular material date picker . I have used dateAdapter class from material and set the values but while doing so my format of display is getting changes.Is anyone have faced same issue ?
export const MY_FORMATS = { parse : { dateInput : 'LL ' , } , display : { dateInput : 'ddd , MMM . D YYYY ' , monthYearLabel : 'MMM YYYY ' , dateA11yLabel : 'LL ' , monthYearA11yLabel : 'MMMM YYYY ' , } , } ; @ Component ( { selector : 'test ' , templateUrl : './test.html ' , styleUrls : [ './test.scss ' ] , providers ...
Change language of Datepicker with maintaining format of Material Angular 10
JS
I wanted to change the background-color on a div dinamically using jQuery 's css ( ) and it worked , but then I tried to add some delay to it , and for some reason it stopped working . What am I missing ? Here 's an MVC of it : HTML : JS : https : //jsfiddle.net/8eabfa2t/1/
< div id= '' nodelay '' > < /div > < div id= '' delay '' > < /div > $ ( `` # nodelay '' ) .hover ( function ( ) { $ ( this ) .css ( `` background-color '' , 'gray ' ) ; } ) ; $ ( `` # delay '' ) .hover ( function ( ) { setTimeout ( function ( ) { $ ( this ) .css ( `` background-color '' , 'gray ' ) ; } , 500 ) ; } ) ;
.css ( ) wo n't get applied after a delay
JS
Consider this example : My questions are : When the props consist of only onChange and no other elements , is the useCallback unnecessary in this case , since the entire component is already memo-ed based on onChange ? If we add an additional prop ( say a value for the initial value for the < input > ) , then I think u...
import React , { useCallback } from 'react ' ; type UserInputProps = { onChange : ( value : string ) = > void ; } ; const UserInput = React.memo ( ( { onChange } : UserInputProps ) = > { // Is this ` useCallback ` redundant ? const handleChange = useCallback ( ( event ) = > { onChange ( event.target.value ) ; } , [ onC...
useCallback necessary within React.memo ?
JS
If I do this in my < head > tag : And inside foo.js I do this : Would this code reliably instantiate the variable foo even though its included above the function definition , or should I move it instead to the bottom of the file , like this :
< script type= '' text/javascript '' src= '' foo.js '' > < /script > var foo = new Foo ( ) ; function Foo ( ) { //code here } function Foo ( ) { //code here } var foo = new Foo ( ) ;
Calling a function before it is declared , browser independent ?
JS
I think I am missing very important thing about javascriptIn the scenario above I have defined an object 'obj ' and created a method 'test ' for this object . Inside the method I have a local function ' y ( ) ' that is used by the 'click ' event attached to the button . Also the click event is being attached in the ano...
var gl = 10 $ ( document ) .ready ( function ( ) { var obj = { } obj.test = function ( ) { gl++ var lc = gl function y ( ) { alert ( 'local = ' + lc ) } ( function ( ) { var k = lc + 1 $ ( ' # button ' ) .click ( function ( ) { alert ( 'local anonymous = ' + k ) y ( ) } ) } ) ( ) ; } obj.test ( ) $ ( ' # button ' ) .of...
What happens to local functions referenced in the events in Javascript ?
JS
Scenario : I need to plot data in Zingchart from a CSV that will have a fixed number of columns ( 37 ) . This CSV has a header that will define the legend of the graph.Problem : If the number of elements I define in the header is less than 10 ( including the X - Axis name ) then everything is good . The first nine colu...
Sample graphTimes|Line_1|Line_2|Line_3|Line_4|Line_5|Line_6|Line_7|Line_8|Line_9| '' Line_10 '' `` Line_11 '' Line_12 Line_13 Line_14 Line_15 Line_16 Line_17 Line_18 Line_19 Line_20 Line_21 Line_22 Line_23 Line_24 Line_25 Line_26 Line_27 Line_28 Line_29 Line_30 Line_31 Line_32 Line_33 Line_34 Line_35 Line_361218604835|...
Zingchart does n't plot correctly a CSV with more than 10 columns
JS
is there any way i can mimic javascripts loose variable handling in php ? for example , in php i have to writewhereas in javascript this would condense todoesnt seem like THAT much of a difference but it adds up
$ instituteID = ( isset ( $ p [ 'regInstituteName ' ] ) & & isset ( $ p [ 'regInstituteName ' ] [ 'ID ' ] ) ) ? $ p [ 'regInstituteName ' ] [ 'ID ' ] : null ; instituteID = p.regInstituteName & & p.regInstituteName.id || null ;
is there a php equivalent to javascripts a = b & & b.c || d
JS
The ProblemI am creating a game using the HTML5 Canvas , the game has a main menu , the main menu has multiple buttons for you to choose . I am finding it difficult and confusing how I would , for example if the user presses the 'Play ' button , to show the game . Here is an image of the main menu : The QuestionThe que...
< html > < head > < title > Sean Coyne < /title > < /head > < body onload= '' start_game ( ) '' > < body > < div style id= '' canvas '' > < canvas id= '' myCanvas '' style= '' border:5px solid # 410b11 '' height= '' 320 '' width= '' 480 '' > < p > Your browser does not support HTML5 ! < /p > < /canvas > < script type= ...
different pages in a canvas game
JS
What is the most efficient and/or most readable way to write a function that takes in an array and returns the degree of multi-dimensionality of that array . For now it can be assumed that the arrays only contain primitive types . Example .
var arr = [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] function findDim ( a ) { //logic goes here } findDim ( arr ) ; // returns 2
Find the dimensionality of a javascript array
JS
I am trying to temporary modify the currentTarget property of an event with vanilla javascript.My main goals would be to have a very fast implementation as events fire rapidly , and not to change the original event or at least to revert the original event back to it 's original state once the operation is done.Unfortun...
// Trigger event for demonstration // in a real scenario that would be caused by a uservar event = new Event ( 'demo ' ) ; document.documentElement.addEventListener ( 'demo ' , eventHandler1 , false ) ; document.documentElement.addEventListener ( 'demo ' , eventHandler2 , false ) ; document.documentElement.addEventList...
What is the best way to alter a native browser event ?
JS
As JavaScript developer I 'm new to type checking and I struggle to understand why this simple code is not working : What I 'm trying to achieve here is to have a method that accepts interface . This however gives me error : Can not call 'printAnimal ' with 'buddy ' bound to 'animal ' because string literal 'dog ' [ 1 ...
type Animal = { id : number , name : string , type : 'dog ' | 'cat ' } ; type Dog = { id : number , name : string , type : 'dog ' , color : string } ; function printAnimal ( animal : Animal ) : string { return ` $ { animal.type } : $ { animal.name } ` ; } const buddy : Dog = { id : 1 , name : 'Buddy ' , type : 'dog ' ,...
Flowtype extend object type
JS
I 'm writing a function to extend a number with sign to a wider bit length . This is a very frequently used action in the PowerPC instruction set . This is what I have so far : value is the integer input , from is the number of bits that the value is using , and to is the target bit length.What is the most efficient wa...
function exts ( value , from , to ) { return ( value | something_goes_here ) ; } exts ( 0b1010101010 , 10 , 14 )
Fastest way to create this number ?
JS
This is one thing I was wondering for a long time . But first example code for bothType AType BI saw both in lots of tutorials , examples and libraries ( subjective Type A in the older ones ) . For me it is more comfortable to use Type A especially in large classes , because you have to write less code . But as I know ...
var JavaScriptClass = function ( ) { } ; JavaScriptClass.prototype = { myMethodOne : function ( ) { } , myMethodTwo : function ( ) { } } ; var JavaScriptClass = function ( ) { } ; JavaScriptClass.prototype.myMethodOne = function ( ) { } ; JavaScriptClass.prototype.myMethodTwo = function ( ) { } ;
Javascript difference between MyClass.prototype = { } and MyClass.prototype.method
JS
Getting Unexpected `` . '' from jslint ( http : //jslint.com/ ) on this code : Why does jslint have a problem with the || operator to force an empty string so a replace can be performed without causing an error , in case foo is passed in as undefined ? This passes : I know it 's opinion based and I can ignore it , etc ...
function test ( foo ) { `` use strict '' ; return ( foo || `` '' ) .replace ( `` bar '' , `` baz '' ) ; } function test ( foo ) { `` use strict '' ; var xFoo = ( foo || `` '' ) ; return xFoo.replace ( `` bar '' , `` baz '' ) ; }
Why 'Unexpected `` . '' ' when using || operator for a default value in parenthesis
JS
In javascript you can define a return function when you do string replacements : This few lines of code allow me to create a very neat template system . The regular expression matches all the `` { { something } } '' strings inside the text variable and the return function matches if something is inside the object data ...
function miniTemplate ( text , data ) { return text.replace ( /\ { \ { ( .+ ? ) \ } \ } /g , function ( a , b ) { return typeof data [ b ] ! == 'undefined ' ? data [ b ] : `` ; } ) ; } text = `` Hello { { var1 } } , nice to meet { { var2 } } '' ; data = { var1 : `` World '' , var2 : `` You '' } //result = > `` Hello Wo...
String replace in PHP with return function
JS
On the `` Google+ Sign-In for server-side apps '' help page , in `` Step 3 : Include the Google+ script on your page '' the following snippet is suggested : Now , what the second SCRIPT seems to do : create a new SCRIPT tag , with static sourceinsert it immediately , before the first SCRIPT tag in the file.Now , my que...
< ! -- The top of file index.html -- > < html itemscope itemtype= '' http : //schema.org/Article '' > < head > < ! -- BEGIN Pre-requisites -- > < script src= '' //ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js '' > < /script > < script type= '' text/javascript '' > ( function ( ) { var po = document.createEle...
Why insert a static JS dynamically ?
JS
After some time of `` development '' of the JavaScript game , I 've came to a great idea , or so it seemed / sounded.I was thinking of creating an entity which would represent lava . That lava would move in a specific direction , using : where is var acrotchar = { `` - '' : Lava } ; .The whole code can be seen here or ...
function Lava ( pos , ch ) { this.pos = pos ; this.size = new Vector ( 1 , 1 ) ; if ( ch == '- ' ) { this.speed = new Vector ( 3 , 0 ) } } var LEVELS = [ [ `` x x '' , `` xx x '' , `` xxx x x '' , `` xx ! xx x ox '' , `` x ! ! ! x x xx '' , `` xx ! xx x x '' , `` x xvx x x '' , `` x xx x '' , `` x x x '' , `` xx x x ''...
How could I achieve the effect of `` lava '' leaving traces
JS
I find my self doing this a lot : Is there a better and less repetitive way of doing a task like this ? Like toggle a class . Btw , only one element can be selected at a given time.Thanks .
$ ( document ) .on ( `` click '' , '' li '' , function ( ) { $ ( `` .selected '' ) .removeClass ( `` selected '' ) ; // Remove any old selected $ ( this ) .addClass ( `` selected '' ) ; // Apply selected to this element } ) ;
Toggle between selected classes
JS
Suppose the page below is loaded from https : //127.0.100.1 . The page makes an XMLHttpRequest to http : //127.0.100.2 . This seems like mixed content : The page is loaded over a secure connection and a resource is loaded over an insecure connection . Mixed content should be blocked by the browser . Yet , the page belo...
< html > < body > < img id= '' dst '' / > < script > let xhr = new XMLHttpRequest ( ) ; xhr.open ( 'get ' , 'http : //127.0.100.2/img.jpg ' ) ; xhr.responseType = 'blob ' ; xhr.onload = function ( ) { document.getElementById ( 'dst ' ) .src = URL.createObjectURL ( xhr.response ) ; } xhr.send ( ) ; < /script > < /body >...
Mixed content via XMLHttpRequest not blocked
JS
What does that get within the object do ? Is that a method or property or something else ? How does it work or how it set property or method to object ? Will i fall into trouble if i simply ignore the use of get and set ? Are there more advantages in using get and set than simply defining property without there use.Wha...
var o , d ; o = { get foo ( ) { return 17 ; } } ; d = Object.getOwnPropertyDescriptor ( o , `` foo '' ) ; // d is { configurable : true , enumerable : true , get : /*the getter function*/ , set : undefined }
Creating properties in literal object
JS
I am building a site that allows one to search for a beer and it returns data about that beer . The user clicks the search button , and it runs the http request I have setup on a service . All displays fine . But what I am trying to do is move my search form from the displaying component , to be inside the navbar . How...
@ Component ( { selector : 'app-home ' , templateUrl : './home.component.html ' , styleUrls : [ './home.component.css ' ] } ) export class HomeComponent implements OnInit { constructor ( private beerSearchService : BeerSearchService ) { } beerName : string ; beers : { } ; selectedBeer : { } ; searchBeer ( beerName ) { ...
Searchbar inside navbar calls an HTTP request , want returned data to populate in another component
JS
I use new Image ( ) to create a new image element . When I set the 'src ' attribute , a network request will be triggered at once . Why ? Is there any documentation that explains it ? The following cases : Case 1 : Case 2 : Case 3 : In case1 and case2 , a network request will be triggered at once.In case3 , if I do n't...
var img = new Image ( ) ; img.src = 'http : //someurl.png ' ; var imgStr = ' < img src= '' http : //someurl.png '' > ' ; var div = document.createElement ( 'div ' ) ; div.innerHTML = imgStr ; var script = document.createElement ( 'script ' ) ; script.src = 'http : //someurl.js ' ; // document.body.appendChild ( script ...
Why does `` new Image ( ) '' trigger a network request at once but `` createElement ( 'script ' ) '' does not ?
JS
I 'm using the opentok SDK for video chatting , and I need to create sessions . It 's pretty straightforward , and that part 's working fine . This is all being done in node.js , server side.The issues is - and it 's mostly cause I still do n't quite get var scopes ( especially with anonymous functions and closures ) -...
function generateSession ( session ) { var session= '' ; opentok.createSession ( function ( error , sessionId ) { if ( error ) { throw new Error ( `` Session creation failed . `` ) ; } session = sessionId ; } ) ; return session ; }
Variable in parent scope not getting altered in anonymous function
JS
I am using this color wheel picker , and I 'm trying to add a div as the dragger instead of having it embedded in the canvas . I got it working thanks to these answers.The problem is , the dragger is a bit off from the cursor . The obvious solution would be to just subtract from the draggers left and top position . Lik...
dragger.style.left = ( currentX + radiusPlusOffset - 13 ) + 'px ' ; dragger.style.top = ( currentY + radiusPlusOffset - 13 ) + 'px ' ; var b = document.body ; var c = document.getElementsByTagName ( 'canvas ' ) [ 0 ] ; var a = c.getContext ( '2d ' ) ; var wrapper = document.getElementById ( 'wrapper ' ) ; var dragger =...
Position div at exact cursors location
JS
Say I have a Parent component which renders a set of Child components . When hovering one of those Child component , I wish to highlight ( bg color ) the Child components that belong in the same group.See code below , each Child has a group property : https : //jsfiddle.net/69z2wepo/53442/If I hover Child with id prope...
const Parent = React.createClass ( { render ( ) { const rows = [ ] ; let group = 1 ; for ( let i = 1 ; i < = 12 ; i++ ) { rows.push ( < Child key= { i } id= { i } group= { group } / > ) ; if ( i % 3 === 0 ) { group++ ; } } return ( < ul > { rows } < /ul > ) ; } } ) ; const Child = React.createClass ( { render ( ) { ret...
How to select a group of children from the parent ?
JS
Now , I 'm new to web programming , javascript in particular . I 'm trying to write a script that will update the image on a webpage and its text when the user clicks the image . Here 's the code : Probably not the best way to do this , but this code will work at first . However , when I click the third image to go bac...
//Images arrayimgs = Array ( `` test1.jpg '' , `` test2.jpg '' , `` test3.jpg '' ) ; //Names arraynames = Array ( `` Test1 '' , `` Test2 '' , `` Test3 '' ) ; //Holds how many times our page has been clickedvar click = 0 ; //Another click varvar click2 = 0 ; //change function function change ( ) { //Get the ID of 'nam '...
Text becomes undefined when going through an array
JS
I wrote the following code in Javascript.In both cases i got value of a as undefined .Why a is undefined even after I called set ( ) ?
function main ( ) { this.a ; this.set = function ( ) { a = 1 ; } } var l = new main ( ) ; alert ( `` Initial value of a is `` + l.a ) ; l.set ( ) ; alert ( `` after calling set ( ) value of a is `` + l.a ) ;
Class and scope in Javascript
JS
my question is actually one of understanding - I have a working solution , I just do n't understand how it works.Okay , so - what I 'm trying to do is adding a setTimeout in a loop , and passing a changing value through it . Example : If I understood correctly , this doesnt work because Javascript does not ( like PHP )...
for ( i=0 ; i < 11 ; i++ ) { setTimeout ( `` alert ( i ) '' ,1000 ) ; } for ( i=0 ; i < 11 ; i++ ) { setTimeout ( function ( x ) { return function ( ) { alert ( x ) } ; } ( i ) ,1000 ) ; }
Variable Global Scope understanding questions
JS
I have an ajax call that returns a HTML fragment . I am trying to select a div in that fragment before rendering.An example of the HTML : Now the problem : Is this a bug or am I doing something wrong ?
< div class= '' event-detail repBy-container '' > < div class= '' copy '' > ... .. < /div > < div class= '' links '' > ... . < /div > < div class= '' contacts '' > < div class= '' name-brand '' > ... . < /div > < div class= '' details '' > ... . , < a href= '' mailto : ... @ ... . '' > ... < /a > < /div > < /div > < /d...
Possible JQuery class selector bug
JS
Defining clusterAny group of cubes of the same color , touching face planes , not their corners . A cluster would form a solid geometric shape.To help visualize the problemLet 's assume each one of these Legos is 1x1 units large.In a simplified code example - let 's look at a 2x2x2 mesh made of 1x1x1 cubes : Each cube ...
var mesh = [ // First layer ( x , y , z ) new THREE.Vector3 ( 0 , 0 , 0 ) , new THREE.Vector3 ( 0 , 0 , 1 ) , new THREE.Vector3 ( 1 , 0 , 0 ) , new THREE.Vector3 ( 1 , 0 , 1 ) //Second layer ( x , y , z ) new THREE.Vector3 ( 0 , 1 , 0 ) , new THREE.Vector3 ( 0 , 1 , 1 ) , new THREE.Vector3 ( 1 , 1 , 0 ) , new THREE.Vec...
In a mesh made of cubes with different colors , how do I find the matching clusters ?
JS
I am using the autocompleter jquery-textcomplete in my web app . It 's working fine for English and Russian letters . But it is not working for certain special letters such as `` ҷ '' .Code : Here the words 'тоҷик ' and 'english ' are working but 'ҷаҳон ' is not . How can I fix this ? I need the following letters to wo...
$ ( '.form-control ' ) .textcomplete ( [ { words : [ 'тоҷик ' , 'ҷаҳон ' , 'english ' ] , match : / ( ^| [ ^\wа-яёҷ ] ) ( [ \wа-яё ] { 2 , } ) $ /i , search : function ( term , callback ) { callback ( $ .map ( this.words , function ( word ) { return word.indexOf ( term ) === 0 ? word : null ; } ) ) ; } , index : 2 , re...
Why do UTF-8 characters not work in jquery textcomplete ?
JS
Possible Duplicate : How can I merge properties of two JavaScript objects dynamically ? I have two objects a and b defined like this : What I want now is to create another object which will get the properties of a and b , like this : Note that a and b need to stay the same.Any idea of how to do this ?
a = { a : 1 , af : function ( ) { console.log ( this.a ) } , } ; b = { b : 2 , bf : function ( ) { console.log ( this.b ) } , } ; c = { a : 1 , af : function ( ) { console.log ( this.a ) } , b : 2 , bf : function ( ) { console.log ( this.b ) } , }
Create an object based on 2 others
JS
I have three same items in the DOM . Exactly what I mean is a wobbling line < span class= '' caret '' > < /span > Scenario : I click on the first < span class= '' caret '' > < /span > gets the class `` open '' , and the rest still has only `` caret '' . I click on the second < span class= '' caret '' > < /span > gets t...
< ul > < li class= '' nav-item-1 '' > < a href= '' # '' > ITEM 1 < /a > < span class= '' caret '' > < /span > < /li > < /ul > < ul > < li class= '' nav-item-2 '' > < a href= '' # '' > ITEM 2 < /a > < span class= '' caret '' > < /span > < /li > < /ul > < ul > < li class= '' nav-item-3 '' > < a href= '' # '' > ITEM 3 < /...
How to add class to only one of multiple same elements
JS
How can I make a function run after a certain element has finished animating ? It 's a slide-down like animation , the element is hidden and when something is clicked , it will become visible by sliding its contents down ( +height ) .I have no control over the animation function on that element , so I ca n't use the ca...
$ ( '.trigger ' ) .click ( function ( ) { // < -- `` trigger '' will make the element animate setTimeout ( myfunction , 500 ) ; } ) ;
Event after a div has finished animating ?
JS
I am making a calculator but ... I can put two dots on my first number , but I can not put a dot on my second number . I am missing something but do n't know what . I have tried different things but nothing worked ... Maybe I have to try another way to do it or I am missing some condition for the dots . And the other t...
function insert ( num ) { const lastChar = document.form.textview.value ; if ( ( ! document.form.textview.value || isNaN ( lastChar ) ) & & isNaN ( num ) ) { return `` ; } document.form.textview.value += num ; } ; function equal ( ) { let exp = document.form.textview.value ; if ( exp ) { document.form.textview.value = ...
Why ca n't I put more then one dot in my JS calc
JS
I 'm using heap snapshots to debug a potential memory issue . As the documentation indicates objects are shown in this format : Where NumericIdentifier is : This is an object ID . Displaying an object 's address makes no sense , as objects are moved during garbage collections . Those object IDs are real IDs — that mean...
ObjectConstructorName @ NumericIdentifier ObjectConstructorName @ 10001ObjectConstructorName @ 10002
Are heap snapshot identifiers guaranteed to be monotonically increasing ?