lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
I have HTML code for kind of blog page . Below - code of 1 post and its height cuts by CSS . It will be many posts on blog page . I want to see all content of particular page by clicking `` Read More '' button.Div with blog content has dynamic id which gets from database by PHP.How can I change height of div with class...
< div class= '' blog_article_wrapper '' > < div class= '' blog_article '' id= '' < ? php echo $ id ; ? > '' > < ! -- Some content -- > < /div > < div class= '' blog_article_read_more '' > < button onclick= '' blogReadMore ( ) '' > Read More < /button > < /div > < /div >
Get sibling div id generated by PHP
JS
ProblemI am trying to push a returning variables value into an array . This is my code , however I 'm returning an empty array and am not sure what 's wrong . JavaScript
var my_arr = [ ] ; function foo ( ) { var unitValue = parseFloat ( $ ( ' # unitVal1 ' ) .val ( ) ) ; var percentFiner = parseFloat ( $ ( ' # percent1 ' ) .val ( ) ) ; var total = unitValue * 1000 ; return my_arr.push ( { unit : unitValue , percent : percentFiner } ) ; }
Pushing a variable value into an array
JS
The following confuses me greatly . As noted in the comments , the compares seem to work by themselves , but when put together they don'tThe while should run for all days in the same month , then increment i by one , then start over again . I have laced the whole sequence up with console.log to try to figure it out , b...
var i=0 ; var currentdate = 0 ; var currentmonth = 0 ; var opensmonth = 0 ; var opens = [ { `` date '' : '' 3/30/2006 '' , '' zip '' : '' 30038 '' , '' latitude '' : '' 33.676358 '' , '' longitude '' : '' -84.15381 '' } , { `` date '' : '' 4/31/2006 '' , '' zip '' : '' 30519 '' , '' latitude '' : '' 34.089419 '' , '' l...
Javascript `` == '' operator lies
JS
I want to show a line graph with rolling std over the sum of values for an interval of dates.The code for the generation of the crossfilter/reductio object is : I have put everything into a jsFiddle to show what I mean ( unrelated question : I do not understand how the dates on the graphs can go beyond my dateToInit va...
myCrossfilter = crossfilter ( data ) ; function getRunningDates ( numDays ) { return function getDates ( d ) { var s = d.ValueDate ; var e = new Date ( s ) ; e.setDate ( e.getDate ( ) + numDays ) ; a = [ ] ; while ( s < e ) { a.push ( s ) ; s = new Date ( s.setDate ( s.getDate ( ) + 1 ) ) } return a ; } } var dim1 = my...
How to generate a rolling std line chart in dc.js/reductio/crossfilter
JS
I have a draggable div . I want it to be only draggable within the size of my screen . But now anyone can drag it and make it go out of the boundaries . My draggable div : I made a search on the web and found this line of code . It was suppose to prevent scrolling.All it does is to disappear scroll bar but you can drag...
$ ( `` # stayaway '' ) .draggable ( ) $ ( `` body '' ) .css ( `` overflow '' , `` hidden '' )
How to prevent the page from scrolling when dragging an element ?
JS
Let 's say I have Player object : It works great , I can create players and each will have its own set of handlers . Now suppose I need to inherit from player : Now when I create testPlayer 's , each of them share the same handlers property : What am I missing here ? I understand than every testPlayer 's prototype is t...
var player = function ( name ) { this.handlers = { } ; } player.prototype.on = function ( event , callback ) { if ( ! this.handlers [ event ] ) { this.handlers [ event ] = [ ] ; } this.handlers [ event ] .push ( callback ) ; } var testPlayer = function ( name ) { this.name = name ; } ; testPlayer.prototype = new player...
JS Prototypal Inheritance : childs use the same parent properties ?
JS
I want to implement a big file downloading ( approx . 10-1024 Mb ) from the same server ( without external cloud file storage , aka on-premises ) where my app runs using Node.js and Express.js.I figured out how to do that by converting the entire file into Blob , transferring it over the network , and then generating a...
const aTag = document.createElement ( `` a '' ) ; aTag.href = ` /downloadDocument ? fileUUID= $ { fileName } ` ; aTag.download = fileName ; aTag.click ( ) ; app.get ( `` /downloadDocument '' , async ( req , res ) = > { req.headers.range = `` bytes=0 '' ; const [ urlPrefix , fileUUID ] = req.url.split ( `` /downloadDocu...
How to download a big file directly to the disk , without storing it in RAM of a server and browser ?
JS
I recently saw this code on another post ( jQuery Set Cursor Position in Text Area ) After too long trying to understand what it was doing I finally figured out that it 's just creating a new function with a parameter $ and then invoking it with jQuery as the parameter value . So actually , it 's just doing this : What...
new function ( $ ) { $ .fn.setCursorPosition = function ( pos ) { // function body omitted , not relevant to question } } ( jQuery ) ; jQuery.fn.setCursorPosition = function ( pos ) { // function body omitted , not relevant to question }
Weird syntax for extending jQuery
JS
Typos happen , and sometimes it is really hard to track them down in JavaScript . Take this for example ( imagine it in between some more code ) : For undeclared variables , strict mode helps : But it does not work for the example above . Is there a program or mode that can catch these bugs ? I tried JSLint and JavaScr...
// no error . I would like a warningdocument.getElementById ( 'out ' ) .innerHtml = `` foo '' ; `` use strict '' ; var myHTML = `` foo '' ; myHtml = `` bar '' ; // - > error // should work ( without warning ) function MyClass ( arg ) { this.myField = arg ; }
JavaScript : prevent unintentional creation of new property
JS
Why does an empty array plus false return the string `` false '' ? An empty array is false , right ? Then false + false = false ? No ?
> [ ] + false > `` false ''
Why does an empty array plus false in JS return a string ?
JS
I have some JavaScript code , from which I need to find start+end indexes of every literal regular expression.How can such information be extracted from UglifyJS ? The structure I 'm getting into variable parsed is very complex . And all I need is an array of [ { startIdx , endIdx } , { startIdx , endIdx } ] of every l...
var uglify = require ( 'uglify-js ' ) ; var code = `` func ( 1/2 , /hello/ ) ; '' ; var parsed = uglify.parse ( code ) ; AST_Token { raw : '/hello/ ' , file : null , comments_before : [ ] , nlb : false , endpos : 17 , endcol : 17 , endline : 1 , pos : 10 , col : 10 , line : 1 , value : /hello/ , type : 'regexp ' }
Enumerate regular expressions via UglifyJS
JS
I have a nested array like this.I want to check if every value is false . I could think of one way of doing this.This works . But I 'm curious if there is a better way ? to check if all values are true or false ?
var arr = [ [ false , false , false , false ] , [ false , false , false , false ] , [ false , false , false , false ] , [ false , false , false , false ] ] let sum = 0 ; arr.forEach ( ( row , i ) = > { row.forEach ( ( col , j ) = > { sum = sum +arr [ i ] [ j ] } ) ; } ) ; if ( sum === 0 ) { console.log ( `` all values ...
Better way to check if every value in a nested array is true or false ?
JS
I 'm reading this book and there is a chapter about prototypes with this hard to understand paragraph and code snippet . When you make a new object , you can select the object that should be its prototype . The mechanism that JavaScript provides to do this is messy and complex , but it can be significantly simplified ....
if ( typeof Object.beget ! == 'function ' ) { Object.beget = function ( o ) { var F = function ( ) { } ; F.prototype = o ; return new F ( ) ; } ; } var another_stooge = Object.beget ( stooge ) ;
Old object as a prototype
JS
I 've got a pretty big complicated HTML5 app I 'm working on ( backbone , marionette , jquery , underscore , handlebars , bootstrap , etc ) and deep within the app is a modal popup with a form in it.When the modal pops open , the first time you click on any form field the form field de-selects itself . After that first...
console.log ( 'bound events : ' , $ ._data ( this. $ el.find ( ' # RandomFieldID ' ) [ 0 ] , 'events ' ) ) ; console.dir ( $ ( ' # elmId ' ) .data ( 'events ' ) ) ; console.log ( 'bound events : ' , $ ._data ( $ ( 'body ' ) [ 0 ] , 'events ' ) ) ;
How do I find mysteriously bound javascript events
JS
I am currently building a portfolio in which I intend to mimic the windows workflow to display my projects and to have a familiar user interaction . The problem I am facing now is with creating multiple explorer windows . I can create multiple ones at the time , but when I try to the content specified to each window , ...
$ ( window ) .ready ( function ( ) { var desktop = document.querySelector ( '.workarea ' ) ; $ ( '.general_icon ' ) .click ( function ( e ) { console.log ( e ) ; var explorerWindow = document.createElement ( 'div ' ) ; explorerWindow.className += 'explorer_window ui-widget-content ' ; var topToolBar = document.createEl...
Windows mimicking portfolio
JS
Just came across a funky function rewriting concept in Javascript.In what situations are these helpfull and is there any other scripting language which support this kind of code ? Fiddler link : http : //jsfiddle.net/4t2Bh/
var foo = function ( ) { alert ( `` Hello '' ) ; foo = function ( ) { alert ( `` World ! `` ) ; } ; } ; foo ( ) ; foo ( ) ;
Rewriting functions in java scripts
JS
This function takes a string of DNA such as 'GTCA ' and returns an array containing correctly matched DNA pairs.This is correct . However i 'm trying to find a shorter , simpler way of writing it . Can anyone help me with what I should be using ?
function pairDNA ( dna ) { const pairs = [ ] for ( let i = 0 ; i < dna.length ; i ++ ) { if ( dna [ i ] === `` C '' | dna [ i ] === `` c '' ) { pairs.push ( `` CG '' ) ; } else if ( dna [ i ] === `` G '' | dna [ i ] === `` g '' ) { pairs.push ( `` GC '' ) ; } else if ( dna [ i ] === `` T '' | dna [ i ] === `` t '' ) { ...
How can I improve and shorten this block of code ?
JS
I 'm not sure what they are called , but what I mean is this : length should be 2 herehow can I see how many attributes I have in the array ? array.length does n't work = ( I 've been trying all kinds of things and I feel like I 'm missing something really simple here..Thank you for your help
array [ `` water '' ] = 50 ; array [ `` fire '' ] = 30 ;
Getting the length of a 'named ' array ?
JS
I 've drawn the following picture demonstrating how the objects are inherited ( function constructors are marked as blue , objects created from those constructors are marked as green ) : Here is the code creating such hierarchy : Now I want to check if new Square ( ) is inherited from the Rect , so here is how I expect...
function Figure ( ) { } function Rect ( ) { } Rect.prototype = new Figure ( ) ; function Square ( ) { } Square.prototype = new Rect ( ) ; function Ellipse ( ) { } Ellipse.prototype = new Figure ( ) ; function Circle ( ) { } Circle.prototype = new Ellipse ( ) ; var s = new Square ( ) ; s instanceof Rect // ? s.__proto__...
Understanding prototype inheritance
JS
I would like to have the numbering of the ordered list in descending order . live example here : demoBut instead of having the counte span multiple ol , I would like the counter to reset after each ol.So , the desired result for the live demo would be : Does anyone have an idea how to modify the code from the live demo...
[ 3 ] 1 [ 2 ] 2 [ 1 ] 3 [ 2 ] 4 [ 1 ] 5
Reverse the numbering order for ordered lists
JS
I 've written basic jQuery plugins before , but I 'm struggling to get my head around something more complex . I 'm looking to emulate the API of jQuery UI , which works like this : I 've tried the following : What I would like to see here is 'newval ' being logged , but I 'm seeing 'defaultVal ' instead ; the plugin i...
$ ( ' # mydiv ' ) .sortable ( { name : 'value ' } ) ; // constructor , options $ ( ' # mydiv ' ) .sortable ( `` serialize '' ) ; // call a method , with existing options $ ( ' # mydiv ' ) .sortable ( 'option ' , 'axis ' , ' x ' ) ; // get an existing option ( function ( $ ) { $ .fn.myPlugin = function ( cmd ) { var con...
How can I emulate the Jquery UI API ?
JS
What in the world is making the second parameter return true ? WARNING : it will loop infinitely and might crash your browserI was totally expecting not to loop at all ... But it is running , and that makes it worse since it can only be running if something evaluated to true , or am I missing something ?
for ( ; ; ) { // ... }
Why does this 'for ( ; ; ) ' loops ?
JS
I was playing around today when I noticed that some of my objects in Chrome 's console were being displayed as Object instead of the constructor function name.This was odd , so I boiled it down to the following code : In the above code b , is not created via a Object.create and yet when logged it says Object . I do n't...
function Baz ( ) { this.baz = true ; } var b = new Baz ( ) ; var c = Object.create ( b ) ; console.log ( b ) ; // why is b outputting with Object not Baz ?
Object.create alters console output of proto object in Chrome ?
JS
I am attempting to build a tool where a user ranks items , and have come across the wonderful sortable package for R , which makes building and capturing the order of a custom drag-and-drop user interface very easy.While it is very easy to capture the order of the objects in the interface behind the scenes , I am strug...
library ( shiny ) library ( shinydashboard ) library ( sortable ) ui < - dashboardPage ( dashboardHeader ( ) , dashboardSidebar ( ) , dashboardBody ( htmlOutput ( `` foodrankingform '' ) ) ) server < - function ( input , output , session ) { output $ foodrankingform < - renderUI ( { fluidRow ( column ( tags $ b ( `` Fo...
Add index to sortable object text in R Sortable
JS
I want to keep my scripts organized in one .js file for all my site ( I have a mess right now ) , something like namespaces and classes in C # ... Is this an idiomatic layout in jQuery and JScript ?
( function ( $ ) { //private variables $ .divref = $ ( `` # divReference '' ) ; //Namespaces window.MySite = { } ; window.MySite.Home = { } ; window.MySite.Contact = { } ; //Public function / method window.MySite.Home.Init = function ( params ) { alert ( `` Init '' ) ; MySite.Home.PrivateFunction ( ) ; $ .divref.click ...
Is this a good structure for my jQuery scripts ?
JS
After reading this section about component interaction — I 've noticed that there is another way of communicating from child to parent ( which was n't really documented there ) : It turns out that if I have a parent class : And in the child component - I Inject a parent type into the ctor : Then Angular sees that i 'm ...
@ Component ( { selector : 'my-app ' , template : ` < div > < h2 > Hello { { name } } < /h2 > < my-item > < /my-item > < /div > ` , } ) export class App { name : string ; go1 ( ) { alert ( 2 ) } constructor ( ) { } } @ Component ( { selector : 'my-item ' , template : ` < div > < input type= '' button '' value='invoke p...
Angular — an undocumented child-to-parent communication ?
JS
What is the most efficient way of conveying the statement above ?
if ( pf [ i ] .length > highest ) { highest = pf [ i ] .length ; }
What is the javascript shorthand for this ?
JS
I 'm relatively new to JS world.I am used to write UI with QT ( great tools to build UI ! ) . With the QT I 'm doing a class for each element : If I have a table with some elements I have a class for each element and a class for the table ( maybe also for the rows ) . Each class contains the data and the method for man...
< script type= '' text/javascript '' > function UsersList ( path ) { this.path = path ; $ ( ' # userList > tbody ' ) .empty ( ) ; this.loadAjax ( ) ; } UsersList.prototype.loadAjax = function ( ) { var that = this ; $ .getJSON ( this.path , function ( users ) { that.fillUsers ( users ) ; } ) ; } ; UsersList.prototype.f...
JS and OOP : abuse of ` that = this ` pattern
JS
I 've got the following use case in a React component.It is a search user input that uses React Autosuggest . Its value is always an ID , so I only have the user ID as a prop . Therefore at first load to show the username value , I need to fetch it at first mount.EDIT : I do n't want to fetch the value again when it ch...
type InputUserProps = { userID ? : string ; onChange : ( userID : string ) = > void ; } ; // Input User is a controlled inputconst InputUser : React.FC < InputUserProps > = ( props ) = > { const [ username , setUsername ] = useState < string | null > ( null ) ; useEffect ( ( ) = > { if ( props.userID & & ! username ) {...
React hooks : why does useEffect need an exhaustive array of dependencies ?
JS
I 'm looking for a smart ES6 way to reduce array of objects into totals-by-property-object.for a sample data : following code : throws an error : Uncaught TypeError : Can not read property 'mon ' of undefinedeven if reduce is initialized with { mon:0 , tue:0 ... } instead of { } .Is there a non-for-loop solution ? p.s ...
const src = [ { mon:1 , tue:0 , wed:3 , thu:5 , fri:7 , sat:0 , sun:4 } , { mon:5 , tue:3 , wed:2 , thu:0 , fri:1 , sat:0 , sun:6 } ] ; const res = src.reduce ( ( totals , item ) = > Object.keys ( item ) .forEach ( weekday = > totals [ weekday ] += item [ weekday ] ) , { } )
Reduce array of object to totals by property object
JS
I have a PHP script being loaded by JS through JQuery 's $ .ajax.I measured the execution time of the PHP script using : It measured somewhere less than 1 second . There are no prepend/append PHP scripts.In the JS $ .ajax code , I have measured the execution time by : The time is the same for the time received and the ...
$ start = microtime ( ) ; // top most part of code// all other processes that includes AES decryption $ end = microtime ( ) ; // bottom part of codefile_put_contents ( 'LOG.TXT ' , 'TIME IT TOOK : '. ( $ end- $ start ) . `` \n '' , FILE_APPEND ) ; success : function ( response ) { console.log ( date ( ' g : i : s a ' )...
Inconsistent loading time for JS and PHP
JS
Hi I 've got a simple question . I 've this code below , i use ajax three times in very similiar ways the only things that change are the data passed and the id of the target . Is there a way to group these instructions in a simple one ? ThxD .
$ ( ' # fld_email ' ) .focusout ( function ( ) { var request_email = $ ( this ) .val ( ) ; $ .ajax ( { type : '' GET '' , url : `` autocomplete.asp '' , data : `` fld=firstname & email= '' +request_email , beforeSend : function ( ) { $ ( ' # fld_firstname ' ) .addClass ( 'ac_loading ' ) ; } , success : function ( msg )...
How to group rules in jquery
JS
Goal : Display a post excerpt for each post in the post list of an Eleventy blogI 'm adapting this starter project as my own blog.I 'm referring to this Eleventy documentto get the post excerpt.My code : I started by editing my .eleventy.js to enable gray-matter excerpt , per the above document , like so : Next , I add...
module.exports = function ( eleventyConfig ) { eleventyConfig.addPlugin ( pluginRss ) ; eleventyConfig.addPlugin ( pluginSyntaxHighlight ) ; eleventyConfig.addPlugin ( pluginNavigation ) ; eleventyConfig.setDataDeepMerge ( true ) ; eleventyConfig.setFrontMatterParsingOptions ( { excerpt : true } ) ; /* file continues b...
How do I use an excerpt from Eleventy 's gray-matter ?
JS
If my script executes a function that returns e.g . a huge object that I do n't want to use or store , is it better/faster/less memory intensive to call that function with the void operator ? Or will it decrease the performance because the return value will just be overwritten ? Just created a test : http : //jsperf.co...
void myFunc ( ) ;
JavaScript void performance
JS
I 'm having a little trouble working out how my JavaScript should be structured , etc..My OOP skills in languages such as PHP , ActionScript 3 and so on are what I 'm assuming to be on-par , but JS is lacking this which has thrown me off quite a bit in my learning.I have a vague understanding of the prototype feature w...
var slideshow = { property : value , /** * This is a method */ myMethod : function ( ) { // do method things } } ; // -- -- -- slideshow.property ++ ; slideshow.myMethod ( ) ; var myslideshow1 = new Slideshow ( ) ; var myslideshow2 = new Slideshow ( ) ; myslideshow1.property = 10 ; myslideshow2.property = 16 ;
How should I look at structuring my JavaScript ?
JS
Forgot to remove the i modifier in a pattern , that should strip out non alphanumeric characters : And wondered , that [ \W_ ] will match i , k and with + quantifier even s : DWithout the i modifier it 's working fine . And of course the i modifier is a mistake , but I do n't understand this weird behavior : regex101 a...
str.replace ( / [ \W_ ] +/gi , '' `` ) ;
Why does [ \W_ ] + with i modifier in Javascript regex match i , k , s ?
JS
Consider : I am trying to understand the memory implications of calling f1 and f2.Regarding n11 , this answer says : For some very small and normally inconsequential value of `` wasted '' .JavaScript engines are very efficient these days and can perform awide variety of tricks/optimizations . For instance , only thefun...
function f1 ( ) { function n11 ( ) { .. lots of code .. } ; const n12 = ( ) = > { .. lots of code .. } ; return n11 ( ) +n12 ( ) +5 ; } const f2 = ( ) = > { function n21 ( ) { .. lots of code .. } ; const n22 = ( ) = > { .. lots of code .. } ; return n21 ( ) +n22 ( ) +5 ; }
Javascript memory implication of nested arrow functions
JS
This is mostly a language-agnostic question . If I 'm waiting for two events to complete ( say , two IO events or http requests ) , what is the best pattern to deal with this . One thing I can think of is the following ( pseudo js example ) .Is this the most effective pattern , or are there more elegant ways to solve t...
request1.onComplete = function ( ) { req1Completed = true ; eventsCompleted ( ) ; } request2.onComplete = function ( ) { req2Completed = true ; eventsCompleted ( ) ; } eventsCompleted = function ( ) { if ( ! req1Completed || ! req2Completed ) return ; // do stuff }
running code when two events have triggered
JS
I want to show notification on master page and for that I am using JQuery dialog.I could achieve Auto show and hide on page load using below code . But I want to keep dialog open if it is hovered by Mouse.This work fine but it hides a dialog even if I hover div # dialog.I want to keep dialog open if it hovers .
$ ( document ) .ready ( function ( ) { $ ( `` # dialog '' ) .dialog ( { autoOpen : false , draggable : false , resizable : false , height : 100 , hide : { effect : 'fade ' , duration : 2000 } , open : function ( ) { $ ( this ) .dialog ( 'close ' ) ; } , close : function ( ) { // $ ( this ) .dialog ( 'destroy ' ) ; } , ...
Keep JQuery dialog open on mouse hovering
JS
( I 'm quite new in web-design ) I have a list of links ( sections on current page ) that can extend to multiple lines depending on viewport size . Links are separated by a vertical line ( border-left ) : I want to avoid the border to be displayed for first element of each line . I 've managed to avoid it for the the f...
.links a { display : inline-block ; } .links a : not ( : first-child ) { border-left : 1px solid black ; padding-left : 15px ; } .links a : not ( : last-child ) { padding-right : 15px ; } < div class= '' links '' > < a href= '' # '' > Link number 1 < /a > < a href= '' # '' > Link number 2 < /a > < a href= '' # '' > Lin...
Setting border on first element per line
JS
I need to find every element in the json array with same name property for example here Alaska is two times then I need to compare the lastupdate of both of the objects and choose the one with latest update time . Adopting from an answer in stackoverflow ( sorry I lost the link ) I can remove the object with same name ...
[ { `` name '' : `` Alaska '' , `` Republican_fre '' : 3 , `` Democrats_fre '' : 0 , `` winner '' : `` R '' , `` iso_2 '' : `` AK '' , `` electoral_vote '' : 3 , `` totalComponents '' : 3 , `` date '' : `` 29.06.2016 '' , `` lastupdate '' : `` 1467233426 '' } , { `` name '' : `` Alabama '' , `` Republican_fre '' : 3 , ...
Find a JSON object with property matched more than once
JS
The score will increase every time when I move the mouse , but how should I add a function to decrease the score until 0 when the mouse is not moving ?
$ ( document ) .ready ( function ( ) { var score = 0 ; $ ( `` body '' ) .mousemove ( function ( ) { score++ ; $ ( `` # result '' ) .val ( score ) ; console.log ( score ) ; } ) ; } ) ;
How to make function work when the mouse not moving ?
JS
Guys I 'm facing a problem in react-slick slider . I 'm rendering a card on the slider depends upon the array length . I 'm also rendering custom next and previous buttons which triggers the next and previous functions to change the slide . I also wanted to this slider to be responsive . It means it has a functionality...
import React , { useState , useRef } from `` react '' ; import Slider from `` react-slick '' ; // Constant Variables// Slides scroll behavior on different sizesconst TOTAL_SLIDES = 6 ; const DESKTOP_SLIDES_SCROLL = 3 ; const TABLET_SLIDES_SCROLL = 2 ; const MOBILE_SLIDES_SCROLL = 1 ; /** * It will return the JSX and re...
Prev and Next button is not working correctly at the breakpoints
JS
I have a circle which orbits every 10 seconds . And i am trying to cast a shadow which is angled towards the orbit origin ( the light source ) whilst also taking into account the camera angle as well.The shadow works for some angles but as the camera goes more edge on or more top down , it starts to look less accurate ...
ctx.beginPath ( ) ; //rotate shadow with the planetctx.translate ( originX + obj [ i ] .x , originY + obj [ i ] .y ) ; ctx.rotate ( obj [ i ] .angle ) ; //rotate around originctx.translate ( - ( originX + obj [ i ] .x ) , - ( originY + obj [ i ] .y ) ) ; var offsetX = - ( 10 * Math.sin ( obj [ 0 ] .angle ) ) ; //i feel...
Moving a shadow around a circle
JS
I need to be able to determine when an object is created ( not a DOM element -- a javascript object ) .An answer to this question has some very useful looking code for creating observable properties , so you can have a function fire when a property changes.In my situation I need to do something when the object/property...
ThisStuff = ( function ( ) { // blah blah return self ; } ( ) ) ; $ ( document ) .ready ( function ( ) { wheneverIsAvailable ( window , 'ThisStuff ' , function ( object ) { object.init ( args ) ; } ) } ) ;
Watch for a property creation event ?
JS
As the title describes , I am trying to animate a dashed arrow . I want it to look as close as possible to this on this site.I was able to make an arrow although I 'm not sure that this was the correct way of making such arrow . I 'm assuming I 'd have to have drawn it with SVG ... Also the animation looks weird and I ...
body { margin : 0 ; font-size : 16px ; line-height : 1.528571429 ; padding : 0 ; height : 100 % ; } body # contact { height : calc ( 100vh - 40px ) ; background-color : # ffffff ; } body # contact .to-top-btn-wrapper { position : absolute ; z-index : 999 ; left : 7 % ; bottom : 15 % ; } body # contact .to-top-btn-wrapp...
How to animate a dashed arrow ?
JS
I 'm trying to do something after an 'enter ' event in a directive . The event is n't firing when the template is loaded in.Here is the app declarationInitially I am using the routing provider to give me a template page . I am then trying to use a directive inside these templates to provide another view . This works by...
angular .module ( 'MyApp ' , [ 'ngAnimate ' , 'ngCookies ' , 'ngResource ' , 'ngRoute ' , 'ngSanitize ' , 'ngTouch ' ] ) .config ( function ( $ routeProvider ) { $ routeProvider .when ( '/ ' , { templateUrl : 'views/home.html ' , controller : 'HomeCtrl ' } ) .when ( '/in-the-community ' , { templateUrl : 'views/in-the-...
Animation in AngularJS Directive , event not firing
JS
I have an array : and this is my function filter : If 'AA ' not found in filter I want it get the 'Null ' Object.My purpose I want the result like this : How I do ? Thanks for help .
const data = [ { location : `` Phnom Penh '' , sale : 1000 } , { location : `` Kandal '' , sale : 500 } , { location : `` Takeo '' , sale : 300 } , { location : `` Kompot '' , sale : 700 } , { location : `` Prey Veng '' , sale : 100 } , { location : `` Seam Reap '' , sale : 800 } , { location : `` Null '' , sale : 0 } ...
How to get default array filter object if it not exist in Javascript
JS
As per my understanding in prototype . If you access a member of an object it will get it from prototype object when not available in that object.My questions is : since functions in Javascript are objects why funcObj.greet - > undefined , but obj.greet - > hello ?
function funcObj ( ) { } funcObj.prototype.greet = `` hello '' ; console.log ( funcObj.greet ) // undefined ? ? ? console.log ( funcObj.prototype.greet ) // hellovar obj = new funcObj ( ) ; console.log ( obj.greet ) ; // hello
Function object prototype
JS
I 'm trying with the following code to execute urql useQuery only at once . But for some reason it is getting called on every re-render.As per the docs https : //formidable.com/open-source/urql/docs/basics/queries/ # pausing-usequerythis query should be paused initially on the render and it should only get executed whe...
const [ { fetching , data , error } , reExecute ] = useQuery ( { query : INITIAL_CONFIG_QUERY , pause : true } ) ; React.useEffect ( ( ) = > { reExecute ( ) ; } , [ ] ) ;
urql useQuery 's pause option does n't freezes the request temporarily
JS
Consider following arrays : I want to call my function myFunc ( arg1 , arg2 , arg3 ) with all argument combinations . But I want to avoid to `` foreach '' hell.Is it possible write function that allows me that , so i can call it some like : ideally with variable count of arrays ( myFunc arguments ) ? EDIT : so function...
var array1 = [ true , false ] ; var array2 = [ 1 , 2 ] ; var array3 = [ `` a '' , `` b '' , `` c '' ] ; cartesianCall ( array1 , array2 , array3 , myFunc ) ; myFunc ( true , 1 , `` a '' ) ; myFunc ( true , 1 , `` b '' ) ; myFunc ( true , 1 , `` c '' ) ; myFunc ( true , 2 , `` a '' ) ; myFunc ( true , 2 , `` b '' ) ; my...
JS call function with all possible arguments permuted
JS
This article defines instanceof as below : The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.That 's a fair explanation and life was good until I came across this code from the book Eloquent Javascript : Let 's create an instance of RTextCell and execute ...
function TextCell ( text ) { this.text = text.split ( `` \n '' ) ; } TextCell.prototype.minWidth = function ( ) { return this.text.reduce ( function ( width , line ) { return Math.max ( width , line.length ) ; } , 0 ) ; } TextCell.prototype.minHeight = function ( ) { return this.text.length ; } TextCell.prototype.draw ...
Javascript : Still confused by the instanceof operator
JS
I did an experiment today to see what I can do with < div > s . So I made a simple Paint-like program , which you can draw with < div > s.This is part of the code . It works , but there are gaps between dots . So I created a function called fillDot which will draw a line from point A ( last point ) to point B ( current...
$ ( window ) .mousemove ( function ( e ) { if ( ! mousedown ) { return false ; } var x = e.clientX , y = e.clientY ; drawDot ( x , y , ele ) ; lastX = x ; lastY = y ; } ) ; drawDot ( x , y , ele ) ; fillDot ( lastX , lastY , x , y , ele ) ; function fillDot ( lx , ly , x , y , canvas ) { var rise = y - ly , run = x - l...
Fill gap between 2 point with < div >
JS
Ok so QA gave me this bug where if a date had a single character starting the month , day or year part of the date ( formatted MM/dd/yyyy ) , that ( ONLY in IE ) it would parse the date but change it.. So digging around and sure enough its being VERY weird..This is some sample code of what I am talking about in IEAnd h...
$ ( `` # dates '' ) .append ( `` < li > 04/30/2012 = `` + new Date ( `` 04/30/2012 '' ) .toString ( ) + '' < /li > '' ) ; $ ( `` # dates '' ) .append ( `` < li > a04/30/2012 = `` + new Date ( `` a04/30/2012 '' ) .toString ( ) + '' < /li > '' ) ; $ ( `` # dates '' ) .append ( `` < li > b04/30/2012 = `` + new Date ( `` b...
What the heck is IE new Date ( string ) doing ?
JS
Given some object y , how can I find out the most specific X such that the expressionevaluates to true ? For example , the following two expressions both evaluate to true ... but Array is more specific than Object .
y instanceof X [ ] instanceof Object [ ] instanceof Array
How to get most specific X such that y instanceof X is true ?
JS
If you go to a Wikipedia page in Chrome and ctrl+scrollup or ctrl+scrolldown the resize is done in an animation.How is this achieved ? ( In FF only the links in the top right corner animate )
Read View source View history
resizing animation on wikipedia
JS
When I move : To : Then the script starts showing on the page from the bold part onwards : style= '' border : none ; overflow : hidden ; width:500px ; height:23px ; '' allowTransparency= '' true '' > ' } , s ) ; var o=this , u=false , a , f , l , c , h , p , d=e ( window ) .height ( ) , v=e ... The script is attributed...
< script src= '' js/jquery.prettyPhoto.js '' > < /script > < script type= '' text/javascript '' > ... < /script > Class : prettyPhotoUse : Lightbox clone for jQueryAuthor : Stephane Caron ( http : //www.no-margin-for-errors.com ) Version : 3.1.5
embedding jquery.prettyPhoto causes script to show on page
JS
I am in the process of debugging another developer 's Javascript for a project at work.I am probably a mid-level Javascript developer on a good day and I 've come across a for loop that appears broken : Can anyone tell me if this is indeed a mistake or if in some instances this is a perfectly valid way to do Advanced t...
for ( i = 0 ; ; i++ )
Javascript for loop missing middle part : error or advanced ?
JS
Here is my function atm : It works great but I want to add the option to remove the box with another click , figured I 'd do it with an if statement but I 'm not 100 % on the syntax in Jquery . I want something along the lines of : How would I write the if statement for this ? SOLUTION : I had to change the visibility ...
$ ( document ) .ready ( function ( ) { $ ( `` # knd '' ) .click ( function ( ) { $ ( `` # wars '' ) .animate ( { opacity : ' 1 ' } ) ; } ) ; } ) ; if ( # wars is visible ) { $ ( `` # wars '' ) .animate ( { opacity : ' 0 ' } ) ; $ ( document ) .ready ( function ( ) { $ ( `` # knd '' ) .click ( function ( ) { if ( $ ( ``...
How do I write this if condition with Jquery ?
JS
JSON Excerpt : I would like to iterate the JSON Tree and obtain a list of 'd ' series values with the navigation path of each 'd ' node , such as Here , I wrote a function as follows : This function only generate the 'name ' and 'value ' parts of each 'd ' record , but how can I get the 'path ' part done in this functi...
{ `` a '' : { `` b1 '' : { `` c1 '' : { `` d1 '' : `` D1 '' , `` d2 '' : `` D2 '' , `` d3 '' : `` D3 '' } , `` c2 '' : { `` d4 '' : `` D4 '' , `` d5 '' : `` D5 '' } } , `` b2 '' : { `` c3 '' : { `` d6 '' : D6 } } } } [ { 'name ' : 'd1 ' , 'value ' : 'D1 ' , 'path ' : [ ' a ' , 'b1 ' , 'c1 ' ] } , ... ] function GetPara...
How Can I Get the Navigation Path of a Node in a JSON Tree While Iterating Through the Tree
JS
I have been learning some basic JavaScript lately and have run into a problem . My Code looks like this : My problem is that when I run the code and enter my name the page will say this : You LOVE BACON ! ! ! You have not entered your name yet.My else statement appears with my if statement as well .
< html > < body > < script type= '' text/javascript '' > var name= window.prompt ( `` Type Your Name . '' ) if ( ( name=='Ethan ' ) ) document.write ( `` You LOVE BACON ! ! ! '' ) else document.write ( `` You Have not entered your name in yet . '' ) < /script > < /body > < /html >
If and Else Statements Bug
JS
I was messing around with JavaScript , and noticed that this can never be a primitive . What am I talking about ? Let me explain.Take this function for example.They are both 'object ' , not 'string ' or 'number ' , like I 'd expect.After a bit of confusion ( and messing with instanceof ) , I figured out what 's going o...
function test ( ) { return typeof this ; } test.call ( 'Abc ' ) ; // 'object'test.call ( 123 ) ; // 'object ' function element ( ) { var $ e = $ ( this ) , $ d = $ e.closest ( 'div ' ) ; } element.call ( ' # myID ' ) ;
Why ca n't this be a primitive ?
JS
im using android to open a local web file and then iterate the dom and apply some changes BUT while its iterating the webview stop to render the page at some random part , look the gif : what i already didand now to avoid the rendering issues at each dom change , i created a documentFragment and change the dom in it ( ...
var elements = document.querySelectorAll ( `` P '' ) ; for ( var i = 0 ; i < elements.length ; i++ ) { //just iterating at the gif im chaging //but i tried without changing , just iterating and the result still the same } var x = document.getElementById ( 'contentRoot ' ) ; //getting the element root from the DOCUMENT ...
Dom iterating causing half webview rendering
JS
I 'm having trouble with uniting the ionux/phactor PHP library , and the indutny/elliptic JS library.One library is being used at a LAMP server , the other via Nodejs at Amazon Lambda.I generate one key pair with the PHP library ; sign sha256 hash data and save results as JSON output.Outputs : I saved the output to a J...
$ ec = KeyManager : :instance ( ) - > getECKeysByHash ( $ k = '122e43fd75dd0492a259146ab5dfd5c6 ' ) ; return $ response = [ 'source ' = > [ 'message ' = > $ m = 'asd ' , 'hash ' = > $ h = hash ( 'sha256 ' , $ m ) , 'hash_signed ' = > $ ec- > sign ( $ h ) , ] , 'ec ' = > [ 'key ' = > $ k , 'keys ' = > config ( KeyManage...
Matching sec256k1 keys in JS and PHP
JS
Is it guaranteed that this codewill wait for the code passed to the runEmbeddedJSInPageEnvironment to finish first , and only then remove it from the page by calling removeChild function ? Or can it be removed before this code finished to execute ?
function runEmbeddedJSInPageEnvironment ( code ) { var e = document.createElement ( 'script ' ) ; e.type = 'text/javascript ' ; e.appendChild ( document.createTextNode ( code ) ) ; ( document.head || document.documentElement ) .appendChild ( e ) ; e.parentNode.removeChild ( e ) ; } runEmbeddedJSInPageEnvironment ( `` $...
Will injected JS code finish before removing
JS
I see code like this all over the webWhy do that instead ofI do n't think laziness or ignorance has anything to do with it . This is out of jQuery 1.4.2They do it all over the place .
var days= `` Monday Tuesday Wednesday Thursday Friday Saturday Sunday '' .split ( `` `` ) ; var days = [ `` Monday '' , `` Tuesday '' , `` Wednesday '' , `` Thursday '' , `` Friday '' , `` Saturday '' , `` Sunday '' ] ; props : `` altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey cur...
Why do I see javascript arrays getting created with string.split ( ) ?
JS
I have a chart created using the amCharts library . But I face an unwanted crop in the image which is on top of each bar when it goes too high , as I 've highlighted here : Please help I do n't want to have that cropping.Here is the CSS code : And here is the last part of JavaScript code : EDIT : When I add zoom : 0.5 ...
# chartdiv { width : 100 % ; height : 500px ; padding : 70px 0 ; border : 3px solid green ; } body { margin : 0 0 0 0 ; overflow : hidden ; background-color : transparent ; font-family : -apple-system , BlinkMacSystemFont , `` Segoe UI '' , Roboto , Helvetica , Arial , sans-serif , `` Apple Color Emoji '' , `` Segoe UI...
How do I get rid of this unwanted cropping ?
JS
I have this little problem ... I have this asp.net website.I have a menu , all done with html and css.So when I click on home , the ajax loads the other content into the specified div element.Working 100 % .In the content that was loaded into the div element , I have a button . An ASP.NET button.When I click on the but...
//Load the Home page on click. $ ( document ) .ready ( function ( ) { $ ( '.home ' ) .click ( function ( ) { $ ( `` # content '' ) .load ( `` html/home/home.aspx '' ) ; } ) ; } ) ; < asp : Panel ID= '' pnlAddNewBlog '' runat= '' server '' > < asp : TextBox ID= '' txtAddNewBlog '' runat= '' server '' TextMode= '' MultiL...
jQuery AJAX and ASP.NET
JS
In my react native app , contains multiple TextInputs for a form which are rendered like this : In the onChangeText function , the value of the textinput is edited using redux and the form is validated as so : This means the TextInput 's value does n't get updated immediately so when the user types relatively fast , th...
{ this.props.steps.map ( step , index ) = > ( < TextInput multiline= { true } value= { this.props.steps [ index ] } placeholder= '' Enter Step '' onChangeText= { value = > this.handleFieldChange ( value , index ) } style= { { padding : 10 , fontSize : 15 } } / > ) } handleFieldChange = async ( value , index ) = > { var...
React Native Textinput Flickers when using Redux
JS
I developed one web-based monitoring system Using js and WebRTC and now I want to develop notification function if the sound goes beyond some level.I 'm taking permission for video and audio and after permission , I want to use the function for sound notification .
navigator.mediaDevices .getUserMedia ( { audio : true , video : true } ) .then ( stream = > { // Display your local video in # localVideo element localVideo.srcObject = stream ; // Add your stream to be sent to the conneting peer pc.addStream ( stream ) ; // call function for sound check } , onError ) ;
How to get Volume level using JavaScript ?
JS
I 'm working with a new application at work that we 're building out using Knockout.js and jQuery . I prefer to `` use strict '' in my scripts , but since some of the libraries we 're using do n't work with `` use strict '' then I have to use the functional form.I do n't like placing javascript inside < script > tags i...
$ ( ( function ( win ) { `` use strict '' ; win.myFunction = function ( ) { // do stuff } ; } ( window ) ) ) ;
How are functions scoped/namespaced within a < script > tag ?
JS
Is there a way for typeof to return what an object is ? returns `` object '' also returns `` object '' . Is there a way in js to return `` array '' ? On top of that , is there a way to tell if an object is a DOM object , a javascript object or whatever object ?
typeof { } ; typeof [ ] ;
A more refined Javascript typeof ?
JS
Google is n't helping me figure this one out . Is there any reason not to do the following : Instead of the doing it this way : Basically I find the code much easier to read when it 's in the jQuery selector format , even though it does n't need to be.Both methods appear to work the same.Thanks !
var test = $ ( 'something ' ) ; $ ( test ) .stuff ( ) ; var test = $ ( 'something ' ) ; test.stuff ( ) ;
Any reason not to use $ ( test ) .stuff ( ) ; vs test.stuff ( ) ; given that test = $ ( 'something ' ) ; ?
JS
What is the recommended way to check if an object property like obj.prop.otherprop.another is defined ? this works well , but enough ugly .
if ( obj & & obj.prop & & obj.prop.otherprop & & obj.prop.otherprop.another )
JavaScript check if property defined
JS
I am using js/jQuery and am attempting to create a true clone- I 'm currently using jQuery for this . I would expect that in multi-level objects even the child objects should be deep cloned , but this appears to not be the case . Below is my test code and out put that leads me to believe that jQuery 's deep clone does ...
function deepClone ( obj ) { return $ .extend ( true , { } , obj ) ; } ; var orig = { } ; orig.companyData = { } ; orig.companyData.TEST= 1 ; var deep1 = deepClone ( orig ) ; deep1.companyData.TEST= 0 ; var deep2 = deepClone ( orig ) ; console.log ( `` orig : `` + orig.companyData.TEST ) ; console.log ( `` deep1 : `` +...
jQuery deep clone is n't recursive
JS
How can you create an html element that when dragged from the browser into a text editor , hidden text on or in the dragged element will be pasted into the editor ? My first thought was to use the href attribute on the anchor tag : This works great in chrome , but firefox and safari remove spaces from the href value wh...
< a href= '' hidden message text here '' > Drag me into a text editor ! < /a >
Hidden text that can be dragged from the browser ?
JS
Inside the Javascript console , if I execute : The window will resize , but if I just execute : then nothing happens . I understand the reason for this behavior . How can I detect situations where window.resizeTo will do nothing ?
m = window.open ( location.origin ) ; m.resizeTo ( 400 , 400 ) ; window.resizeTo ( 400 , 400 ) ;
Can it be determined if window.resizeTo will work ?
JS
Talk is cheap ; show me the code.I had read ydkjs book and Im familiar with call-site and dynamic this binding , but I do n't understand why the last function call has window as its this context ; in this controlled experiment that only thingthat is changed ( ) and comma operator and as you can see in the last statemen...
// equals to this.fellan = `` window '' var fellan = `` window '' ; function f ( ) { console.log ( this.fellan ) } ; var a = { fellan : `` object '' , fn : f } ; a.fn ( ) ; // `` object '' -- > fine ( a ) .fn ( ) ; // `` object '' -- > fine ( 1 , a ) .fn ( ) ; // `` object '' -- > fine ( a.fn ) ( ) ; // `` object '' --...
Why comma operator changes ` this ` in function call
JS
It seems that Chrome forces hardware-accelerated transforms on text that is on top of a canvas element.Can anyone help me understand this behavior ? Ultimately , I 'd like to scale text on top of a canvas element without having the text converted to a texture.This fiddle shows the issue : http : //jsfiddle.net/Gb6h4/1/...
// Get a reference to the canvas and its contextvar $ canvas = $ ( `` canvas '' ) ; var ctx = $ canvas [ 0 ] .getContext ( '2d ' ) ; // Make the canvas fullscreenvar width = $ ( window ) .width ( ) , height = $ ( window ) .height ( ) ; $ canvas.attr ( { width : width , height : height } ) ; // In Chrome , modifying the...
Chrome transforms text differently over a canvas element . Why ?
JS
I know that ng-non-bindable allows a given element and its children to be not compiled as a template . It seems it was designed to be peppered throughout a template as needed . Is there a way to tell Angular to not process a given element , BUT to `` poke holes '' into that and allow selected child elements to be proce...
< div ng-non-bindable > < div > { { 2+2 } } < /div > < div ng-bindable > { { 2+2 } } < /div > < /div > < div ng-non-bindable > < div ng-repeat= '' n in [ 1,2,3 ] '' > { { n+2 } } < /div > < div ng-bindable ng-repeat= '' n in [ 1,2,3 ] '' > { { n+2 } } < /div > < /div >
Angular : Selectively compile templates
JS
I have a parent element with a real lot of child elements ( 1000s ) . I am looking for the fastest possible way to get a handle to the last child element . The options I 've found are : and Any opinions on which one is reliably faster across browsers ? EDITI wrote a test in jsfiddle to measure this out and it turns out...
$ ( '.parent .child ' ) .last ( ) $ ( '.parent .child : last ' )
Which is more efficient - $ ( 'selector ' ) .last ( ) or $ ( 'selector : last ' ) ?
JS
I have two < div > elements , and the following JavaScript code : This , as I expect , produces an < input > element within each of the two < div > elements.Now when I create a new instance of myObject and call insert ( ) again I will be expecting 4 < input > elements , two in each < div > . Weirdly , I only get 3 < in...
var myObject = { $ input : $ ( ' < input / > ' ) , insert : function ( ) { $ ( 'div ' ) .append ( this. $ input ) ; $ ( 'div ' ) .append ( ' ' ) ; } } ; myObject.insert ( ) ;
JavaScript unexpected object behavior with jQuery
JS
I have a function foo and I wanted to add a sleep/wait function to make a kind of DOM elements animation . I 've already done some research and I know that it 's impossible to pause a javascript function because it freezes browser - correct me if I 'm wrong . How can I overcome it ? $ someDiv refers to different DOM el...
function foo ( ) { while ( someCondition ) { var $ someDiv = $ ( '.someDiv : nth-child ( ' + guess + ' ) ' ) ; $ someDiv.css ( { 'background-color ' : 'red ' } ) ; wait 1000ms $ someDiv.css ( { 'background-color ' : 'blue ' } ) ; wait 1000ms if ( someCondition2 ) { doSomething ; } else { for loop } } } function sleep (...
How can I animate DOM elements in a loop with interval between each iteration ?
JS
Is there any shortcut ( actually a function ) in jQuery or Javascript to handle button press except something , or only something , e.g . : that will trigger only on [ a-z ] [ 0-9 ] buttons pressed and ignoring single shift or ctrl but handling shift+a = > A pressed ? P.S.i do know about if ( key.code == 123 ) then ...
$ ( input ) .keypress ( 'nonfunctional ' function ( ) { // do something } ) ;
Jquery keypress except : { something }
JS
I have been learning hooks in react for the past couple of days , and I tried creating a scenario where I need to render a big grid on screen , and update the background color of the nodes depending on the action I want to take . There are two actions that will change the background color of a node , and these two acti...
const Grid = ( ) = > { // grid array contains references to the GridNode 's function handleMouseDown ( ) { setIsMouseDown ( true ) ; } function handleMouseUp ( ) { setIsMouseDown ( false ) ; } function startAlgorithm ( ) { // call grid [ row ] [ column ] .current.markAsVisited ( ) ; for some of the children in grid . }...
React Hooks ( Rendering Arrays ) - Parent component holding a reference of children that are mapped vs Parent component holding the state of children
JS
I 've a div that I 'd like to maximise the size of , within a parent that 's based on a 100vh.The problem being that I have two p divs that can also change their height based on the width of the window , leading to a varying size.Now the quick and dirty solution might simply be to run a jQuery snippet to detect the siz...
* { margin : 0 ; padding : 0 ; font-family : Arial , san-serif ; } # parent { height : 100vh ; background : lightblue ; } p { font-size : 40px ; background : yellow ; } # p1 { top : 0 ; } # p2 { bottom : 0 ; position : absolute ; } div { background-color : red ; height : 100 % ; } < div id= '' parent '' > < p id= '' p1...
Maximising the height of a div with surrounding elements of variable height
JS
I am intermediate level javascript developer trying to understand how great javascript developer write their code and i decide to start looking into Backbone library as starting point . here is some code snippet for initial setup in backbone please help me to make sense out of it.code1 - is there any specific reason to...
( function ( ) { var root = this ; } ) .call ( this ) ; ( function ( root ) { } ) ( this ) ; var Backbone ; if ( typeof exports ! == 'undefined ' ) { Backbone = exports ; } else { Backbone = root.Backbone = { } ; } var Backbone = root.Backbone = { } ; var _ = root._ ; if ( ! _ & & ( typeof require ! == 'undefined ' ) )...
backbone library code patterns I could n't understand
JS
I 'm trying to figure out a way to structure a new framework for work capable of injecting plugins . The idea is to have each file be loaded asynchronously.Here is how I would love to configure my plugins : As I 'd be using inline functions ( within the DOM ) I thought of using a command queue which on load would invok...
< script id= '' target_root '' src= '' assets/js/target/target.js '' async= '' true '' > < /script > < script > var target = target || { } ; target.cmd = target.cmd || [ ] ; target.cmd.push ( function ( ) { target.loadPlugins ( [ { `` name '' : `` root '' , `` src '' : `` assets/js/target/target.root.js '' } , { `` nam...
javascript es5 async plugin architecture
JS
Hello i 'm fairly new to JavaScript and decided to learn more by following along the w3schools game tutorial.I decided to make it a platform game , however I have n't been able to figure out how to add a viewport that follows the player outside the canvas.Could anyone help me out ? Thanks in advance.Fiddle
//Backgroundvar Background ; //Objectsvar Player ; var Obstacle ; //Mobile buttonsvar UpBtn ; var DownBtn ; var LeftBtn ; var RightBtn ; //Endfunction startGame ( ) { Background = new component ( 656 , 270 , `` gray '' , 0 , 0 ) ; Player = new component ( 30 , 30 , `` blue '' , 200 , 75 ) ; Obstacle = new component ( 1...
JavaScript game viewport
JS
I am working on a custom scroll animation framework . Where I can control the sequence via a blob of json data.This code here uses some subscribers -- and although the forward/reverse animations are in place -- - the fade in/out is not working well - where the fades malfunction.Using json - I want to provide the skelet...
let data = [ { `` structure '' : { `` name '' : `` square '' , `` height '' : 30 , `` width '' : 30 , `` x '' : 0 , `` y '' : 0 , `` background '' : 'url ( `` https : //i.pinimg.com/originals/74/f3/5d/74f35d5885e8eb858e6af6b5a7844379.jpg '' ) ' } , `` frames '' : [ { `` animation '' : `` move '' , `` start '' : 0 , `` ...
Banana sprite js animation ( forward/reverse and fade ) with json data
JS
So on the net I 've come across a several ways to preload / redirect a webpage.Now 's the question is this the proper way to handle a redirect with preload ( Load the next page async while still showing the current page ) Or should I better stay with a regular redirect ? The next page contains a fullscreen video and a ...
$ .get ( `` page.php '' , function ( data ) { document.open ( ) ; document.write ( data ) ; document.close ( ) ; window.history.pushState ( `` Title '' , `` Title '' , `` /page.php '' ) ; $ .cache = { } ; } , `` html '' ) ; window.location = `` page.php '' ;
Normal redirect or preload
JS
I am given the task to build a test suit using testcafe and , as I write tests I stumble upon one particular question “ how much assertions is too much ? ” . Basically , after the tests are done , a report is generated . Looking at the report it is not intuitive . For example , If an element is not found on the webpage...
> Selector ( 'tads ' ) does not exist in the DOM . await t.click ( this.loginButton ) ; await t.expect ( this.loginButton.exists ) .ok ( `` I don ’ t see the login button '' ) ; await signup.newUserSignUp ( ) ; await t.expect ( this.loginButton.exists ) .notOk ( `` The login modal didn ’ t disappear '' ) ;
How much is too much assertions in automation testing ?
JS
In a NodeJS 6.10.2/SailsJS 0.12.13 based JavaScript application I experience since several months a strange error behavior.In a Sails controller , I try to retrieve a property of a literal object : However , in my case someObject is undefined . So , I 'd expect to get an error like ' Can not read property someProperty ...
console.log ( someObject.someProperty ) ; console.log ( `` I am still here ! `` ) ; mySailsControllerFunction : function ( req , res ) { console.log ( someObject.someProperty ) ; console.log ( `` I am still here ! `` ) ; res.json ( { `` foo '' : '' dahoo '' } ) ; } mySailsControllerFunction : function ( req , res ) { r...
Non existing property : EventEmitter memory error instead of proper error message
JS
Possible Duplicate : JavaScript : var functionName = function ( ) { } vs function functionName ( ) { } In JavaScript we can say : Or we could sayCan anyone explain to me how exactly these differ , which , if any , is more preferable , and under what circumstances would one use each ? Any links or external reading would...
function a ( ) { } ; var a = function ( ) { } ;
What is the difference between these two function declarations in JavaScript ?
JS
Back in the day ( yes I really am this old ) you could reference scripts out of a renamed zip file like this This was supported on IE4 , NS4 and Opera5 with identical mark-up and semantics , but has been consigned to the digital scrapyard . Why ? OK for those of you interested in the answer but not interested enough to...
< script archive= '' path/to.jar '' src= '' some.js '' > < /script >
Why minify when the transport will gzip ?
JS
Everything in JS is an object . I 've always known that , and I totally understand that . I know why { } ! == { } . It 's two different objects . Same as if you were to write out new Object ( ) == new Object ( ) . Some other examples : But , Strings are objects too ( it 's why you can do `` .replace ( ) and extend them...
{ } == { } // = > false [ ] == [ ] // = > false/ / == / / // = > falsenew String ( ) == new String ( ) // = > false `` == `` // = > true
In JavaScript , why do n't any objects equal each other , except strings ?
JS
So I 'm reading a book on AJAX , and they are talking about using inner function as a way to handle multiple requests . I understand that , but in this bit of code they used , I do n't understand how the variable XMLHttpRequestObject can still be used : My first qualm is when they delete XMLHttpRequestObject and then ,...
if ( XMLHttpRequestObject ) { XMLHttpRequestObject.open ( “ GET ” , dataSource ) ; XMLHttpRequestObject.onreadystatechange = function ( ) { if ( XMLHttpRequestObject.readyState == 4 & & XMLHttpRequestObject.status == 200 ) { document.getElementById ( “ targetDiv ” ) .innerHTML = XMLHttpRequestObject.responseText ; dele...
How does AJAX do antying if XMLHttpRequestObject is deleted and/or contains no value since it 's also set to null ?
JS
I 'm pretty new to ReactJS and redux , so I 've never really had to work with this before . I 'm retrieving data from an API call in my project . I want to modify the data by adding a new property to the object . However , because the code is not ran synchronously , the unmodified array is being returned ( I assume ) i...
export function loadThings ( ) { return dispatch = > { return dispatch ( { type : 'LOAD_THINGS ' , payload : { request : { url : API_GET_THINGS_ENDPOINT , method : 'GET ' } } } ) .then ( response = > { let things = response.payload.data ; // Retrieve all items for the loaded `` things '' if ( things ) { things.forEach ...
Synchronously populate/modify an array and return the modified array inside a promise
JS
THREE.Box3.setFromObject ( *object* ) returns wrong values . The best way to show you is by showing you how I work through it : I create 2 meshes from vertices . First one with the triangle ( ) function , the other with trapezoidForm ( ) .I use the returned value to create my mesh : And use that to place it in the scen...
var triangle = function ( base , height ) { return [ new THREE.Vector2 ( 0 , -height / 2 ) , new THREE.Vector2 ( -base / 2 , height / 2 ) , new THREE.Vector2 ( base / 2 , height / 2 ) ] ; } var trapezoidForm = function ( base , upperBase , height ) { return [ new THREE.Vector2 ( -base / 2 , height / 2 ) , new THREE.Vec...
setFromObject ( mesh ) returns wrong values , sometimes
JS
This code works in local , but when I deploy to Google App Engine I got the error `` Browser var is not defined '' . How can I define globally the browser variable in better way ? My goal is to launch puppeteer browser at startup and use the same instance to open a new webpage for each HTTP request.app.yml
const puppeteer = require ( 'puppeteer ' ) ; const express = require ( 'express ' ) ; const fs = require ( 'fs ' ) ; var port = process.env.PORT || 80 ; const app = express ( ) ; app.get ( '/request ' , async ( req , res , next ) = > { console.log ( browser ) //using browser var here < -- - // UnhandledPromiseRejection...
Global variable in Google App engine Nodejs Puppeteer