lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I 'm having a hard time to get promises to work with the right this scope inside prototypes.Here is my code : Whenever I run the tests I get } ) ; I get the following error : I now that $ q in strict mode sets the this inside then to undefined . I tried using bind ( this ) in multiple places but not luck ... Any ideas ...
'use strict ' ; angular.module ( 'testApp ' ) .factory ( 'UrlSearchApi ' , function ( $ resource , URL_SEARCH_API , PAGE_SIZE , $ q ) { var resource = $ resource ( URL_SEARCH_API ) ; resource.Scroll = function ( ) { return this.reset ( ) ; } ; resource.Scroll.prototype.reset = function ( ) { this.visibleItems = [ ] ; t...
Chained promises and prototype ` this `
JS
Do you know why this code compiles and what is something ?
function Box ( ) { something : { alert ( 1 ) ; } } var box = new Box ( ) ;
Weird JavaScript syntax I 've never used before , but it works
JS
So , I was searching for some answer to this question and found that while importing , 'React ' does n't need to be in { } as it is the default export and not a named export , Well that 's correct , but I have also seen that while importing a default export , we could use any name for it on import . But in this case , ...
import React from 'react ' ; import Somename from 'react ' ;
If 'React ' is the default export from 'react ' , Why ca n't we use some other name instead of 'React '
JS
How do I go about re-arranging my array to by organized by shirt size : Desired output :
[ { shirt_id : 1 , size : `` small '' } , { shirt_id : 1 , size : `` medium '' } , { shirt_id : 1 , size : `` large '' } , { shirt_id : 2 , size : `` medium '' } , { shirt_id : 3 , size : `` large '' } ] ; [ [ 1 , { size : `` small '' } , { size : `` medium '' } , { size : `` large '' } ] , [ 2 , { size : `` medium '' ...
Group array of items by their distinct id
JS
I 'm new to React and I 'm doing my best to put together an app , so I 've created two main sections and I 'm at a point where I would like to combine them , but I 'm not exactly sure how to go about it.Here is the error I 'm getting : TypeError : Can not read property 'openSidebar ' of undefinedand it points to this c...
// Sidebar button and opening of sidebar// main function created to open sidebar buttonimport React from 'react ' ; import { FaBars } from 'react-icons/fa ' ; import { useGlobalContext } from './context ' ; const Home = ( ) = > { /*const data can setup data form each button under sidebar */ // < -- -- - ERROR HERE cons...
React Components from Separate App not integrating into Main App
JS
Furthermore , variables can be passed into the anonymous wrapper to localize commonly accessed global variables , such as window , document , and jQuery ... What is the point of this localisation if those are globally accessible anyway ?
var module = ( function ( window , document , $ ) { // module stuff } ) ( window , document , jQuery ) ;
Why do we localize global libraries/references ?
JS
.css ( `` zoom '' ) is not working with Firefox and IE , but works fine on Chrome.my code works only on chrome :
//ZoomIn Button $ ( '.zoom -- actions .zoom-in ' ) .on ( 'click ' , function ( ) { if ( $ ( `` .img-zoom '' ) .css ( `` zoom '' ) ==1 ) { $ ( `` .img-zoom '' ) .css ( `` zoom '' , `` 125 % '' ) ; } else if ( $ ( `` .img-zoom '' ) .css ( `` zoom '' ) ==0.75 ) { $ ( `` .img-zoom '' ) .css ( `` zoom '' , `` 100 % '' ) ; }...
Firefox : Is there any alternative to replace .css ( `` zoom '' )
JS
Is there an option to not create an object with particular condition within constructor , e.g .
function Monster ( name , hp ) { if ( hp < 1 ) { delete this ; } else { this.name = name ; } } var theMonster = new Monster ( `` Sulley '' , -5 ) ; // undefined
not to create an object with new Constructor
JS
I am trying to choose a library for my project which provide data binding and DOM management features . Comparing multiple libraries I ended up with Inferno and Svelte . I noticed evaluate script time of Svelte is higher than the other libraries ( Please refer attached image ) . In the sample I have rendered a 100 x 15...
< style > table , td , tr { border : 1px solid black ; } < /style > < script > import { officedatabase } from '../../../data_generator/sampleGridData/initialloaddata.js ' ; < /script > < table > { # each officedatabase as row } < tr > { # each row as cell } < td > { cell } < /td > { /each } < /tr > { /each } < /table >...
Svelte 'evaluate script ' time is appearing higher compare to inferno , preact
JS
We can trigger vibration on supported devices like so : But does the API support any access to user-defaults ? In other words , is it possible to get the vibration duration from the OS ? So when a user would normally press a button when using the device , get that vibration duration ( if any ) ?
navigator.vibrate ( 50 ) ;
Get user-defined vibration duration
JS
I have some issues with targeting dynamically created elements with JavaScript.Issue 1Shortened JavaScript code:1 : Now I want to make an event on my < nav > . How do I get the event to target # lightbox nav a instead of just # lightbox nav ? I 've tried many things , like this : And this : Issue 2Shortened JavaScript ...
var lightbox = document.createElement ( 'div ' ) , nav = document.createElement ( `` nav '' ) , imga = document.querySelectorAll ( `` .gallery a '' ) ; for ( i = 0 ; i < imga.length ; i++ ) { imga [ i ] .addEventListener ( `` click '' , function ( ) { document.body.insertBefore ( lightbox , document.body.firstChild ) ;...
JavaScript issues regarding events for dynamically created HTML
JS
Can anyone tell me why the following statement evaluates to false ? It does the same thing in Javascript and C++ .
bool myBoolean = .6 + .3 + .1 == .1 + .3 + .6 ; // false
C # strange behavior with + operator
JS
Having the following pice of code ... Why does Promise.all ( ) by itself calls my .then ( ) proto function on the Array ? Of course it must call .then ( ) for each of the elements in the array . That ’ s obvious . But what is the purpose of doing it over the Array itself ? This behavior is happening on V8To consider : ...
const array = [ Promise.resolve ( 1 ) , Promise.resolve ( 2 ) , Promise.resolve ( 3 ) ] ; Array.prototype.then = function ( ) { console.log ( 'Why does this gets triggered ? ' ) ; } Promise.all ( array ) .then ( result = > console.log ( result ) ) Promise.all ( array )
Why does Promise.all ( ) tigger Array.prototype.then if defined ?
JS
I 'm learning Node.js and trying to properly use the mysql2 module . Because of this , I have recently started researching about promises.I 'm writing a kind of `` library '' , so I can practice all these topics , and while doing that , I got into a problem with promise chaining I ca n't really understand . Any help is...
query ( ) { let p = new Promise ( ( resolve , reject ) = > { resolve ( `` Hello world '' ) } ) ; p.then ( data = > { console.log ( `` Hello world a second time ! `` ) ; } ) .then ( data = > { console.log ( `` Hello world a third time '' ) } ) return p ; } DBObject.query ( ) .then ( ( data ) = > { console.log ( `` Hello...
How promises and promise chaining works ? [ Problem with code ]
JS
I 'm using angular-fullstack generator to develop my project . When I try to create a new route using the command ( I 've installed uiRouter ) : All the files are created successfully . But whenever I try to open that route , I get redirected back to the home page . The config is autogenerated like this : search.jssear...
yo angular-fullstack : route search 'use strict ' ; angular.module ( 'tachologyApp ' ) .config ( function ( $ stateProvider ) { $ stateProvider .state ( 'search ' , { url : '/search ' , template : ' < search > < /search > ' } ) ; } ) ; 'use strict ' ; ( function ( ) { class SearchComponent { constructor ( ) { this.mess...
Yeoman Angular-Fullstack new route does not redirect
JS
I have an Array with duplicate values.I want to create a Set to get the distinct values of that array and remove or create a new Array that will have the same data MINUS the elements required to create the Set.This is not just a matter of remove the duplicates , but remove a SINGLE entry of a each distinct value in the...
let originalValues = [ ' a ' , ' a ' , ' a ' , ' b ' , ' b ' , ' c ' , ' c ' , 'd ' ] ; let distinct = new Set ( originalValues ) ; /*distinct - > { ' a ' , ' b ' , ' c ' , 'd ' } */// Perhaps originalValues.extract ( distinct ) ? ? for ( let val of distinct.values ( ) ) { const index = originalValues.indexOf ( val ) ;...
How to create a Set from Array and remove original items in JavaScript
JS
This solution was given to this question asking how to trigger an HTML button when Enter is pressed in an input field.Why is if ( typeof e == 'undefined ' & & window.event ) { e = window.event ; } nescecary ? It appears to be checking if the argument did n't get passed correctly , why would n't it ? Is this related to ...
< input type= '' text '' id= '' txtSearch '' onkeypress= '' searchKeyPress ( event ) ; '' / > < input type= '' button '' id= '' btnSearch '' Value= '' Search '' onclick= '' doSomething ( ) ; '' / > < script > function searchKeyPress ( e ) { // look for window.event in case event is n't passed in if ( typeof e == 'undef...
Why is this line of code necessary in clicking a button with JavaScript ?
JS
A few coworkers and I have come across some more strange JavaScript syntax . We are having trouble explaining the following behaviour ( I am using the Chrome console ) : YieldsEssentially , it is valid syntax to include any object ( not just empty ) before the array , and the result is always just the array . Is there ...
> { } [ 1 ] [ 1 ]
JavaScript Strange Array Definition Syntax
JS
I am creating a responsive data table that adds a row each time I click on a add button that is in the end of the row . And the add button turns into a delete button . Here 's the code I madeFor the Table : When for adding is clicked : And my delete function : However when I click on delete nothing seems to happen . Ca...
< table id= '' invoice_table_data '' > < tr id= '' last_row '' > < td contenteditable id= '' item_name '' > < /td > < td contenteditable id= '' item_code '' > < /td > < td contenteditable id= '' description '' > < /td > < td > < button type= '' button '' name= '' btn_add '' id= '' btn_add '' class= '' btn btn-xs btn-su...
How to delete a row from a table
JS
Here 's an example of a situation where a simple JS loop does not behave as expected , because of the loop variable not being in a separate scope . The solution often presented is to construct an unpleasant-looking bit of loop code that looks like this : My question is , could this be improved upon ? Could I use this :...
for ( var i in obj ) { ( function ( ) { ... obj [ i ] ... // this new shadowed i here is now no longer getting changed by for loop } ) ( i ) ; } Object.prototype.each = function ( f ) { for ( var i in this ) { f ( i , this [ i ] ) ; } } ; // leading to this somewhat more straightforward invocationobj.each ( function ( ...
Javascript Function Scoped For Loops
JS
My web application collects data with : id ( key value ) timestampvalueThen , it creates an HTML table like this : Explanation : It sorts the timestamp value in DESC order.If , for example , t1 is the timestamp for ID1 and 't2 ' is the timestamp for ID2 , and ... t1 + 2 seconds > = t2the ID2 row becomes red.In my examp...
< table > < tr bgcolor= '' # FFA9A9 '' > < td > ID1 < /td > < td > 20150619T09.43.03 < /td > < td > VALUE1 < /td > < /tr > < tr > < td > ID2 < /td > < td > 20150619T09.43.02 < /td > < td > VALUE1 < /td > < /tr > < tr bgcolor= '' # FFA9A9 '' > < td > ID3 < /td > < td > 20150619T09.43.00 < /td > < td > VALUE2 < /td > < /...
Sum red row of a table in javascript and then alter the table
JS
I 'm trying to achieve something I ca n't wrap my mind around.The thing is that when a specific user is logged , I store in session the user and that he is logged.Before telling me yes , I know this is n't best practice but the purpose of this page is internal only and there is no possibility to be hacked or so because...
var logged = < ? php echo $ _SESSION [ 'logged_user ' ] ; ? > ; if ( logged=='admin ' ) { // action here }
Limit Javascript from PHP ?
JS
I am displaying every word in a sentence in separate div using inline-block with max-width of 120px . When I try to increase the font size on parent div my inline-block of div get overlaps due to large font size . Is there any way to programmatically calculate the max-width required for inline-block of div to be used a...
jQuery ( '.btnIncFont ' ) .click ( function ( ) { jQuery ( '.parentDiv ' ) .css ( 'font-size ' , parseInt ( jQuery ( '.parentDiv ' ) .css ( 'font-size ' ) ) +2 ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < button class= '' btnIncFont '' > + < /button > ...
Resize container dynamically when font size changes
JS
If you take the following : In Chrome , you 'll get : Invalid DateBut in IE and Firefox , you 'll get : Fri Jun 01 2040 00:00:00 GMT-0500 ( Central Daylight Time ) It appears to be just adding 8888 days to Feb 01 . Instead , I would expect the date to be considered invalid . Is there a way I can make FireFox and IE thi...
var s = `` 2/8888/2016 '' ; var d = new Date ( s ) ; alert ( d ) ;
Why is 2/8888/2016 a valid date in IE and Firefox ?
JS
I have a bunch of divs that have a content div inside of them . In the content div are 3 elements , an h1 , a p and a span , all left-aligned . What I want to happen is the following : The content div should be vertically and horizontally centeredThe content div should be exactly as wide as the text in the h1 or the te...
function toggleBorders ( ) { $ ( 'h1 , p , span ' ) .toggleClass ( 'bordered ' ) ; $ ( '.content ' ) .toggleClass ( 'content-bordered ' ) ; } .box-holder { display : flex ; flex-flow : row wrap ; } .box { flex : 0 0 380px ; display : flex ; align-items : center ; justify-content : center ; height : 350px ; border : 1px...
Div expand to size of certain content
JS
I have a column in which i am displaying Email of user , i have added sort functionality to it . But the resultant array is not sorted properly.Sample code is hereAny help will be appreciatedIn the example code , output of sorting [ Ascending ] is abc+1 @ abc.com abc @ abc.com bac @ abc.comBut Expected output is abc @ ...
< ul ng-repeat= '' user in users | orderBy : 'email ' : false '' >
Issue in sorting Email Values , using AngularJS custom sort function
JS
My question is rather weird , it has to do with something i have seen in jQuery but so far i have been unable to recreate it.in jQuery you can go like thisorthe application i am making would need a similar syntax , i notice if you use new likeyou can call the function with just that , without the ( ) , but in some case...
jQuery ( 'div ' ) .append jQuery.ajax var that=new function ( ) { } that ( ' [ data-something= '' this '' ] ' ) .setEvent ( 'click ' , functin ( ) { } ) that.loadIt ( 'this ' , ' [ data-something= '' that '' ] ' )
javascript : passing as object or function
JS
I search a lots but what I got is how to merge objects and keeps properties of both . How about keep only the same props only ? For example : Is there any way to create an obj3 which is { a:3 , b:3 } ( only keep props in both objects ) ?
const obj1 = { a : 1 , b:2 , c:3 } const obj2 = { a : 3 , b:3 , d:5 , e:7 }
Javascript - How to merge to objects but keep only the same properties
JS
I am practicing with OO Javascript , making a sort of web-app for viewing Manga ( comics ) Right now I have a few classes : SearchResultManga ( generated from data out of the search result ) Chapter ( contained within Manga ) Page ( contained within Chapter ) Image ( contained within Page ) I add the search result to t...
function ( data , result , response ) { var $ resultContainer = $ ( ' < div/ > ' , { class : 'row-fluid ' } ) , maxResults = 10 ; for ( var i in data ) { if ( i == maxResults ) { break ; } data [ i ] .manga = Manga ( data [ i ] ) ; var res = new SearchResult ( data [ i ] ) ; res.setMyContainerElement ( $ resultContaine...
OO Javascript - Should I let a class add itself to the DOM or let it return an element to then add to the DOM ?
JS
I happened to come across the following weird case : One of the network calls returned a response like this : But when the following script is getting evaluated , it is returning an error Unexpected IdentifierThis issue gets fixed when a semi-colon is added after the function1 definition So the correct fix is : I am cu...
window.function1 = function ( ) { console.log ( 'function 1 ' ) ; } window.project = 'test ' ; window.function1 = function ( ) { console.log ( 'function 1 ' ) ; } ; window.project = 'test ' ;
Semi Colon Issue in JS
JS
For my application in node.js I must sort elements of an array in descending order based on some numeric value ( i.e . a numeric rank ) . Since my application is performance-critical , I decided to build my data structure so that sorting is optimized . I hypothesized that the fewer data contained per element in my arra...
var buffer = [ 781197 , ... ] ; var sparseArray = [ 781197 , ... ] ; var sparseArray2 = [ { ' a ' : 781197 } , ... ] ; var denseArray = [ { ' a ' : 781197 , ' b ' : [ ' r ' , ' a ' , ' n ' , 'd ' , ' o ' , 'm ' ] } , ... ] ; /* buffer : for some reason , the first test always takes significantly longer than the others ...
Why do arrays of numbers , more data sort faster than arrays of objects , fewer data in Javascript ?
JS
I ran into a problem with an object which I 'm trying to modify . The object has a certain amount of keys in the format key_yyyy-mm-dd . When certain inputfields lose focus , I trigger a function to modify the object . This function is as follows : .no_hotel are the textboxes that trigger the function , and they also p...
function updateHotelBooking ( ) { $ ( `` .no_hotel '' ) .each ( function ( i ) { var day = $ ( this ) .attr ( 'name ' ) .match ( /\ [ ( .* ? ) \ ] / ) [ 1 ] ; hotelBooking [ `` key_ '' + day ] = parseInt ( $ ( this ) .val ( ) ) ; } ) ; } Objectkey_2011-08-21 : 3key_2011-08-22 : 0key_2011-08-23 : 0key_2011-08-24 : 0key_...
jQuery object never changing except for first time
JS
ProblemI 'm having an issue adding and removing classes , applying styles on scroll.Specifically , when I scroll down the page : The class of is-red is still on the first .dot__outer group when you scroll down the page when it should be removed , there should be one group highlighted with the is-red classThere seems to...
$ ( function ( ) { function updateProgress ( ) { let dot = $ ( `` .dot '' ) ; let dotsBottom = $ ( `` .dots '' ) .offset ( ) .top + $ ( `` .dots '' ) .outerHeight ( ) ; let panelHeaderBottom = $ ( `` .panel-1 '' ) .offset ( ) .top + $ ( `` .panel-1 '' ) .outerHeight ( ) ; let panelRelatedTop = $ ( `` .panel-8 '' ) .off...
Adding and removing class , applying styles on scroll
JS
I have 3 handsontables in my React view . I need them to be synced when the user is scrolling both horizontally and vertically . I tried to use javascript to get horizontally working without any luck.I could n't get it run in the StackOverflow code editor . so here is link to jsfiddlelink
import React from 'react ' ; import ReactDOM from 'react-dom ' ; const handsontableData = Handsontable.helper.createSpreadsheetData ( 6 , 50 ) ; const Table1 = ( ) = > ( < div > < Handsontable.react.HotTable id= '' T1 '' data= { handsontableData } colHeaders rowHeaders colWidths= { [ 100 ] } height= { 200 } width= '' 1...
How to sync multiple handsontable horizontal scrolling
JS
So I have 3 different inputs for the user - Day/Month/Year , and I 'm trying to run an if statement to check if the month is Jan/Feb ( 1 or 2 ) , and then if it subtracts 1 from the year . My if statement is : This is my first time trying to use javascript and it 's very frustrating ! As you can see my code runs when I...
if ( month == 1 || month == 2 ) { if ( month == 1 ) { year = Number ( year ) - 1 ; } else if ( month == 2 ) { year = Number ( year ) - 1 ; } }
JavaScript - When if statement is true , code does n't execute ?
JS
why does javascript have null and undefined ? they both seem to mean the same thing , there 's nothing here and they are both falsey , as they should be . But it means , for example if I want to check if something exists but it could be { } , [ ] , 0 or some other falsey thing i have to checkalso , I know that typeof n...
if ( thing ! == undefined & & thing ! == null ) const nullVariable = null ; console.log ( nullVariable.x ) // = > errorconst emptyVariable = { } ; console.log ( emptyVariable.x ) // = > undefinedconst undefinedVariable ; console.log ( undefinedVariable.x ) // = > error const undefinedVariable = undefined ;
why does javascript have both null and undefined ?
JS
Yes , this question has been answered a lot of times already and , trust me , I searched the internet for it . However , I have n't found a good solution after a fair amount of time.My problem is the following : Imagine an array of the following structure : You can clearly see the duplicates of values . What I am tryin...
[ [ 'helpers ' , 'ConfigHelper.java ' ] , [ 'helpers ' , 'GenerateRandomString.java ' ] , [ 'helpers ' , 'package-info.java ' ] , [ 'helpers ' , 'ScreenshotHelper.java ' ] , [ 'pages ' , 'LoginPage.java ' ] , [ 'pages ' , 'package-info.java ' ] , [ 'pages ' , 'tests ' , 'LoginPageTest.java ' ] , [ 'pages ' , 'tests ' ,...
Multiple arrays into JavaScript object
JS
I have a bouncing arrow on my website that I created with Jquery and setInterval , like this : You can see this in place in a codepen here : http : //codepen.io/mcheah/pen/wMmowrI made it run faster than i needed because its easier to see the issues quicker . My issue is that after leaving the interval running for a fe...
bouncing = setInterval ( function ( ) { $ ( `` div '' ) .animate ( { top : '' 30px '' } ,100 , '' easeInCubic '' , function ( ) { $ ( `` div '' ) .animate ( { top : '' 0px '' } ,100 , '' easeOutCubic '' ) ; } ) ; console.log ( `` bounced '' ) ; } ,200 ) ;
Interval does n't clear immediately after repeating for a while
JS
Example : I want to put the < br > tag after every 5 words like so : How can I do this ?
let str = `` Hello this is a test string to figure out how is it possible to split a long string into multiple string '' ; let str1 = `` Hello this is a test < br > string to figure out how < br > is it possible to split < br > a long string into multiple < br > string '' ;
How can I put the < br > tag in a long string after every 5 words ?
JS
So if you look at this fiddle http : //jsfiddle.net/r0k3t/z8f2N/1/ you can see that returns true . Why does n't Given that I created the `` me '' object as an object literal sure enough it 's prototype should be Object.prototype and the first line would seem to confirm that .
var me = { fName : `` ken '' , lName : `` n '' } ; console.log ( Object.prototype === Object.getPrototypeOf ( me ) ) ; console.log ( Object.prototype === me.prototype ) ;
why is n't Object.prototype === to myNewObj.prototype ?
JS
If you click on the image , which you ca n't see now , another div appears with some info , inside that div there is another image which you also ca n't see , by clicking on it some even more info appears.And there is a button which shows all/hides all info.What I would like to achieve , is when any of the popup texts ...
function popupD1 ( ) { var popup = document.getElementById ( `` myPopupD1 '' ) ; popup.classList.toggle ( `` show '' ) ; var image = document.getElementById ( `` arrow1 '' ) ; if ( image.getAttribute ( 'src ' ) == `` arrow.png '' ) { image.src = `` arrowL.png '' ; } else { image.src = `` arrow.png '' ; } var D1S=docume...
How to make this work with show all/none button ?
JS
I read both articles on Big O for Recursive Fibonacci sequence but still do not have a conceptual understanding of why it is O ( 2^n ) .This is not a duplicate of this link . Please do n't mark as a duplicate . I 'm looking for a conceptual answer . This is one of the simplest recursive functions out there and I want t...
// O ( 2^n ) function fiboR ( n ) { if ( n === 0 || n === 1 ) { return n ; } else if ( n > =2 ) { return fiboR ( n-1 ) + fiboR ( n-2 ) ; } } // O ( n ) function fibo ( n ) { let prev0 = 0 ; let prev1 = 1 ; if ( n === 0 || n === 1 ) { return n ; } while ( n -- > = 2 ) { sum = prev0 + prev1 ; prev0 = prev1 ; prev1 = sum ...
What is a non-mathematical explanation for the Big O of recursive fibonacci ?
JS
I have a next.js project and I keep getting : I 'm not sure why because I 'm not including either jspdf or canvg.Not sure what 's causing it . Any help would be appreciated . I 'm using material-ui if that matters .
error - ./node_modules/jspdf/dist/jspdf.es.min.js:458:25Module not found : Ca n't resolve 'canvg '
Next.js : Module not found : Ca n't resolve 'canvg '
JS
In the following , the second and third console outputs seem to contradict : As per my comments , inspecting the arguments property on this shows null , whilst logging this.arguments explicitly shows [ `` my '' , `` arguments '' ] .What exactly is this when you invoke a function in such a way ? I did n't expect this.ar...
function test ( ) { console.log ( arguments ) ; // - > [ `` my '' , `` arguments '' ] console.dir ( this ) ; // - > test function with arguments property set to null console.log ( this.arguments ) ; // - > [ `` my '' , `` arguments '' ] } test.call ( test , 'my ' , 'arguments ' ) ;
Unexpected `` arguments '' property on object
JS
Given an input array of 1s and 0s of arbitrary length , such as : How can I ( most efficiently ) calculate a new array detailing if chunks of size n 0s which can fit into the input ? ExamplesWhere output now means1 == 'Yes a zero chunk that size could go here ' 0 == 'Could n't fit a chunk that size there'Chunk size = 1...
[ 0 , 1 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 0 , 1 , 0 , 0 ] const calculateOutput = ( input , chunkSize ) = > { const output = input.map ( ( value , index ) = > { let chunkFitsHere = false ; const start = ( index - ( chunkSize ) > = 0 ) ? index - ( chunkSize ) : 0 ; const possibleValues = input.slice ...
How to determine if chunks of a value could fit into an array
JS
I am using jQuery 's .animate ( ) function to animate the width of a < div > when a child < input > is focused . However , this is causing the input to jump up and down when the event is fired . It seems to be something with inline-block.JSFiddleHTMLCSSJavaScript
< div id= '' simp-inputs '' > < div > < label class= '' control-label '' for= '' simp-date '' > Date : < /label > < div class= '' input-group '' > < div class= '' input-group-addon '' > < span class= '' glyphicon glyphicon-calendar '' > < /span > < /div > < input type= '' text '' class= '' form-control '' id= '' simp-d...
jQuery .animate ( ) causing jumpy input
JS
I would like to make something like this : The result should be an alert with the text `` Hello world ! '' inside the h1 tag.It is my goal to be able to do this without explicitly passing the element as an argument to alertHtml .
function alrtHtml ( ) { alert ( this.innerHTML ) } function myFunc ( id ) { document.getElementById ( id ) .alrtHtml ( ) } < html > < head > < meta charset= '' UTF-8 '' / > < title > test < /title > < /head > < body > < h1 id= '' h1 '' > Hello world ! < /h1 > < input type= '' button '' value= '' click '' onclick= '' my...
How to call your own method using `` this '' on a DOM node
JS
Coming from a non-javascript background , I 'm trying to wrap my head around 'undefined'.I wrote a `` isUndefined '' function as follows : if I type in my source this ( where the variable 'boo ' does not exist ) , I get the expected result `` undefined variable '' .if I type in the following : console.log ( isUndefined...
function isUndefined ( value ) { return ( typeof value === 'undefined ' ) ; } if ( typeof boo === 'undefined ' ) { console.log ( 'undefined variable ' ) ; }
Understanding functions and undefined
JS
If there 's a similar question out there about this , please point me in that direction . This issue is hard for me to describe but I will try my best : http : //jsfiddle.net/e70r1mtw/Users here are greeted by a slideshow of images that fade from greyscale to color . This works just fine on OSX and on Firefox in Window...
# home-featured .cycle-slide { -webkit-filter : grayscale ( 100 % ) ; filter : grayscale ( 100 % ) ; -webkit-transition-property : -webkit-filter ; -webkit-transition-duration : 4s ; -webkit-transition-timing-function : ease ; -webkit-transition-delay : 2s ; transition-property : -webkit-filter , filter ; transition-du...
The Initialization of Cycle2 plugin works differently on Windows than on OSX
JS
I have array : I need save this array to another variableNow I need splice from save first index but when I try it , the index is removed from both arrays .
var array = [ `` a '' , `` b '' , `` c '' ] ; var save = array ; var array = [ `` a '' , `` b '' , `` c '' ] ; var save = array ; save.splice ( 0 , 1 ) ; console.log ( array ) ; console.log ( save ) ;
How to create copy of array ?
JS
I am continually having to hold this in a temp variable in order to access it in other functions . For example in the two methods below , I am holding this in a that variable : Is there anyway around this or could I possibly use apply ?
startTimer : function ( ) { var that = this ; if ( $ ( ' # defaultCountdown : hidden ' ) ) $ ( ' # defaultCountdown ' ) .show ( 'slow ' ) ; shortly = new Date ( ) ; shortly.setSeconds ( shortly.getSeconds ( ) + 5 ) ; $ ( ' # defaultCountdown ' ) .countdown ( 'change ' , { until : shortly , layout : ' < ul id= '' errorL...
Stop holding 'this ' in a temp variable
JS
I 'd like to create a series of dl tags in a list from some data using d3.js.The code I came up with is this : where data is an array of objects . Everything works except the elements are not in the correct order.Here is the order I manage to get : But it should be like this : I 've done a fair amount of googling and n...
var x=d3.select ( `` body '' ) .append ( 'ol ' ) .selectAll ( 'li ' ) .data ( data ) .enter ( ) .append ( 'li ' ) .append ( 'dl ' ) .selectAll ( ) .data ( d= > Object.entries ( d.volumeInfo ) ) .enter ( ) ; x.append ( 'dt ' ) .text ( d= > d [ 0 ] ) ; x.append ( 'dd ' ) .text ( d= > d [ 1 ] ) ; < dl > < dt > key1 < /dt ...
How do I create a < dl > using d3.js
JS
I was playing around in Chrome devtools and tried the following code : The code above wo n't work if I replace `` let '' with `` var '' . I 'm assuming that let = 1 is the same as var let = 1 . If so , should n't let x = 2 be translated to 1 x = 2 and therefore be an error ?
let = 1 ; let x = 2 ; console.log ( let ) ; // 1console.log ( x ) ; // 2
Assigning `` let '' a value in Javascript
JS
I was practicing some JavaScript on Codeacademy few minutes ago and I found something confusing . Here is the code : The problem is that when I pass the string `` Steve '' as an arg in the search function , it returns the condition `` Contact not found '' while when I pass the string `` Bill '' as an arg in the same se...
var friends = { } ; friends.bill = { firstName : `` Bill '' , lastName : `` Gates '' , number : `` ( 206 ) 555-5555 '' , address : [ 'One Microsoft Way ' , 'Redmond ' , 'WA ' , '98052 ' ] } ; friends.steve = { firstName : `` Steve '' , lastName : `` Jobs '' , number : `` ( 408 ) 555-5555 '' , address : [ ' 1 Infinite L...
Why else block is executed even though if condition is true ?
JS
ES6 has a lot of functions including assign and others . But is there a method to get a list of properties that are different from one object to the next ? For example , if I have a component with two states . The default state has 100 properties that define it . State two there are only 10 properties that change . Let...
var object = { name : Fred , age : 20 , weight : 100 } ; var object2 = { name : Fred , age : 21 , weight : 120 } ; function getChangesFromObjectTwo ( object1 , object2 ) { return object ; } // returns { age:21 , weight : 120 } ; var changes = getChangesFromObjectTwo ( object , object2 ) ; var object = { name : Fred , a...
Is there an ES6 function that will return an object containing property changes ?
JS
I am no javascript programmer and am totally puzzled by what this code does and what it is used for : It 's part of what you get when using the dart2js compiler.I 'm not trying to understand the whole context , but what does assigning a property and deleting it directly again help achieve ? This looks like outsmarting ...
function map ( x ) { x = Object.create ( null ) ; x.x = 0 ; delete x.x ; return x ; }
Assign and immediately delete property
JS
I 'm trying to target a parent from a link with a jQuery function , at first to get its innerHtml but now , just to get its value.However , I ca n't manage to track it and I 've been putting way too much time on this simple problem.Here 's my html : And my jQuery : I tried parent ( ) , parents ( ) , closest ( ) ... I '...
< table > < tr > < td title= '' td_title_1 '' value= '' td_value_1 '' > Some text < a href= '' # '' title= '' Copy '' > Element_1 < /a > < /td > < td title= '' td_title_2 '' value= '' td_value_2 '' > Some other text < a href= '' # '' title= '' Copy '' > Element_2 < /a > < /td > < /tr > < /table > $ ( function ( ) { $ (...
Ca n't manage to target an element in jQuery
JS
I 'm trying to access a value in my object : Here 's the result of the console.log call : Here 's the strange bit : If I console.log ( ui.item.label ) I get : Boston , Massachusetts , United States.If I call $ ( 'input [ name= '' address-search '' ] ' ) .val ( ui.item.label ) ; I only get Boston . Any ideas why this is...
< input type= '' text '' name= '' address-search '' placeholder= '' 43 Roxling Drive Boston , MA '' class= '' ui-autocomplete-input ui-corner-all '' autocomplete= '' off '' > select : function ( event , ui ) { console.log ( ui ) ; $ ( 'input [ name= '' address-search '' ] ' ) .val ( ui.item.label ) ; }
Strange behavior accessing a property in a javascript object
JS
I made a simple example of my problem with a babel object : Now , I want to extends this object : But what if I need to use an existing function define before ? What I could do is : But in this case , I will always use the context of the say object , is n't it ?
function babel ( ) { this.english = { hello : function ( ) { alert ( 'hello ' ) ; } , goodbye : function ( ) { alert ( 'goodbye ' ) ; } teeshirt : function ( ) { alert ( 'T-shirt ' ) ; } } } babel.prototype.french = { bonjour : function ( ) { alert ( 'bonjour ' ) ; } , aurevoir : function ( ) { alert ( 'au revoir ' ) ;...
How to extends a javascript object ?
JS
I 'm implementing a small voting system on my website . I came up with three implementation methods that I would like your feedback on . I want to give my users the ability to cast several types of votes on some user generated content . It 's micro Q & A about games , not unlike SO 's and their vote system , on a much ...
voteTypes ( id , voteTypeId , voteName ) votes ( id , postId , parentId , userId , ownerUserId , voteTypeId ) < input type= '' hidden '' value= '' @ voteTypeId '' etc ... < a data-vote-type-id= '' @ voteTypeId '' data-post-id= '' @ postId '' etc ...
Of these three methods , which is the best one to implement a voting system ?
JS
I was trying to implement a function similar to angular.isDefined ( ... ) but allowing to check variables and their properties , so I wrote this proof of concept : I know that typeof allows a non declared identifier , and it seems to work properly within eval ( ) : But in my code fails when it is processed by eval ( ) ...
function check ( s ) { let parts = s.split ( '\ . ' ) ; let partial = `` ; return parts.every ( p = > { partial += ( partial ? ' . ' : `` ) + p ; let expr = ` typeof $ { partial } ` ; console.log ( 'Evaluating ' , expr ) ; return eval ( expr ) ! == 'undefined ' ; } ) ; } check ( 'obj ' ) ; let obj= { } ; check ( 'obj '...
Why does typeof within eval ( ) throw an error in my function ?
JS
Okay , I am a beginner at Javascript and jQuery , so this may be a very simple question , but I 've tried researching it , and ca n't quite find any good answers.On my website : http : //joeyellisdesign.com/testingspace/JE2 I have a rollover on the `` work '' section of my portfolio that I am trying to make only appear...
jQuery $ ( document ) .ready ( function ( ) { $ ( `` .project '' ) .hover ( function ( ) { $ ( `` .projectdescription '' ) .animate ( { top : '4px ' } ) ; } , function ( ) { $ ( `` .projectdescription '' ) .animate ( { top : '183.77px ' } ) ; } ) ; } ) ; < div class= '' project '' > < a class= '' workanchor '' href= ''...
Is it possible to make jQuery only target div for hover animation if it is a child of the element being hovered over ?
JS
Possible Duplicate : JavaScript asynchronous return value / assignment with jQuery I need a prototype of chart with constructor , so I wrote this : Then I realized , that because of JaavScript 's synchronousness it returns undefined . How should I defere the return statement of Chart ?
function Chart ( file ) { var chart = undefined $ .getJSON ( file , function ( data ) { chart = { categories : data.keys series : [ { name : 'first ' , data : data.first } , { name : 'second ' , data : data.second } ] } } ) ; return chart }
Defering return statement
JS
I 'm trying to declare a variable whose value is another variable that is n't set at that time.http : //jsfiddle.net/seSMx/1/Is there a way to do this using Jquery/Javascript ?
var add = 1 + three ; var three = 3 ; document.getElementById ( 'thediv ' ) .innerHTML = add ; //results in `` NaN ''
Javascript `` pre set '' a variable ?
JS
I have the following code which takes a single image and applies a specific width to it : However I am struggling to get my head around handling a jQuery collection of images , such as $ ( 'img ' ) without a for loop or $ .each ( ) inside each of the functions ( I have more than these two functions shown above ) .So fa...
function Foo ( img ) { this.image = img ; } Foo.prototype._getWidth = function ( ) { return this.image.data ( 'largest ' ) + 'px ' ; } ; Foo.prototype.applyWidth = function ( ) { this.image.css ( 'width ' , this._getWidth ( ) ) ; } ; var img = Foo ( $ ( 'img ' ) ) ; img.applyWidth ( ) ; var temp = [ ] ; function Create...
jQuery collections , function and organisation
JS
I have a picture and wish its background to change and repeatedly take random colours sequencially from all over the spectrum till the user 's mouse exits the picture . I guess the solution should use setInterval ( see this ) and the following shall help : Here is a fiddle trying to implement what I have in mind : The ...
var red = Math.round ( Math.random ( ) * 255 ) ; var green = Math.round ( Math.random ( ) * 255 ) ; var blue = Math.round ( Math.random ( ) * 255 ) ; var bg = `` background-color : rgb ( `` + red + `` , '' + green + `` , '' + blue + `` ) ; '' ; x.style = bg ;
Repeatedly change background colour of picture onMouseOver
JS
I want to show and hide some div on click and I managed to achieve part of it ( it shows divs and hide them when I click on corresponding buttons ) . However , I do n't know how to close all the already opened divs when I click on other buttons.For example if I click on `` add '' button and it opens the corresponding d...
< div id= '' controls '' > < input type= '' button '' class= '' addBtn '' value= '' Add '' id= '' add '' / > < input type= '' button '' class= '' editBtn '' value= '' Edit '' id= '' edit '' / > < input type= '' button '' class= '' viewBtn '' value= '' View '' id= '' view '' / > < input type= '' button '' class= '' dele...
on click to hide div
JS
I am trying to figure out this operator on JS -But I can not find ant information.Is that a comparison or assignment ? Thanks .
'string ' ^= 'string ' ;
What is the meaning of ^= operator in JS
JS
I recently started learning JavaScript for the purpose of creating HTML5 games , and I 've come across a behavior that I 'm having a hard time understanding.As an example , I have a constructor that initializes new sprites with an array of actions that they should carry out every time the game updates ( such as animati...
Sprite = function ( ) { this.actions = [ this.animate ] ; } ; Sprite.prototype = { animate : function ( ) { /* animate the sprite */ } , update : function ( ) { this.actions [ 0 ] ( ) ; // does n't do anything ( ? ) } } ; Sprite = function ( ) { this.actions = [ this.animate ] ; this.holder = 'whatever ' ; } ; Sprite.p...
Do n't understand why this JavaScript function can be called one way but not the other
JS
I 'm using the jQuery Masked Input plugin to set all input elements with a data-mask attribute defined to the attribute mask value : Given this html : And this script : The second iteration an error is thrown : `` Uncaught TypeError : undefined is not a function '' on this line , saying 'split ' is not defined.This cod...
< input type='text ' id= '' a '' data-mask='999 ? 999 ' / > < input type='text ' id= '' b '' data-mask='999 ' / > $ ( `` input [ data-mask ] '' ) .each ( function ( ) { var maskValue = $ ( this ) .data ( 'mask ' ) ; console.log ( $ ( this ) .attr ( 'id ' ) + `` : `` + maskValue ) ; //undefined error here on second iter...
Object not defined when running in a loop , but not when executed sequentially
JS
I have a problem trying to convert current JSON structure to anotherI want to convert data to an output structure like this.Here 's the target with just the result I want to achieve.It is diffcult for me , could someone help me in this matter ? I 've tried for several hours . Using lodash or underscore or plain JS is o...
var data = [ { `` url '' : `` asset/01.flv '' , `` pic '' : `` asset/01.jpg '' } , { `` url '' : `` asset/02.flv '' , `` pic '' : `` asset/02.jpg '' } , { `` url '' : `` asset/03.flv '' , `` pic '' : `` asset/03.jpg '' } , { `` url '' : `` asset/04.flv|asset/05.flv|asset/06.flv|asset/07.flv|asset/08.flv '' , `` pic '' ...
use underscore or lodash convert one JSON structure to another
JS
http : //jsfiddle.net/bpt33/When g is not specified , it works correctly , When g is specified , it works alternatively
var t = `` '' ; var a = [ `` atom-required '' , '' atom-label '' , '' atom-data-type '' , '' atom-regex '' ] ; var r = /atom\- ( label|required|regex|data\-type|class|is\-valid|field\-value|error ) /i ; function test ( a , r ) { for ( var i = 0 ; i < a.length ; i++ ) { t += a [ i ] + `` = > `` + r.test ( a [ i ] ) + ``...
How does `` g '' in RegExp test method works alternatively ?
JS
I expect this code to return undefined , because arrow functions are lexically scoped , hence this must be eagerly bound to the outer scope.Yet , it returns 123.Why exactly does this happen ? And yep , I understand it 's still stage 3 , but still - why does the proposed standard behave like that ? ( See https : //babel...
class Foo { static v = 123 ; static bar = ( ) = > this.v ; } console.log ( Foo.bar ( ) ) ;
Why are arrow functions as static members values not lexically scoped ?
JS
In http : //eloquentjavascript.net/1st_edition/chapter6.html , there is the following example : Knowing only basic Javascript and imperative programming , I am stumped by this programming style . Can someone help me to understand what happens during runtime.I stepped through the code and inspected variables and found t...
function negate ( func ) { return function ( x ) { return ! func ( x ) ; } ; } var isNotNaN = negate ( isNaN ) ; alert ( isNotNaN ( NaN ) ) ;
How are parameters handled when passing functions in Javascript ?
JS
Please , consider the code sample below , and focus on variable assignments . Since I have never seen such form in C++ , what does the following mean : `` upload '' in new XMLHttpRequest ` .I would need a good explanation of what does the following statement mean : progress : `` upload '' in new XMLHttpRequest . Especi...
tests = { filereader : typeof FileReader ! = 'undefined ' , dnd : 'draggable ' in document.createElement ( 'span ' ) , formdata : ! ! window.FormData , progress : `` upload '' in new XMLHttpRequest } ;
Explanation of `` in '' in JavaScript
JS
After much Googling , I can not find a clear example how to avoid programming every catch to ascertain if a Promise rejection error is programmatic or operational . Compare this to the Node callback pattern of providing callback ( error , params ... ) , where operational errors are cleanly provided in the error paramet...
function logMeIn ( email , password , login_token ) { selectFromDbByEmailAndCheckPwAndReturnId ( email , password ) .then ( id = > { return updateUserIdLoginToken ( id , login_token ) ; } ) .catch ( error = > { // all rejects and throws end up here console.log ( error ) ; } ) } ) function selectFromDbByEmailAndCheckPwA...
Promise.catch ( ) : how to identify the differences between operational rejects and programmatical throws
JS
/ } / is a valid regular expression in JS : However , the ECMA standard does n't seem to allow that : Why does the above work ? Is this feature universally supported ? Is it documented anywhere ?
alert ( ' } } } '.replace ( / } /g , `` ! '' ) ) PatternCharacter : :SourceCharacter but not any of : ^ $ \ . * + ? ( ) [ ] { } |
Why / } / is a valid regular expression in javascript ?
JS
I have an array with predefined lines : I have a div , which i created with JS and styled it with my CSS : Right now i have that code that can animate the texts fadeIns and fadeOuts on click : But it is not a cycle that can iterate through my array items , it will be showing the predefined text all the time . I tried t...
var linesArr = [ `` asd '' , `` dsa '' , `` das '' ] ; var div = document.createElement ( `` div '' ) ; div.className = `` storyArea '' ; div.innerHTML = linesArr [ 0 ] ; $ ( div ) .click ( function ( ) { $ ( this ) .fadeOut ( 1000 , function ( ) { $ ( this ) .text ( `` Random text '' ) .fadeIn ( 2000 ) ; } ) ; } ) ; $...
Insert items from an array into a div when clicking
JS
I 'm working through some practice JavaScript problems , and solved a problem involving recursion . Although I got it right , my implementation is different from the `` official '' solution , so I was wondering if anyone had any insight on whether the official answer is better and if so , why . Question Implement a fun...
function repeat ( operation , num ) { if ( num > 0 ) { operation ( ) ; repeat ( operation , num - 1 ) ; } ; } ; function repeat ( operation , num ) { if ( num < = 0 ) return ; operation ( ) ; return repeat ( operation , -- num ) ; } ;
Did I use recursion correctly ?
JS
I 'm trying to create a simple collage creator using jquery.what I need to do is to have a margin of 1 % between each element ( collage ) .But at the same time I need the collages to have 0 margin from their container.I hope that makes sense.I 've created this FIDDLE so you know what I mean.when you run the code , just...
$ ( ' # colBtn ' ) .live ( 'click ' , function ( ) { $ ( '.lable ' ) .show ( ) ; $ ( ' # reset ' ) .show ( ) ; $ ( ' # fileField ' ) .show ( ) ; $ ( ' # sbs ' ) .show ( ) ; var width = $ ( ' # width ' ) .val ( ) ; var height = $ ( ' # height ' ) .val ( ) ; $ ( ' # main ' ) .append ( ' < div class= '' droppable '' style...
jQuery : css margin based on the amount of elements in container ?
JS
Doing some data transformation exercises and getting stuck . I have an object that I want to transform to look likefrom ( starting ) - > to ( expected ending ) output described below . I 'm trying to use Array.reduce and Object.assign to keep the output pure . but I just can not get it to work properly .
/** * from ( starting ) : { topic : { id : 2 } , products : { id : 3 } } * to ( expected ending ) : { topic : 2 , products : 3 } */const starting = { topic : { id : 2 } , products : { id : 3 } } ; const ending = Object.keys ( starting ) .reduce ( ( p , key ) = > { if ( ! p [ key ] ) p [ key ] = key ; return Object.assi...
Write a pure function to return one object from inner properties another objects ?
JS
I have a menu , when I clicked on each nav , it used to animate to resume on that specific section.Somehow , now it did n't do that anymore recently.What should I check ? I see nothing in my console.Live : https : //www.bunlongheng.com/I used JSThis is the snippet
$ ( ' # main-menu ' ) .onePageNav ( { currentClass : `` active '' , changeHash : false , scrollThreshold : 0.5 , scrollSpeed : 750 , filter : `` '' , easing : `` swing '' } ) ;
Click on Menu Navigation animate to that Section
JS
Why does this happen ? Do BlockStatements return 0 , and why ?
{ 1 + `` } + 10 // 10 { 1 + `` } + `` // 0
JavaScript BlockStatement confusion
JS
The assignment operator has right-to-left associativity . So works as expected and x equals 1 . Consider now the code : I would expect the above to work like the following : However , in the first case foo.x is undefined while in the second case foo.x points to foo ( circular reference ) . Any explanation ?
var x , y ; x=y=1 ; var foo= { } ; foo.x = foo = { n : 2 } ; var foo = { n : 2 } ; foo.x=foo ;
Assignment associativity
JS
Please follow these two steps : focus on the input by clicking in itand now click on the buttonThe result will be : one|two| ! Well I do n't want this . I want to disable focusout when I click on the button . How can I do that ? Expected result after following those two steps should be two| .
$ ( `` input '' ) .on ( { focusout : function ( ) { this.value += `` one| '' ; } } ) ; $ ( `` button '' ) .on ( `` click '' , function ( ) { $ old_val = $ ( `` input '' ) .val ( ) ; $ ( `` input '' ) .val ( $ old_val+ '' two| '' ) ; } ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min....
How can I detect specific element is clicked ?
JS
I 'm trying to figure out a one-liner code using map.Here is a simple set up.Then , I can use map ( ) to call mew method in cats.call ( ) on prototype also works.And here is my final one-liner , but it emits error and I could't understand why : Checking typeof Cat.prototype.mew.call says it 's a functionand map ( ) 's ...
function Cat ( name ) { this.name = name ; // FYI : using __proto__ is discouraged . thanks @ KarelG this.__proto__.mew = function ( ) { console.log ( this.name + `` mews '' ) ; } ; } var cats = [ new Cat ( 'MB ' ) , new Cat ( '503 ' ) ] ; cats.map ( function ( cat ) { cat.mew ( ) ; } ) ; // MB mews// 503 mews cats.map...
Calling method of objects in array using map ( )
JS
I try to match root of domain name with regular expressions in JS . I have a problem when path has n't www . in himself.For example , i tried match from this string : Thats regex what i try is presented below . I try him on regex101.comI expect the output array with names web.archive.org and mrvc.indianrail.gov.in but ...
( http : //web.archive.org/web/20080620033027/http : //www.mrvc.indianrail.gov.in/overview.htm ) / ( ? < = ( \/\/ ( www\. ) |\/\/ ) ) .+ ? ( ? =\/ ) /g
How i can match root of domain name without www . using regex
JS
JavaScript 1.7 allows for destructuring : Is there a way to get the rest of the array and head like : ClojurePythonReference : https : //developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7 # Using_JavaScript_1.7
[ a , b ] = [ 1 , 2 ] // var a = 1 , b = 2 ; ( let [ [ head & xs ] [ 1 2 3 ] ] ( print head xs ) ) ; would print : 1 [ 2 3 ] a , b* = [ 1 , 2 , 3 ]
Destructuring in JavaScript 1.7
JS
I have two tables in different div.This tables use for compare records in table rows.This two tables have two scroll bars.I want to scroll these two scrollbar simultaneously.Someone please help me on linking two scrollbars perfectly .
function SyncScroll ( phoneFaceId ) { var face1 = document.getElementById ( `` phoneface1 '' ) ; var face2 = document.getElementById ( `` phoneface2 '' ) ; if ( phoneFaceId== '' phoneface1 '' ) { face2.scrollTop = face1.scrollTop ; } else { face1.scrollTop = face2.scrollTop ; } } div { display : inline-block ; height:1...
How to scroll two rows simultaneously ?
JS
I 'm learning xss prevention through this ppt : http : //stash.github.io/empirejs-2014/ # /2/23 , and I have a question on this page.It says `` JavaScript sanitization does n't save you from innerHTML '' , and I tried a simple test like this : when I opened this html on my browser ( chrome ) , I only saw the name `` Je...
< ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < title > test < /title > < /head > < body > < div id= '' test '' > < /div > < script > var userName = `` Jeremy\x3Cscript\x3Ealert ( 'boom ' ) \x3C/script\x3E '' ; document.getElementById ( 'test ' ) .innerHTML = `` < span > '' +userName+ '' < /span > ...
what does `` JavaScript sanitization does n't save you from innerHTML '' mean ?
JS
JavaScript map has 2 methods get and has.Method get returns undefined if element does not exist or if value undefined was added to the map.So if I implement my method GetAlways or such , which will return existing or add new and return if not exists , then I am stuck with the choice of sacrificing runtime performance m...
Map.prototype.GetAlways = function ( name ) { let child = this.get ( name ) ; if ( child === undefined ) { // equating undefined value to non-existence child = { } ; this.set ( name , child ) ; } return child ; } Map.prototype.GetAlways = function ( name ) { if ( this.has ( name ) ) // first map seek return this.get ( ...
Double seek vs undefined in JavaScript Map : TryGet wanted
JS
If I define a function : I can print the function definition by calling the toString method on the foo function.output : function foo ( ) { alert ( this.x ) ; } If I then runoutput : `` [ object Function ] '' It is surprising the me that the output is different . I thought these two forms were equivalent ? , i.e . the ...
function foo ( ) { alert ( this.x ) ; } console.log ( foo.toString ( ) ) console.log ( Object.prototype.toString.call ( foo ) )
What is the difference between foo.toString ( ) and Object.prototype.toString.call ( foo ) ?
JS
Is it posible to know , if my function takes vars ? For example :
function ada ( v ) { } ; function dad ( ) { } ; alert ( ada.hasArguments ( ) ) ; // truealert ( dad.hasArguments ( ) ) ; // false
Is it possible to determine if function has arguments ?
JS
I am trying to find the first 100 items in a very large array that match a condition and I 'd prefer to end the loop once I 've found those 100 for efficiency sake , since the method for matching the items is expensive.The problem is that doing : will find all the results in the large array before returning the first 1...
const results = largeArray.filter ( item = > checkItemValidity ( item ) ) .slice ( 0 , 100 ) ; const results = largeArray.slice ( 0 , 100 ) .filter ( item = > checkItemValidity ( item ) ) ;
How to find first n array items that match a condition without looping through entire array
JS
Form : JS : PHP : ... after filling the form and hitting submit , it does submit the form without an error , but the data returned ( JSON ) is empty : json : [ ] What am I doing wrong ?
< form action= '' '' id= '' register '' method= '' post '' > < input type= '' text '' placeholder= '' eg . John '' > < input type= '' text '' placeholder= '' eg . Appleseed '' > < input type= '' text '' placeholder= '' youremail @ domain.com '' > < /form > $ ( 'form # register ' ) .on ( 'submit ' , function ( e ) { $ ....
AJAX form submission - No data returned
JS
I always wondered . Clearly , if I do , a will hold the reference to an instance of Date . It has methods , etc . Why is it , then , that I can subtract two dates using simple the - operator in between ? Am I not subtracting two objects here ? Does Date `` extend '' Number in some way ? And , can I , for myself , defin...
const a = new Date ( ) ; const a = new Date ( ) ; const b = new Date ( ) ; console.log ( a - b ) ;
Why can I directly subtract two Date objects ?
JS
I find the following code in some file : The node is So What 's the . @ operator meaning ?
var node = < title / > ; node . @ name = `` titleName '' ; < title > < name > titleName < name/ > < /title >
Is . @ a Javascript symbol ?
JS
can somebody explain to me how it works ?
function test ( ) { setTimeout ( function ( ) { var now=new Date ( ) ; while ( ( new Date ( ) ) .getTime ( ) < now.getTime ( ) +5000 ) { } console.log ( ' p ' ) } , 0 ) ; } test ( ) ; test ( ) ; //it takes 10 seconds , the second test function runs after the first finished .
Why setTimeout code blocked ?
JS
How to check if a JavaScript variable has actually been declared ? This solution does n't work in my case : JavaScript check if variable exists ( is defined/initialized ) Example : Same as : It produces true in both cases . I could do this : It works , but I 'm looking for anything better that this , x-browsers.EDIT : ...
( function ( ) { var abc ; alert ( typeof abc === 'undefined ' ) // true } ) ( ) ; ( function ( ) { alert ( typeof abc === 'undefined ' ) // true } ) ( ) ; ( function ( ) { var abc ; var isDefined = false ; try { isDefined = abc || ! abc ; } catch ( e ) { } alert ( isDefined ) ; // true } ) ( ) ;
How to check if variable has been declared , although uninitialized ?
JS
Im look at Addy Osmani 's chapter on the constructor pattern : http : //addyosmani.com/resources/essentialjsdesignpatterns/book/ # constructorpatternjavascriptand I came across the following : He said this was not a great thing to do with regards to the this.toString function as it is n't very optimal and is n't shared...
function Car ( model , year , miles ) { this.model = model ; this.year = year ; this.miles = miles ; this.toString = function ( ) { return this.model + `` has done `` + this.miles + `` miles '' ; } ; } // Usage : // We can create new instances of the carvar civic = new Car ( `` Honda Civic '' , 2009 , 20000 ) ; var mon...
Why should you not add functionality to a JavaScript constructor but instead via prototype ?