lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I have an application that uses axios for it 's ajax requests . When a user experiences a network issue ( for example , their wifi goes out and they no longer have an internet connection while on my application ) , I want to make sure that only the first axios request is made , and if I detect there is a network issue ...
const getData = async ( ) = > { try { const response = await axios.get ( 'api/data ' ) ; return response.data ; } catch ( error ) { handleError ( error ) ; } } ; const fetchToken = async ( ) = > { try { const data = await axios.get ( 'api/twilio-token ' ) ; return data.token ; } catch ( error ) { return handleError ( e...
Handling network errors with axios and Twilio
JS
My typical JS class structure looks like this : ... My ongoing annoyance with JS is that I seem to have to use this continuously in member functions in order to access the properties of the very same object to which those functions belong . In several other languages e.g . C # & Java , this may be safely omitted when m...
MyClass = function ( args ) { this.myProp1 = undefined ; this.myProp2 = args [ 0 ] ; // ... more member data this.foo = function ( ) { return this.myProp1 + this.myProp2 ; // < - the problem . } // ... more member functions } //if MyClass extends a superclass , add the following ... MyClass.prototype = Object.create ( ...
JS class without constant reference to `` this '' for member access
JS
I 'm using the sidebar example provided in the official documentation of react-router-v4 as an inspiration https : //reacttraining.com/react-router/web/example/sidebar1- So the initial URL of my application would be : localhost:3000/search-page/Lists2- I have a list of clickable Links that when clicked display the clic...
class MyComponent extends Component { constructor ( props ) { super ( props ) ; this.state = { showListButtonPressed : true } ; this.showTheOtherList = this.ShowTheOtherList.bind ( this ) ; } showTheOtherList ( ) { this.setState ( { showListButtonPressed : ! this.state.showListButtonPressed } ) ; } render ( ) { const d...
How to use nested routes to add content to a page without removing the content of the previous route with react-router-v4 ?
JS
Is it considered bad practice to use jQuery 's .on ( ) event handler for every event ? Previously , my code contained script like this : However I 've recently started using InstantClick ( a pjax jQuery plugin ) .Now none of my scripts work . I understand why this is happening , but I can not wrap my code with the Inst...
$ ( ' # cartButton ' ) .click ( function ( ) { openCart ( ) ; } ) ; $ ( document ) .on ( 'click ' , ' # cartButton ' , function ( ) { openCart ( ) ; } ) ;
Using jQuery .on ( ) for all events
JS
We were using Redis for a plenty of time until we have come to the conclusion that moving to KeyDB may be a good choice for its features . EnvironmentBackgroundReferring to the KeyDB documentation , KeyDB is compatible with the latest version of Redis . KeyDB remains fully compatible with Redis modules API and protocol...
OS : Centos 7NodeJs : v12.18.0Redis : v6.0.5Targeted KeyDB : v0.0.0 ( git:1069d0b4 ) // keydb-cli -v showed this . Installed Using Docker.ioredis : v4.17.3pm2 : v4.2.1 // used for clustering my application . error : message=write EPIPE , stack=Error : write EPIPE./app-error-1.log:37 : at WriteWrap.onWriteComplete [ as ...
IOREDIS - Error Trying to Migrate from Redis to KeyDB
JS
I am playing with ECMAScript 6 symbols and maps in Node.JS v0.11.4 with the -- harmony flag . Consider the following.Can the value 'Noise ' be retrieved given the property is identified by an `` anonymous '' symbol key , which is guaranteed to be unique ?
var a = Map ( ) ; a.set ( Symbol ( ) , 'Noise ' ) ; // Prints `` 1 '' console.log ( a.size ) ;
Recover property key/value
JS
This code throws an error.but this code does n't throws an error.Live Example | Live SourceAs far as I kwon , func ( arg ) is equal to this.func ( arg ) if this is Global Object . Why does such a thing happen ?
try { alert ( hasOwnProperty ( 'window ' ) ) ; } catch ( e ) { alert ( e ) ; // Type Error : ca n't convert undefined to object } try { alert ( this.hasOwnProperty ( 'window ' ) ) ; // true ( if on browser ) } catch ( e ) { // through catch block alert ( e ) ; }
Call Object.prototype method on Global Scope
JS
I was reading about how the Javascript prototype property works along with inheritance and then began to look through the Angular.js code and came up with some questions.First off , I read that the prototype property points to an object that has a `` constructor '' property which points back to the original function th...
// This is the constructorfunction Shape ( ) { this.position = 1 ; } // The constructor points back to the original function we definedShape.protoype.constructor == Shape ; function Square ( ) { } Square.prototype = new Shape ( ) ; var square = new Square ( ) ; square.position ; // This will output 1 var Lexer = functi...
Why assign Something to Something.prototype.constructor ?
JS
I have a Shiny app rendering a datatable within which I would like to incorporate 2 conditional formatting featuresAdd commas to numbers greater than 1000Apply blue background to column 2 values when values column 2 values are > = 1.3x values in column 1 . Apply red background when column 2 values are < = .7x values in...
js_cont_var_lookup < - reactive ( { JS ( 'function ( nRow , aData ) { for ( i=2 ; i < 3 ; i++ ) { if ( parseFloat ( aData [ i ] ) > aData [ 1 ] * ( 1.03 ) ) { $ ( `` td : eq ( `` + i + `` ) '' , nRow ) .css ( `` background-color '' , `` aqua '' ) ; } } for ( i=2 ; i < 3 ; i++ ) { if ( parseFloat ( aData [ i ] ) < aData...
Displaying commas and conditional highlighting in Rshiny - not compatible
JS
I have a youtube player on a web page created with the YouTube IFrame APIWhen I get an onStateChange event , like in the code example : When onPlayerStateChange is being called , I would like to be able to differentiate betweenThe user clicked on the player UI and changed the state ( Play , Pause etc . ) An API call to...
var player ; function onYouTubeIframeAPIReady ( ) { player = new YT.Player ( 'player ' , { height : '390 ' , width : '640 ' , videoId : 'M7lc1UVf-VE ' , events : { 'onReady ' : onPlayerReady , 'onStateChange ' : onPlayerStateChange } } ) ;
Detect event source in YouTube API
JS
When my card title is clicked , its content shows or hides with the show slide jquery animation .show ( 'slide ' , { direction : 'up ' } , 'slow ' ) / .hide ( 'slide ' , { direction : 'up ' } , 'slow ' . The problem is that during the animation the width of .content-annales decreases so there is a lack of continuity wi...
jQuery ( `` .title-annales '' ) .on ( `` click '' , function ( ) { var element = jQuery ( this ) ; if ( jQuery ( this ) .next ( ) .css ( 'display ' ) === 'none ' ) { element.css ( 'border-radius ' , '20px 20px 0px 0px ' ) ; jQuery ( this ) .next ( ) .show ( 'slide ' , { direction : 'up ' } , 'slow ' , function ( ) { el...
Div 's width decreases when show slide animation is playing
JS
What I 'm hoping to achieve is when I hover over an element in the deptmts array , the corresponding element in the brnches array is then faded in and out . I 've added below what I thought it should be but not really sure where I 'm going wrong . Any help would be much appreciated .
var brnches = [ `` # branch01 '' , '' # branch02 '' , '' # branch03 '' , '' # branch04 '' ] var deptmts = [ `` # depart01 '' , '' # depart02 '' , '' # depart03 '' , '' # depart04 '' ] var brchhov = function ( ) { for ( var i=0 ; i < deptmts.length ; i++ ) { $ ( deptmts [ i ] ) .hover ( function ( ) { $ ( brnches [ i ] ...
Hover array element to fade corresponding element in another array [ Closure issue ]
JS
About using Vue ( vue-loader ) + Webpack and ChromatismExample : ( on dev / source ) Does it possible to tell Webpack to convert to rgb ( 0,0,0 ) on build version ? So on build version should be converted something like : ( for performance )
let textColor = chromatism.contrastRatio ( ' # ffea00 ' ) .cssrgb // = > rgb ( 0,0,0 ) let textColor = 'rgb ( 0,0,0 ) '
Webpack : How to convert variables on build
JS
I am in need for a regex in Javascript . I have a string : I want to split this string by periods such that I get an array : What regex will do this ?
'*window.some1.some\.2 . ( a.b + `` ) '' ? cc\.c : d.n [ a.b , cc\.c ] ) .some\.3 . ( this.o.p ? `` .mike . '' [ ff\ . ] ) .some5 ' [ '*window ' , 'some1 ' , 'some\.2 ' , //ignore the . because it 's escaped ' ( a.b ? cc\.c : d.n [ a.b , cc\.c ] ) ' , //ignore everything inside ( ) 'some\.3 ' , ' ( this.o.p ? `` .mike ...
Regex needed to split a string by `` . ''
JS
I am using meteor to create simple blog system . For sitemaps files I 'm using this package.I added some initialize data in server startup function ( create some post ) and used below code ( server/sitemaps.js ) in server to create sitemaps for each category ( e.g . sitemap1.xml for first category and etc ) : And I hav...
function sitemapOutput ( categoryName ) { var out = [ ] , posts = Posts.find ( { category : categoryName } ) .fetch ( ) ; _.each ( posts , function ( post ) { out.push ( { page : post.url ( ) , lastmod : post.insertDate , changefreq : 'weekly ' } ) ; } ) ; return out ; } Categories.find ( ) .forEach ( function ( Catego...
sitemap not created until server restart in meteor
JS
Solved , see bottom of post for final algorithmBackground : I am working on a 2D platformer using JS and the HTML canvas element . The level map is tile-based , but the player is not clamped to the tiles . I am using a collision detection algorithm outlined in `` Tiny Platformer '' on Code inComplete . It largely works...
var borderTiles = getBorderTiles ( object ) , //returns 0 ( a falsy value ) for a tile if it does not fall within the level tileTL = borderTiles.topLeft , tileTR = borderTiles.topRight , tileBL = borderTiles.bottomLeft , tileBR = borderTiles.bottomRight , coordsBR = getTopLeftXYCoordinateOfTile ( tileBR ) , // ( x , y ...
Collision detection should n't make object teleport up
JS
While learning JavaScript , I noticed that some of the functions , for instance getElementById ( ) , are in camel case while the onclick is not.I would like to know why there is a difference in the function naming in JavaScript .
document.getElementById ( `` demo '' ) .onclick = function ( ) { myFunction ( ) } ; document.getElementById ( `` demo '' ) .innerHTML = `` YOU CLICKED ME ! `` ;
Why is camel case used in 'getElementById ' but not in 'onclick ' ?
JS
In JavaScript , with my own emulator implementation , getting the value of register field RA from a 32-bit instruction i is often represented as : However , having the above expression many times in a function is ugly and hard to follow and edit . I have avoided defining a variable ra with that expression and using it ...
this.gpr.u32 [ ( i > > 16 ) & 0x1f ]
'inlining ' in JavaScript ?
JS
Consider that I have this CSS rule for an anchor tag : Of course by watching at what is rendered in the browser , I can judge which of these fonts has already been used ( applied ) to format the current anchor element 's text.However , I need to know which font is currently in use via JavaScript ( jQuery for example ) ...
font-family : Helvetica , Verdana , Calibri , Arial , sans-serif ; $ ( ' # anchor-id ' ) .css ( 'font-family ' ) ;
Besides seeing , is there any way to know which font is currently applied on an HTML element
JS
I 'm trying to update an array from a put requestThis works fine when I perform only 1 request at the time , but when I click the button that performs the update twice the promises , instead of spreading the array and updating the old value with the new one , both of them are spreading the same array causing that when ...
const [ descriptors , setDescriptors ] = useState ( [ ] ) ; const handleDescriptorUpdate = ( id , descriptorData ) = > { services .putDescriptor ( id , descriptorData ) .then ( ( response ) = > { const descriptorIndex = _.findIndex ( descriptors , ( e ) = > e.id === id ) ; if ( descriptorIndex ! == -1 ) { const tempDes...
How to use the useState hook with asynchronous calls to change an array ?
JS
I have a series of points , which represent mobile devices within a room . Previously I have systematically emitted a ping from each and recorded the time at which it arrives at the others to calculate the distances.Here 's a simple diagram of an example network.The bottom A node should have been a D insteadAfter recor...
A = { B : 2 , C : 1 , D : 3 } B = { A : 2 , C : 2 , D : 2 } C = { A : 1 , B : 2 , D : 2 } D = { A : 3 , B : 2 , C : 2 }
Positioning Devices ( Intersecting Circles )
JS
I have this URL : I would like to replace the second to last / with # ( I need the last / ) and get the following output : I 've tried a lot of things with indexOf ( ) , lastIndexOf ( ) and substr ( ) , but I ca n't get the result I want . I could n't get any regex solution to work properly , either.Note that sometimes...
http : //localhost:8888/alain-pers/fr/oeuvres/architecture/ http : //localhost:8888/alain-pers/fr/oeuvres # architecture/ http : //localhost:8888/alain-pers/fr/oeuvres/art-contemporain/
Replace second to last `` / '' character in URL with a ' # '
JS
Let 's say I create a class that has its own canvas with : I use that canvas , draw some stuff , etc. , but never add the canvas to the DOM tree.And when I 'm done , I wo n't use the whole class any more.So when I delete the class that used the canvas , does the canvas still take up memory ? Do I have to delete it in s...
this.canvas = document.createElement ( `` canvas '' ) ;
What happens to unused DOM elements ?
JS
I read through https : //developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML , which claims SyntaxError may happen.I have tried to replace test string with < div > ( partial ) , < div ( broken ) and < div > < /p > ( unmatched ) . Never have I met exception . I wonder whether I need to add pre-check or protection...
dom = document.createElement ( 'div ' ) // output : < div > < /div > dom.innerHTML = ' [ try.various.strings.here ] '// output : `` [ try.various.strings.here ] '' dom// check final DOM
Will exception occur when assigning innerHTML ?
JS
The issue I have is that I made a table , and some arrows separately on different div . But those div can not move and become bigger or smaller simultaneously if I change a browser or zoom in the page.Currently what I am doing is constructing a big table . Inside this big table , there are many small tables : for each ...
< html > < head > < title > Dupont Model < /title > < style type= '' text/css '' > .table { //for tablesposition : absolute ; width : 633px ; height : 309px ; left : 0px ; top : -35px ; } .NetMarginArrow { Position : absolute ; width : 180px ; height : 115px ; left : 428px ; top : 166px ; } < -- -- -- each arrow is asi...
html5 : how to align multiple div without shifting away when changing browser
JS
I have 2 full height divs . When you scroll down the page the one div scrolls up and the other scrolls in an opposite direction . This works great.I 'm trying to keep this effect but put normal full width content underneath it whilst trying to maintain natural scrolling . So I 'd like to keep the alternate scrolling ef...
( function ( $ ) { var top = 0 ; $ ( document ) .ready ( function ( ) { var contentHeight = $ ( '.right ' ) .height ( ) , contents = $ ( '.right > .content ' ) .length ; top = ( 0 - ( contentHeight * ( contents - 1 ) ) ) ; $ ( '.right ' ) .css ( 'top ' , top + 'px ' ) ; } ) ; $ ( window ) .resize ( function ( ) { var c...
Alternate direction scrolling with content underneath
JS
BackgroundI am experimenting with how Generator.prototype.throw ( ) works and made this example : which at runtime results in the following : QuestionI can understand that yield 4 and the remaining part of the try block is skipped after throwing an error.But why does the generator skip yield 7 ?
var myGen = function * ( ) { try { yield 1 ; yield 2 ; yield 3 ; yield 4 ; yield 5 ; } catch ( err ) { console.log ( err ) ; } yield 7 ; yield 8 ; yield 9 ; } var myIterator = myGen ( ) ; console.log ( myIterator.next ( ) ) ; console.log ( myIterator.next ( ) ) ; console.log ( myIterator.next ( ) ) ; myIterator.throw (...
Why does this generator skip a yield outside the try block ?
JS
On a recent project I used Alexander Farkas ' HTML5 Shiv and I noticed that when minified the script was 2.274 KB . This seemed pretty large to me for a concept that John Resig demonstrated in essentially two lines ( I realize that this is highly oversimplified , because John 's does n't include a check for support or ...
( function ( document ) { var div = document.createElement ( 'div ' ) , elements = 'article|aside|audio|canvas|details|figure|figcaption|footer|header|hgroup|nav|output|progress|section|summary|video'.split ( '| ' ) , i = 0 , length = elements.length ; div.innerHTML = ' < header > < /header > ' ; if ( div.childNodes.le...
Downsides of a Custom HTML Shiv
JS
i am trying to use my keyboard to click on a button using the id . For some buttons i had to set the ID , which actually works . But as soon as i try to use the keyboard for the buttons where i set the id , it wo n't work.I am not getting any errors and since adding the id to the element works , i am kinda confused why...
//setting id for first button ( works ) $ ( `` a : contains ( 'Im Verband freigeben ' ) '' ) .attr ( 'id ' , 'freigabe-verband ' ) ; //setting id for second button ( works aswell ) $ ( `` a : contains ( 'Vorheriger Einsatz ' ) '' ) .attr ( 'id ' , 'vorheriger-einsatz ' ) ; $ ( document ) .keydown ( function ( e ) { if ...
jquery script adding id and using it does n't work
JS
I 'm using terser-js to minify my code.The output : What I want : Note that I ca n't write it by hand because the inputs are generated from TypeScript .
a.prototype.a = ... a.prototype.b = ... a.prototype.c = ... var h = a.prototypeh.a = ... h.b = ... h.c = ...
How to minify nested properties
JS
Very limited script experience . I am attempting to get a preloader to cover my images loading in a bootstrap carousel before a second script cycles through them.This script is as far as I can get.andThe sequence I need is loading animation div covering images loading in `` # myCarousel '' > images have loaded > coveri...
< ! -- Preloader -- > < script type= '' text/javascript '' > // < ! [ CDATA [ $ ( window ) .load ( function ( ) { // makes sure the whole site is loaded $ ( ' # status ' ) .fadeOut ( ) ; // will first fade out the loading animation $ ( ' # preloader ' ) .delay ( 50 ) .fadeOut ( 'slow ' ) ; // will fade out the white DI...
Script not firing properly after preloader script
JS
There are 3 parts in below Mask image :1.Outside Non-Transparent Part2.Border3.Inside Transparent partRight now When user click on Transparaent or Non-Transparent part , i am allowing user to upload image ... . Requirement : when user click on Non-Transparent part , than it should not display dailogue box to upload ima...
var mask ; let jsonData = { `` path '' : `` love shape\/ '' , `` info '' : { `` author '' : `` '' , `` keywords '' : `` '' , `` file '' : `` love shape '' , `` date '' : `` sRGB '' , `` title '' : `` '' , `` description '' : `` Normal '' , `` generator '' : `` Export Kit v1.2.8 '' } , `` name '' : `` love shape '' , ``...
Upload Image through Transparent part only
JS
I am trying to learn more about JavaScript OO Programming , but am seeing conflicting methods to create a `` Class '' -like object . I am wondering if there are any substantial differences in these two methods : Method 1Method 2I have seen these two methods used for creating a complex JavsScript object . I have even se...
function Person ( name ) { this.name = name ; this.setName = function ( val ) { this.name = val ; } this.getName = function ( ) { return this.name } } var John = new Person ( `` John '' ) ; function Person ( name ) { var exports = { } ; exports.name = name ; exports.setName = function ( val ) { this.name = val ; } expo...
Differences in JavaScript OO methodology
JS
I 'm trying to write a set of filters to highlight and then dehighlight dynamically generated html : Highlight filter : Dehighlight : I 'm trying to strip away the span tag and leave the original text , but I 'm not sure if it 's working or what to return . Str is the html string . Any help would be greatly appreciated...
app.filter ( 'highlight ' , function ( $ sce ) { return function ( str , termsToHighlight ) { // Sort terms by length termsToHighlight.sort ( function ( a , b ) { return b.length - a.length ; } ) ; var regex = new RegExp ( ' ( ' + termsToHighlight.join ( '| ' ) + ' ) ' , ' g ' ) ; return $ sce.trustAsHtml ( str.toStrin...
Angular highlight & dehighlight dynamic html using filters
JS
Suppose I have a string I want to convert this into in 1 RegExp operation . I can do it in 2 RegExp operations like is it possible to do this in 1 RegExp operation ?
`` , , , a , , , , , b , ,c , , , ,d , , , , '' `` a , b , c , d '' var str = `` , , , a , , , b , , , ,c , , , , , , , ,d , , , , , , '' ; str = str.replace ( / , + , /g , '' , '' ) .replace ( /^ , *| , * $ /g , `` ) ;
Merge contiguous `` , '' into a single `` , '' and remove leading and trailing `` , '' in one RegExp
JS
I have a problem , and try it to solve two more days.Try do it like this : And like this : And like this too : Try .hide ( ) to see work selector at all , and it does n't work too . But when I open DOM , I can see this element and this ID.Warning ! I think it important , this div is added to DOM by AJAX.HTML element :
$ .when ( $ ( document ) .ready ) .then ( function func_fold ( ) { $ ( `` # collapsible_sidebar '' ) .addClass ( 'folded ' ) ; } ) $ ( document ) .ready ( function func_fold ( ) { $ ( `` # collapsible_sidebar '' ) .addClass ( 'folded ' ) ; } ) $ ( document ) .ready ( function ( ) { $ ( `` # collapsible_sidebar '' ) .ad...
JQuery : `` addClass does n't work by id '' , when document ready
JS
I 'm concerned about using Clients.All in my C # Signal R hub class I 'm calling it in both OnConnected ( ) and OnDisconnected ( bool stopCalled ) to show the online status of my logged in users.OnDisconnected ( ) is n't as bad because it 's only being called when someone actually logs offex.My concern - > Blowing up t...
Clients.All.setConnectionStatus ( profileId , true ) ; public override Task OnConnected ( ) { string profileId = Context.User.Identity.Name ; _connections.Add ( profileId , Context.ConnectionId ) ; Clients.All.setConnectionStatus ( profileId , true ) ; return base.OnConnected ( ) ; } public override Task OnDisconnected...
Determine Signal R connection status without broadcasting Clients.All.someMethod ( ) and blowing up client side resources
JS
AsyncFileUpload is not working inside Listview Insert , Edit Itemtemplate and EmptyData Template.Above is my Client Side FunctionsMarkup in .aspx fileTrying to upload file Client side event OnClientUploadError is getting called Not able to understand why it is giving error.same file upload on simple page and inside Upd...
function AttachmentUploadSuccessful ( ) { debugger ; var textError = $ ( `` .AttachmentError '' ) .text ( ) ; if ( textError.length > 0 ) { var text = $ ( `` .AttachmentError '' ) ; text.innerText = text.textContent = textError ; sender._onError ( textError ) ; // it will raise the OnClientUploadError event return ; } ...
AsyncFileUpload Inside Listview Insert , Edit Itemtemplate and EmptyData Template wo n't work
JS
I am trying to create an accordion that is a little bit different than most.What I am trying to do : Have a title that when clicked a description is displayed across the width of the pageI would like to have the titles split across the screen into three columns ; therefore the title would not span the width of the page...
[ tabs direction= '' top '' tab1= '' the first tab '' tab2= '' the second tab '' tab3= '' the third tab '' ] [ tab1 ] [ row ] [ span4 ] [ accordion title= '' Title 1 '' ] Lorem ipsum dolor sit amet , consectetur adipiscing elit . Cras lorem lectus , porta et nulla ut , bibendum placerat sem . Aliquam a consequat ante ,...
How can I create an accordion with jQuery in WordPress ?
JS
When working with bitmap buffers like : I often use math like this : in order to calculate x , y , or vice versa to work with flat buffers of bitmap data . Almost always I end up with flipped results and some way or another end up flipping them back , but clearly there 's something wrong with my thinking on this.What '...
[ 50 , 50 , 50 , 255 , 50 , 50 , 50 , 255 , ... ] [ r , g , b , a , r , g , b , a , ... ] let bufferWidth = width * 4 ; buffer.forEach ( ( channel , index ) = > { let y = Math.floor ( index / bufferWidth ) ; let x = Math.floor ( ( index % bufferWidth ) / 4 ) ; let remainder = index % 4 ; function crop ( buffer , width ...
Why does my algorithm to convert between index and x , y with bitmap buffers result in the image being flipped vertically ?
JS
I am a very beginner in backbone.js.My page navigation looks like this : The left navigation defines four view types , while the top navigation should update the datamodel and re-render the current view ( that 's what I have in mind ) .I want to allow the user to bookmark the current view and category , according to hi...
var AppRouter = Backbone.Router.extend ( { routes : { `` : view/ : category '' : `` aggregatefunction '' } } ) ;
Backbone router for two dimensional menu : advice
JS
I was trying working on animation through jQuery and I faced a problem that the div box work for only 2 clicks . Any kind of help is appreciated.Here is my code : Here is my code link : https : //jsfiddle.net/djmayank/mcutmbcy/1/
$ ( document ) .ready ( function ( ) { $ ( `` # one '' ) .click ( function ( ) { $ ( `` div '' ) .animate ( { top : '250px ' } ) ; } ) ; $ ( `` # sec '' ) .click ( function ( ) { $ ( `` div '' ) .animate ( { bottom : '250px ' } ) ; } ) ; $ ( `` # thi '' ) .click ( function ( ) { $ ( `` div '' ) .animate ( { right : '25...
jQuery animation do n't work after two clicks
JS
I have div tag , in this div tag , I write results from database ( with PHP / MYSQL ) .I want alert height this div tag . Problem is that , sometimes alert returns incorrect div height ( less than real result ) . sometimes result is correct.I think , this happens , because javascript returns result before , than php fi...
$ res = mysqli_query ( `` SELECT some_column FROM table '' ) ; echo ' < div id= '' my_div '' > ' ; while ( $ row = mysqli_fetch_row ( $ res ) ) { echo ' < p > '.row [ 0 ] . ' < /p > ' ; } echo `` < /div > '' ; $ ( document ) .ready ( function ( ) { alert ( $ ( `` # my_div '' ) .height ( ) ) ; } ) ;
Obtain div tag height
JS
Reading fs.read and fs.write , it seems that in Node.js no interface to the C function lseek is directly exposed ; the current file descriptor position can be changed right before any fs.read or fs.write by the argument position.I strongly suspect that , at low level , the argument position is handled with an lseek cal...
int position = lseek ( fd , 0 , SEEK_CUR ) ;
How to know file position in Node.js ? - return value of lseek
JS
I have a Chrome extension ( source provided below ) that is getting caught with a race condition . I need some injected JavaScript to run before all other JavaScript on a web page.The source code of a simple example of what I 'm trying to do is here : https : //github.com/nddipiazza/oogiIt is attempting to add a namesp...
JSESSIONIDlastVisit oogi $ JSESSIONIDoogi $ lastVisit < body > < H2 > Cookies from Inline JavaScript < /H2 > < script > console.log ( `` Inline javascript is executed . `` ) ; document.write ( listCookies ( ) ) ; < /script > < /body > Inline javascript is executed.cookie get/set injector completed
In Chrome extensions , can you force some javascript to be injected before everything ?
JS
I have this jQuery function : I do n't want it as a class , I 'd like to be able to call it like this : onClick= '' scrollTo ( id ) ; '' So , how can I put the function in javascript format : EDITED by publisher : I do n't hate you guys ; o ) I appreciate all your answers , but I 'm not trying to get the id . On the ot...
$ ( '.scrollToLoginBox ' ) .click ( function ( ) { $ ( 'html , body ' ) .animate ( { scrollTop : $ ( `` # LoginBox '' ) .offset ( ) .top-5 } , 'slow ' ) ; } ) ; function scrollTo ( id ) { $ ( 'html , body ' ) .animate ( { scrollTop : $ ( `` # '+id+ ' '' ) .offset ( ) .top-5 } , 'slow ' ) ; } $ ( '.scrollToSettings ' ) ...
How to call a jquery function like in javascript
JS
I want to reformat and validate if a user has provided a valid Belgian enterprise number . Because the input can be all of the following examples : BE 0123.321.123BE0123.321.123BE0123 321 1230123.321.123123.321.123123321123I 've written a function that validates and reformat the input to a 'display ' version ( BE 0123....
formatAndValidateEnterpriseNumber = enterpriseNumber = > { if ( enterpriseNumber === undefined || ! enterpriseNumber || ( enterpriseNumber || `` ) .length < 3 ) return { isValid : false , error : 'Please fill in your enterprise number ' } ; //Remove space , dots , ... enterpriseNumber = enterpriseNumber.toUpperCase ( )...
Can this function be rewritten with a regex ?
JS
I am trying to test some code and for that I need to make some tests in loop , like this : Click here for working example at jsFiddleBut for some reason i in the loop ( and result ) is always 6 , so this code gives me output like this : What am I doing wrong ?
for ( var i = 1 ; i < = 5 ; i++ ) { QUnit.test ( 'Hello ' + i , ( assert ) = > { console.log ( i ) ; assert.ok ( 1 == ' 1 ' , 'Result : ' + i ) ; } ) ; } 66666
QUnit - test in loop , index always the same
JS
I am trying to verify that some properties exist on a configuration object and have values ( truthy ? not necessrily as a few pointed out in the comments ) in javascript in the following manner : I feel this is too verbose and I am curious if there is a better pattern . Perhaps something likeif ( [ 'my ' , 'options ' ]...
const verifyJanrainAppSettings = ( options ) = > { return options.JanrainAppSettings & & options.JanrainAppSettings.settings.tokenUrl & & options.JanrainAppSettings.settings.capture.clientId & & options.JanrainAppSettings.settings.capture.appId & & options.JanrainAppSettings.settings.capture.appDomain & & options.Janra...
How can I check if multiple properties exists on an object without being too verbose ?
JS
I created a function that given any string will return the string with the first and last letter of each word capitalized . So far it works in some words , not on others , can someone help me figure out why ? It works when I type : Capitalize ( `` my name is john smith '' ) , but not with Capitalize ( `` hello there ''...
function Capitalize ( str ) { var spl = str.split ( `` `` ) ; var words = [ ] ; for ( let i = 0 ; i < spl.length ; i++ ) { //For every word for ( let j = 0 ; j < spl [ i ] .length ; j++ ) { //For every letter in each word var word = spl [ i ] ; var size = spl [ i ] .length ; var firstLetterCapital = word.replace ( word...
Function to capitalize first and last letter of each word not working
JS
I have created a javascript class TkpSlider being inspired from this w3schools page . ( JSFiddle ) I have extended this to add some swipe ability being inspired from this page so that I can the slider works on user swipe . ( JSFiddle ) I separated the code so I do n't get confused later from the base code and if any ad...
var TkpSlider = function ( args ) { args= args|| { } ; } ; var mainSwiper = new TkpSlider ( ) ; var TkpSwiper = function ( args ) { TkpSlider.call ( this , args ) ; } ; TkpSwiper.prototype = Object.create ( TkpSlider.prototype ) ; var mainSwiper = new TkpSwiper ( ) ; var TkpSlider = function ( args ) { args= args|| { }...
Javascript prototype extend base-class unable to access base-class properties/methods from prototype class
JS
I am using HTML 5 required attribute for form validation . Now what I want is that if the form has passed the HTML 5 validation , it should take the user to the stripe checkout ( I deliberately xxx out info in the code below for SO question ) . Now if the form has not passed validation , the submit does n't process , w...
< form id= '' tcform '' > < p > < b > Quantity : < /b > 1 < /p > < b class= '' price '' > Price : < /b > < s > £xx < /s > < span style= '' color : red ; '' > £xx < /span > < button class= '' btn btn-default buynow '' id= '' checkout-button-sku_xxx '' role= '' link '' > Buy Now < /button > < p > < i style= '' font-size ...
Page not redirecting to stripe checkout after it passed form validation
JS
Note : This is a repost of another question , which the author deleted . Here 's the original question : I have this polyvariadic comp function in Javascript and was wondering if a similar implementation in Haskell were possible . I am mostly interested in comp 's type : comp builds up a heterogeneous array that usuall...
const comp = f = > Object.assign ( g = > comp ( [ g ] .concat ( f ) ) , { run : x = > f.reduce ( ( acc , h ) = > h ( acc ) , x ) } ) ; const inc = n = > n + 1 ; const sqr = n = > n * n ; const repeatStr = s = > n = > Array ( n + 1 ) .join ( s ) ; comp ( repeatStr ( `` * '' ) ) ( inc ) ( sqr ) .run ( 2 ) ; // `` ***** '...
How to write this polyvariadic composition function in Haskell ?
JS
My index.html page looks like this : Using grunt i was able to concat and minify the js files into one file at prod/js/file.min.js . I also have a new index.html page at prod/index.html that is minify.The problem now is that this new index.html page still reference the old three javascript files and not the new single ...
< html > < script src= '' js/file1.js '' > < /script > < script src= '' js/file2.js '' > < /script > < script src= '' js/file2.js '' > < /script > < /html > < html > < script src= '' js/file.min.js '' > < /script > < /html >
How do I automatically , with Grunt , reference the new ( minified & concatenated ) JavaScript files in HTML ?
JS
I have setup the following css to stop middle mouse panning on computers : However , I can still pan around on my tablet by flicking my finger on the screen ... is there a way of disabling this as well ? Thanks .
overflow-y : scroll ; overflow-x : hidden ;
Is there a way of disabling panning on tablets - website ?
JS
I have an es6 class User and a global function map ( ) given below : Instead of writing the following : I want to ( somehow ) write something like : I am not sure if this is possible or not .
class User { constructor ( public name : string ) { } } const map = < T , R > ( project : ( value : T ) = > R ) = > { } map ( ( value ) = > new User ( value ) ) map ( new User )
How to automatically apply argument to class constructor ?
JS
I have made a wrapper in which I have animated the same effect as Apple on their Airpods Pro page . It 's basically a video , when I scroll the video plays bit by bit . The video 's position is fixed so the text nicely scrolls over it . However , the text is only visible when between the offset of a specific division (...
//If video-animation ended : Make position of video-wrapper relative to continue scrolling if ( $ ( window ) .scrollTop ( ) > = $ ( `` # video-effect-wrapper '' ) .height ( ) ) { $ ( video ) .css ( `` position '' , `` relative '' ) ; $ ( `` # video-effect-wrapper .text '' ) .css ( `` display '' , `` none '' ) ; }
Element from fixed to relative on scroll
JS
I have conditionals like this : Surely there 's a faster way to write this ? Thanks .
if ( foo == 'fgfg ' || foo == 'asdf ' || foo == 'adsfasdf ' ) { // do stuff }
shorter conditionals in js
JS
I have a polygon with several points and a new point has to be added . The existing points are stored in an array : How do you determine which position of the array this newPoint should be added into ? Attempt : I iterated through all the existing points and calculate newPoint 's distance from them , and sorted the exi...
var points = [ { x : 0 , y:0 } , { x : 100 , y : 0 } , { x : 100 , y : 100 } , { x : 0 , y : 100 } ] ;
Adding a new Point into the correct position in an Array of Points
JS
I have created a random quote generator for my Angular app . The component code looks like this : That 's pulling from data that looks like this : And then in my view I do this : The thing is , right now this will generate a new quote every time the component re-loads , which can be multiple times within a single sessi...
qotd = this.quotes [ Math.floor ( Math.random ( ) * this.quotes.length ) ] ; quotes = [ { quote : `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . Phasellus euismod magna magna , euismod tincidunt libero dignis . `` , author : 'Sorato Violasa ' } , { quote : `` Nullam dignissim accumsan magna vitae rhoncus...
Make JavaScript Random Quote Generator Only Generate One Quote Per Day
JS
I 'm trying to learn jquery custom events . I need to fire a simple event on page load.HTML : I need to call my own event to fire an alerti tried the below code .
< div id= '' mydiv '' > my div < /div > $ ( `` # mydiv '' ) .custom ( ) ; function customfun ( ) { $ ( `` # mydiv '' ) .trigger ( `` custom '' ) ; } $ ( document ) .ready ( function ( ) { $ ( `` # mydiv '' ) .bind ( customfun , function ( ) { alert ( 'Banana ! ! ! ' ) ; } ) ; } ) ;
Simple custom event in jquery
JS
What would be the best way to split a word in the middle ( or after a specific amount of characters or syllables ) and join both `` word-parts '' with a line . Basically imagine a very long flexible underscore.The goal is to have `` word___part '' always 100 % of the parent container . Meaning it should work fully resp...
span : first-child { float : left ; display : inline-block ; } span.underscore { } span : last-child { float : right ; display : inline-block ; } < span > Auto < /span > < span class= '' underscore '' > < /span > < span > mation < /span >
CSS/JS : split words with horizontal line in responsive design
JS
I am looking for the most elegant solution for putting both rtl and ltr languages together in a textarea : e.g . arabic and html together.The standards say not to create it using css : This does not work for me anyway , as the html has the nested text problem . Arabic is aligned to the right but the html is broken.Is t...
direction : rtl ; unicode-bidi : embed ;
How to dynamically apply nested base languages in textarea ?
JS
For example , if I have this : Will the user see the question content for a brief moment before the dialog is shown ? Note : Normally I 'd just hide the # question manually , but there 's actually a step in between html ( ) and dialog ( ) with another jQuery plugin where the content must not be 'hidden ' .
$ ( ' # button ' ) .click ( function ( ) { $ .get ( '/question ' , function ( data ) { $ ( ' # question ' ) .html ( data ) ; $ ( ' # question ' ) .dialog ( ... ) ; } ) ; return false ; } ) ;
Does browser rendering and JavaScript execution happen simultaneously ?
JS
I am having a hard time understanding a bit of example code from the book JavaScript Allongé ( free in the online version ) .The example code is a function for calculating the circumference for a given diameter . It shows different ways to bind values with names . One way to go about it , according to the book is this ...
( ( diameter ) = > ( ( PI ) = > diameter * PI ) ( 3.14159265 ) ) ( 2 ) ; // calculates circumference given diameter 2 ( ( ( PI ) = > ( diameter ) = > diameter * PI ) ( 3.14159265 ) ) ( 2 ) ;
Need help understanding function invocation in JavaScript
JS
So currently I have made 2 tables with information in them . But I want to make it so when users open the html document it only shows you 1 table and you can toggle between the different tables . When I click the button for table 1 it hides table 2 and when I click button for table 2 it hides table 1 .
function myFunction ( ) { var x = document.getElementById ( `` Tables '' ) ; if ( x.style.display === `` none '' ) { x.style.display = `` block '' ; } else { x.style.display = `` none '' ; } } function myFunction1 ( ) { var x = document.getElementById ( `` Tables1 '' ) ; if ( x.style.display === `` none '' ) { x.style....
Toggle tables using Buttons
JS
I recently posted a question asking for a way to highlight words smarter by : Single-click highlights the whole word ( default behavior is double-click ) .Click-drag will hightlight full words/terms only . Beautiful solution was posted by Arman.jsFiddle for testing . My aim with this question is to allow the user to si...
jQuery ( document ) .ready ( function ( e ) { ( function ( els ) { for ( var i=0 ; i < els.length ; i++ ) { var el = els [ i ] ; el.addEventListener ( 'mouseup ' , function ( evt ) { if ( document.createRange ) { // Works on all browsers , including IE 9+ var selected = window.getSelection ( ) ; /* if ( selected.toStri...
If a word is highlighted and user clicks the connecting word , highlight both
JS
I have a simple HTML file , that gets data from the server and outputs it : The file that is on the server , test.html looks like this : I keep getting 0 as a status , despite the fact that in the console , it says everything is fine , and gives a 200 status . When I change if ( xmlhttp.status == 200 ) to if ( xmlhttp....
< html > < head > < script type= '' text/javascript '' > var xmlhttp = new XMLHttpRequest ( ) ; function startRequest ( ) { xmlhttp.onreadystatechange = handleStateChange ; xmlhttp.open ( `` GET '' , `` http : //new-host-2.home/test.html '' , true ) ; xmlhttp.send ( null ) ; } function handleStateChange ( ) { if ( xmlh...
Getting 0 As Status
JS
I have a code for a simple photo gallery that had been writen with jquery , but i think it 's overkill to load the entire library for such a simple thing . I want it in raw javascript.Also i 'm wondering how do I attach a loading spinner to this code . thanks.jsfiddle
$ ( ' # thumbs ' ) .delegate ( 'img ' , 'click ' , function ( ) { $ ( ' # largeImage ' ) .attr ( 'src ' , $ ( this ) .attr ( 'src ' ) .replace ( 'thumb ' , 'large ' ) ) ; $ ( ' # description ' ) .html ( $ ( this ) .attr ( 'alt ' ) ) ; } ) ;
converting a simple jquery code to javascript
JS
I was looking at a solution to a puzzle on codewars and I do n't understand why it works . How is minus ( ) working ?
function makeNum ( num , func ) { if ( func === undefined ) { return num ; } else { return func ( num ) ; } } function three ( func ) { return makeNum ( 3 , func ) ; } function eight ( func ) { return makeNum ( 8 , func ) ; } function minus ( right ) { return function ( left ) { return left - right ; } ; } console.log ...
Codewars Solution - Functions acting on each other nested
JS
What does it mean when a javascript function is declared in the following way : How is the above different from just declaring it like below ?
JSON.stringify = JSON.stringify || function ( obj ) { //stuff } ; function stringify ( obj ) { //stuff }
Question about javascript function declaration
JS
The crux of my issue is that I need to use a datatransferitemlist asynchronously which is at odds with the functionality described in the specs , which is that you are locked out of the dataTransfer.items collection once the event ends . https : //bugs.chromium.org/p/chromium/issues/detail ? id=137231 http : //www.what...
drophandler : function ( event ) { event.stopPropagation ( ) ; event.preventDefault ( ) ; event.dataTransfer.dropEffect = 'copy ' ; zip.workerScriptsPath = `` ../bower_components/zip.js/WebContent/ '' ; zip.useWebWorkers = false ; // Disabled because it just makes life more complicated // Check if files contains just a...
HTML5 ondrop event returns before zip.js can finish operations
JS
I am passing a clone of an object from a parent component to a child component using props , but when I change the value of the status property in the object of the parent component the child component gets notified and chenges the value of the status property in the `` cloned '' object.I 've read about Object.assign (...
< template > < div > < AppServerStatus v-for= '' server in servers '' : serverObj= '' JSON.parse ( JSON.stringify ( server ) ) '' > < /AppServerStatus > < hr > < button @ click= '' changeStatus ( ) '' > Change server 2 < /button > < /div > < /template > < script > import AppServerStatus from './AppServerStatus ' ; expo...
Deep copy of a Javascript object is not working as expected in Vue.js
JS
Problem : Firefox loses the first click event when a textarea has the following CSS : See demo : http : //jsbin.com/wuxomaneba/edit ? html , css , outputThe solution to this is simple - remove the : focus selector.However I 'd like to know why this happens and are there any other css rules or situations where this can ...
textarea : focus { resize : vertical ; }
Firefox bug : click event lost if resize : vertical set on focus
JS
There 's a syntax that Javascript adopted from C where you can perform a logical check , without checking anything : What is this equivalent to ? Is it : My actual motivation for asking is wanting to ensure that a member `` exists '' ( that is to say , if it is null or undefined then it does n't exist ) : My concern is...
if ( foo ) { } if ( foo ! = null ) { } if ( foo ! == null ) { } if ( typeof ( foo ) ! = 'undefined ' ) { } if ( typeof ( foo ) ! == 'undefined ' ) { } if ( typeof ( foo ) ! = 'object ' ) { } if ( typeof ( foo ) ! == 'Object ' ) { } if ( window.devicePixelRatio ! == null ) if ( window.devicePixelRatio ! = null ) if ( ! ...
What is the full form of an expressionless statement in javascript ?
JS
I want to make a couple things happen here : Start button starts the animation and then turns into Stop button.Stop button then stops animation where it is and turns back into Start button and enables me to resume from where it stopped.Instead the animation just disappears once i press start or stop again.I am a newbie...
< html > < head > < meta charset= '' UTF-8 '' > < style > div { left : 0px ; bottom : 100px ; } < /style > < script src= '' http : //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { move ( ) ; Stop ( ) ; } ) ; function move ( ) { $ ( `` input '...
I want my animation to travel horizontally across the screen and stop once i press the stop button
JS
Is there a way to return the properties ?
function Name ( first , last ) { this.first = first ; this.last = last ; this.fullName = first + `` `` + last } Name.prototype = { get fullName ( ) { return this.first + `` `` + this.last ; } , set fullName ( name ) { var names = name.split ( `` `` ) ; this.first = names [ 0 ] ; this.last = names [ 1 ] ; } } ; var pers...
JavaScript properties with setter methods are n't real properties ?
JS
In my src/app.ts , I have : And in src/models/index.ts , I have : My typings/global.d.ts has : And finally , my tsconfig.json has : But I still get the error : What am I doing incorrectly ?
import DB from '../models ' export default ( ( ) = > { if ( global.DB ) { return global.DB } ... // Do some other stuff return something declare namespace NodeJS { export interface Global { DB : any ; } } declare var DB : any ; { `` compilerOptions '' : { `` outDir '' : `` ./built '' , `` allowJs '' : true , `` target ...
Typescript : Property 'DB ' does not exist on type 'Global '
JS
One of the developers I work with began to write all his code this way : vs : Are there any performance benefits to doing this ?
$ ( '.toggles ' ) .delegate ( 'input ' , 'click ' , function ( ) { // do something } ) ; $ ( '.toggles ' ) .click ( function ( ) { // do something } ) ;
Is it better to use .delegate ( ) performance wise ?
JS
I 'm trying to pass a reference to a variable and then update the contents in javascript , is that possible ? For example a simple ( fail ) example would be ... This of course does n't work , can anyone help ?
var globalVar = 2 ; function storeThis ( target , value ) { eval ( target ) = value ; } storeThis ( 'globalVar ' , 5 ) ; alert ( 'globalVar now equals ' + globalVar ) ;
Accessing a variable by reference in Javascript
JS
Suppose I have a JavaScript script named foo.js in a GitHub repo . I need to know what sites ( domains ) are using this script . Thus , for instance , if a website www.example.com is referencing my script ... I 'd like to get , track or list example.com as a domain . To be more clear , I do n't want to track actual use...
< html > < head > < script src= '' https : //myGitHubRepo/foo.js '' > < /script > < /head > etc ... < /html >
What sites are using my GitHub hosted script ?
JS
I have a website that i have built that is 90 % jQuery with ajax so i would like to render different maps with directions with the click of a button without page refreshing.I have everything working right for the first rendering as you can see in the following picture.But when i go to reload or change to a different on...
window.initialize_map = function ( ) { function getMiles ( i ) { return i*0.000621371192 ; } function toHHMMSS ( i ) { var sec_num = parseInt ( i , 10 ) ; // do n't forget the second param var hours = Math.floor ( sec_num / 3600 ) ; var minutes = Math.floor ( ( sec_num - ( hours * 3600 ) ) / 60 ) ; var seconds = sec_nu...
Issue rendering Google maps on 2nd render In Dialog Box
JS
The URL example.com/redir will automatically redirect the user ( HTTP 302 ) to example.com/hi.SWF ? message=Message+Value.How can I get the message value , using javascript or flash , in the following example ? Consider that : The above .html is hosted in cross-domain.com , just like any other file involved in the solu...
< ! DOCTYPE html > < html > < body > < embed id= '' foo '' src= '' https : //example.com/redir '' > < /embed > < ! -- Remember that example.com/redir will be automatically redirected to example.com/hi.SWF ? message=Message+Value -- > < ! -- The code to get the message value must go here -- > < /body > < /html >
Getting flash src after a 302 redirect OR an element inside an embed/object/iframe tag ( cross-domain )
JS
On executingHow can the first code just execute as if a has already been initialize before .
var a=b=c=d=e=f=a ; //no error ( a has not initialize before ) var x=y ; //ReferenceError : y is not defined
Assigning the variable name to the same variable name
JS
Is it better / faster inside an event listener to use this or event.targetI 've been writing code like this ( example is jQuery ) : And I was told to replace e.target with this because it 's `` better '' . Is there really any advantage to one or the other ? I use target because it 's a more general solution as it works...
jQuery ( 'input ' ) .bind ( 'keyup ' , function ( e ) { var j = jQuery ( e.target ) ; foo ( j.attr ( 'id ' ) , j.val ( ) ) ; } ) ;
Advantage of *this* over event.target
JS
I 'd like to be able to end a Google speech-to-text stream ( created with streamingRecognize ) , and get back the pending SR ( speech recognition ) results.In a nutshell , the relevant Node.js code : What I experience is that the SR stream ends successfully , but I do n't get any data events or error events . Neither d...
// create SR streamconst stream = speechClient.streamingRecognize ( request ) ; // observe data eventconst dataPromise = new Promise ( resolve = > stream.on ( 'data ' , resolve ) ) ; // observe error eventconst errorPromise = new Promise ( ( resolve , reject ) = > stream.on ( 'error ' , reject ) ) ; // observe finish e...
How to end Google Speech-to-Text streamingRecognize gracefully and get back the pending text results ?
JS
ES6 introduced a shorthand notation to initialize objects with functions and properties.However , these different notations behave differently , as you can see . If I do new obj1.a ( ) in the browser ( tested Chrome and Firefox ) , I get a TypeError : obj1.a is not a constructor . new obj2.a ( ) behaves completely norm...
// ES6 shorthand notationconst obj1 = { a ( b ) { console.log ( `` ES6 : obj1 '' ) ; } } ; // ES5var obj2 = { a : function a ( b ) { console.log ( `` ES5 : obj2 '' ) ; } } ; obj2.a ( ) ; obj1.a ( ) ; new obj2.a ( ) ; new obj1.a ( ) ;
Constructor behaving differently using ES6 shorthand notation
JS
This is a simple snippet , I just dont understand something.The below code outputs 12 , I understand that , because the var foo = 12 ; replaces the previous declaration of the variable.In the below code , it alerts 1 , which means the variable declared outside the function is accessible inside the function.But , in the...
< script > var foo = 1 ; function bar ( ) { if ( ! foo ) { var foo = 12 ; } alert ( foo ) ; } bar ( ) ; < /script > < script > var foo = 1 ; function bar ( ) { alert ( foo ) ; } bar ( ) ; < /script > < script > var foo = 1 ; function bar ( ) { if ( ! foo ) { var foo = foo ; } alert ( foo ) ; } bar ( ) ; < /script >
Javascript- Variable Hoisting
JS
Here is the problem , I actually have to manage objects that can contain other objects defined in db.So , for example , I have 5 kind of boxes . A red box , a green box , a blue box , a yellow box and a black box.Each box can contain one box , that can also contain a box , and so on.What I receive is this kind of objec...
{ `` id '' :1 , `` type '' : '' black '' , `` box '' : { `` id '' :8 , `` type '' : '' red '' , `` box '' : { `` id '' :15 , `` type '' : '' green '' , `` box '' : null } } } < select name= '' LEVEL_1 '' > < option value= '' 0 '' > NONE < /option > < option selected value= '' 1 '' > black < /option > < option value= ''...
Dynamic Edit form for some kind of Russian Dolls container ( s ) with AngularJS
JS
I created the following component to select dates in UnForm : To save records the component is working normally , loading and saving the date I selected . When I am going to edit a record , when trying to load the date in the initial load , the page is broken and the following error is displayed : If I comment out the ...
export default function DatePickerInput ( { name , ... rest } ) { const datepickerRef = useRef ( null ) ; const { fieldName , defaultValue = `` , registerField } = useField ( name ) ; const [ date , setDate ] = useState ( defaultValue || null ) ; useEffect ( ( ) = > { registerField ( { name : fieldName , ref : datepick...
Datepicker component breaking an edit screen , using @ unform and react-datepicker
JS
What is the difference between those three code samples here below ? Is one better than the others and why ? I 've seen people using jQuery in their examples , and each one of them brings jQuery into ASP.NET in a different way . What is the best way ?
1.Page.ClientScript.RegisterClientScriptInclude ( typeof ( demo ) , `` jQuery '' , ResolveUrl ( `` ~/js/jquery.js '' ) ) ; 2 . < asp : ScriptManager runat= '' server '' > < Scripts > < asp : ScriptReference Path= '' ~/jquery-1.2.6.min.js '' / > < asp : ScriptReference Path= '' ~/jquery.blockUI.js '' / > < /Scripts > < ...
Proper way of bringing in jQuery into ASP.NET ( or any other external JavaScript )
JS
I did some research on this and still ca n't find a good solution for it . I wrote my app in ExtJS 4.1 and when I run it on an iPod the dragging functionality is disabled by default ( which is what I want ) , but if I write the same app in ExtJS 6.2 all windows can be draggable which causes issues of visibility of the ...
var win = Ext.create ( 'Ext.Window ' , { title : `` My Window '' , width : 500 , modal : true , layout : 'fit ' , items : form , buttons : [ { text : 'Close ' , handler : function ( ) { win.hide ( ) ; } } ] } ) ; win.show ( ) ; if ( Ext.os.deviceType === 'Tablet ' ) { win.dd.disable ( ) ; }
Dragging windows
JS
Let 's say I have a fairly nested JS object like this and I need to JSON-encode it : If I JSON-encode it using the native browser JSON.stringify ( tested in Chrome , Firefox , IE9/10 ) , I get back a JSON string that looks like this ( which is what I expect ) : Native JSON.stringify JSFiddle exampleThe weirdness comes ...
var foo = { `` totA '' : -1 , `` totB '' : -1 , `` totC '' : `` 13,052.00 '' , `` totHours '' : 154 , `` groups '' : [ { `` id '' : 1 , `` name '' : `` Name A '' , `` billingCodes '' : [ { `` bc '' : `` 25 '' , `` type '' : `` hours '' , `` hours '' : `` 5 '' , `` amount '' : `` $ 25.00 '' } ] } ] } ; { `` totA '' : -1...
Noticing an odd difference between different implementations of JSON.stringify
JS
I have used the Canvas code provided elsewhere on this site to create a screen where I have several overlapping transparent pngs with the non-transparent parts being irregular shapes . I can get the color under the cursor and that is great . But my shapes are all the same color and I need a way to get the ID of the par...
$ ( ' # myCanvas ' ) .click ( function ( e ) { var position = findPos ( this ) ; var x = e.pageX - position.x ; var y = e.pageY - position.y ; var coordinate = `` x= '' + x + `` , y= '' + y ; var canvas = this.getContext ( '2d ' ) ; var p = canvas.getImageData ( x , y , 1 , 1 ) .data ; var hex = `` # '' + ( `` 000000 '...
Is HTML5 hit detection possible ?
JS
I have board game with some image and table.The display is ok when I am working with Chrome but on other browsers , such IE , or other computer with smaller screen then mine the display is being disrupted.When I tried to resize my browser I found this problem too . Before resizing browser to left : After resizing brows...
margin-left : 10 % ; margin-right : 10 % ; td { width : 105px ; height : 90px ; text-align : left ; vertical-align : top ; border : 1px solid black ; position : relative ; margin-left : 10 % ; margin-right : 10 % ; } table { position : fixed ; left:9px ; top:8px ; } # dice { right : 230px ; position : fixed ; margin-le...
How to keep the size of images and table 's cells relative on browser resizing
JS
I have a dropdown that contains around 100,000 rows which make up a list.I have a text box which acts as a search , so as you type it matches the input to items in the list , removing what does not match . This is the class I wrote to perform the removing of list elements.See the fiddle ( list has about 2000 items ) I ...
< input id= '' search '' type= '' text '' / > < ul > < li > item 1 < /li > < li > item 2 < /li > ... < li > item 100,000 < /li > < /ul > // requires jQueryvar Search = ( function ( ) { var cls = function ( name ) { var self = this ; self.elem = $ ( ' # ' + name ) ; self.list = $ ( ' # ' + name ) .next ( 'ul ' ) .childr...
Fastest way to remove/hide a lot of elements from a list
JS
This script when included in an HTML document which includes any declared styles ( excluding those set by style= '' '' ) will output an optimized stylesheet to the to the page . The script uses the following methods ... Ignore any @ or : rules to leave responsive styles as is.Separate the rules into single selector rul...
@ media ( min-width : 0px ) { /* This says that these styles always apply */ } var stylesheets = document.styleSheets , stylesheet , i ; var ruleText = `` '' ; if ( stylesheets & & stylesheets.length ) { for ( i = 0 ; ( stylesheet = stylesheets [ i ] ) ; i++ ) { var rules = stylesheet.rules , rule , j ; if ( rules & & ...
CSSRules group selectors with common properties
JS
I 'm using the standard Fisher-Yates algorithm to randomly shuffle a deck of cards in an array . However , I 'm unsure if this will actually produce a true distribution of all possible permutations of a real-world shuffled deck of cards.V8 's Math.random only has 128-bits of internal state . Since there are 52 cards in...
function shuffle ( array ) { var m = array.length , t , i ; while ( m ) { i = Math.floor ( Math.random ( ) * m -- ) ; t = array [ m ] ; array [ m ] = array [ i ] ; array [ i ] = t ; } return array ; }
Can Fisher-Yates shuffle produce all playing card permutations ?
JS
I completely understand why it 's better to use the prototype instead of the constructor to define a class method , ( i.e . Use of 'prototype ' vs. 'this ' in JavaScript ? ) However , I recently came across a HashMap class that defines the count property in the prototype and the map property in the constructor : Are th...
js_cols.HashMap = function ( opt_map , var_args ) { /** * Underlying JS object used to implement the map . * @ type { ! Object } * @ private */ this.map_ = { } ; / ... } /** * The number of key value pairs in the map . * @ private * @ type { number } */js_cols.HashMap.prototype.count_ = 0 ;
Why declare an instance property in prototype instead of constructor ?
JS
How do I `` think in Qunit '' with my own JavaScript libraries ? I 'm familiar with developing in javascript , but now I 'd like to start using Qunit ( with my applications in HTML/JavaScript ) .I make my own libraries . I use public functions and private functions . I also use asynchronous functions ( event listeners ...
var mylib ; ( function ( ) { // ... } ) ( ) ;
How do I `` think in QUnit '' with my own JavaScript libraries ?