lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
JS
This is more of a sanity check than anything else . I 've found that when working with closures in Javascript I often use the following pattern to access the enclosing class from within the function : Obviously this works just fine , and it 's not even a big hassle to work with . There 's just this little itch in the b...
MyClass.prototype.delayed_foo = function ( ) { var self = this ; setTimeout ( function ( ) { self.foo ( ) ; // Be nice if I could use 'this ' here } , 1000 ) ; } ;
Accessing 'this ' in Javascript closure
JS
I have two js arrays , one contains strings , the other color codes , something like : I need to sort the first array by the length of the values , longer first . I know I can do something like : But this way I am losing the color assined to each string . How can I sort both arrays keeping the keys pairing ?
strings = [ 'one ' , 'twooo ' , 'tres ' , 'four ' ] ; colors = [ '000000 ' , 'ffffff ' , 'cccccc ' , '333333 ' ] ; strings.sort ( function ( a , b ) { return b.length - a.length ; } ) ;
Sort two arrays of different values maintaining original pairing
JS
displaying some tabs.while html page load on browser and display the content of it so it should display first tab information because it is set active.but active tab not displaying its content they are working after click on the tab.i simply want while i set active on any tab it should display its content without click...
< ! DOCTYPE html > < html > < head > < title > < /title > < style type= '' text/css '' > .sight_img { height : 80 % ; width : 100 % ; } .tab { overflow : hidden ; border : 1px solid # ccc ; background-color : # f1f1f1 ; } /* Style the buttons inside the tab */ .tab button { background-color : inherit ; float : left ; b...
why html tab is not displaying its content when it set by active ?
JS
I have a JavaScript object which looks like this.and I have some HTML code which looks like thisOn HTML I have stored which JavaScript variable to modify if I do any change to that field . I have written JavaScript code which look like this.Is there any better approach to this problem , currently I am using eval ( ) wh...
var myObj = [ { `` HOLIDAY '' : { `` Sun '' : `` Date '' , `` Mon '' : `` Date '' , `` Tue '' : `` Date '' , `` Wed '' : `` Date '' , `` Thr '' : `` Date '' , `` Fri '' : `` Date '' , `` Sat '' : `` Date '' } } ] < input data-event= '' change '' data-variable= '' myObj '' data-bind= '' [ 0 ] [ 'HOLIDAY ' ] [ 'Sun ' ] '...
JavaScript : Update a object value by retrieving variable names from string
JS
I 'm new to Objective javascript even I had a good amount of experience in Javascript . How do I pass my parameters to the calc closure here ? I want to pass the parameters to calc like ( calc.multiply ( 10,20 ) ) ; Thanks in advance..
var calc = ( function ( ) { var a = 5 ; var b = 0 ; return { add : function ( ) { return a + b ; } , subtract : function ( ) { return a - b ; } , multiply : function ( ) { return a * b ; } , divide : function ( ) { if ( b ! = 0 ) return a / b else { alert ( 'division by zero ' ) ; return false ; } } } } ) ( ) ; ​ conso...
passing parameter : Objective javascript
JS
I have some elements in my page and I need to refresh their contents every 5 seconds . The code that I 'm going to show you works well but it looks so long and repeating itself . When I use only setInterval function , page does n't loaded regularly before the interval comes . Can you suggest a better way to do this ? T...
var $ song= $ ( `` .song '' ) ; var $ album= $ ( `` .album '' ) ; var $ cover= $ ( `` .cover '' ) ; var $ background= $ ( `` .overlay-bg '' ) ; $ .ajax ( { url : `` song.php '' , success : function ( response ) { var nowPlaying= $ .parseJSON ( response ) ; $ song.html ( nowPlaying.song ) ; $ album.html ( nowPlaying.alb...
Is there a shorter way to refresh div
JS
I notice that with emscripten , even relatively small C++ files can quickly be turned into rather huge JavaScript files . Example : Compile this with a recent emsdk using a command likeThe resulting file is over 400k big . With -g thrown in I can doand see what kinds of functions we have there . Here are some examples ...
# include < memory > int main ( int argc , char** argv ) { std : :shared_ptr < int > sp ( new int ) ; } em++ -std=c++11 -s DISABLE_EXCEPTION_CATCHING=1 -s NO_FILESYSTEM=1 \ -s NO_BROWSER=1 -s NO_EXIT_RUNTIME=1 -O3 -o foo.js foo.cc grep -n '^function _ ' foo.js | c++filt -_ std : :__1 : :moneypunct < char , false > : :d...
Omit some C++ subsystems
JS
Say I have an array like so : How can I deconstruct it in into individual variables in increments of two ? So that let one = [ 1 , 2 ] , let two = [ 3 , 4 ] , etc ? I know that you can deconstruct an array using individual variables like so : But doing it in increments of two , is that possible ?
let arr = [ 1 , 2 , 3 , 4 , 5 , 6 , `` a '' ] let one , two , three ; [ one , two , three ] = arr
Deconstructing an array in increments of two
JS
I am using this color wheel picker , and I 'm trying to add a div as the dragger instead of having it embedded in the canvas.I created an outer div ( a wrapper ) , and inserted a div ( dragger ) , then the canvas . I made the dragger div 's position to absolute . Then in the redraw ( e ) function , I set the left and t...
dragger.style.left = currentX + 'px ' ; dragger.style.top = currentY + 'px ' ; var b = document.body ; var c = document.getElementsByTagName ( 'canvas ' ) [ 0 ] ; var a = c.getContext ( '2d ' ) ; var wrapper = document.getElementById ( 'wrapper ' ) ; var dragger = document.createElement ( 'div ' ) ; dragger.id = 'dragg...
Div is n't at right position
JS
I am trying to position an image above ( NOT before ) the text . Below is the code I have so far . I also posted the result I am getting and the one I want to achieve . My goal is , when the user hover the < p > I want to show an image above it , this mean I need to use absolute position because I do not want anything ...
< div id= '' wrap '' style= '' position : relative ; height : 100px ; width : 500px ; background : red '' > < img src= '' img/cat.png '' style= '' position : absolute ; `` > < p style= '' position : absolute ; `` > Some text here.. < /p > < /div >
How to position an image above the content
JS
Javascript code : It is working , just NetBeans says : `` Use the || operator ( Column [ where the ? is ] ) '' . I did n't find any explanation.What is it ? Thanks !
var a = ( b ) ? b : 40 ;
Use the || operator notice
JS
I have a jQuery script that looks through a list of divs , and then it 's children , and prints out : The item 's titleThe item 's descriptionAn issue I 'm noticing is that even though the two console.log ( ) s are next to each other in the inner $ .each ( ) , I 'd expect to see : Title 1 Description 1 Title 2 Descript...
$ ( '.ghx-backlog ' ) .each ( function ( ) { $ ( $ ( this ) .find ( 'div [ class*=has-issues ] ' ) ) .each ( function ( index ) { console.log ( $ ( this ) .find ( '.ghx-key > a ' ) .text ( ) ) ; //The Title console.log ( $ ( this ) .find ( '.ghx-summary > span ' ) .text ( ) ) ; //The Description } ) ; } ) ; < div id= '...
Logging sequence in $ .each ( )
JS
I have to do a sorting by start date time with a reference to current date time with multiple attributes . For ex , I have this list : and the current date time is 09-04-2019 15:15 , the desired output should be : I tried this but does n't include inplay param and also the ordering is not quite correctBasically the lis...
< ul > < li data-startDate= '' 09-04-2019 15:00 '' data-inplay=false > Name1 < /li > < li data-startDate= '' 09-04-2019 15:30 '' data-inplay=false > Name2 < /li > < li data-startDate= '' 09-04-2019 15:20 '' data-inplay=false > Name3 < /li > < li data-startDate= '' 09-04-2019 16:00 '' data-inplay=false > Name4 < /li > <...
javascript sort by nearest start date time to present to furthest away and another attribute
JS
This is my case.How can I map this into key : value pair so that the final output is { `` question 1 '' : `` answer 1 '' } ? The trick is that only if a property exists then it should be assigned to the new object as above example { `` question N '' : `` answer N '' } .I have tried combining .map ( ) and .filter ( ) , ...
data : [ { q : `` question 1 '' , a : `` answer 1 '' } , { q : `` question 2 '' } ] const obj = data.map ( e = > e.q ) .filter ( s = > s.a )
Map object if property is found in another array of objects
JS
Is using async and await the crude person 's threads ? Many moons ago I learned how to do multithreaded Java code on Android . I recall I had to create threads , start threads , etc.Now I 'm learning Javascript , and I just learned about async and await.For example : This looks way simpler than what I used to do and is...
async function isThisLikeTwoThreads ( ) { const a = slowFunction ( ) ; const b = fastFunction ( ) ; console.log ( await a , await b ) ; }
Is Javascript async and await the equivalent to mulithreading ?
JS
I have a sortable set up like this : I want to ignore elements with the nosort class from the sortable.This works good ; however , the index I get seems to include all elements in the sortable , not only those that can be sorted , so it ca n't really be used for what I need.Is there any easy way to avoid this ? Here 's...
$ ( '.sortable ' ) .sortable ( { items : ' > * : not ( .nosort ) ' , axis : ' y ' , stop : function ( event , ui ) { var index = ui.item.index ( ) ; // do something with the index } } ) ;
Sortable - Excluded items still affect index
JS
I 'm creating a game in which players will need to sort objects on the screen into the correct target locations . I 'm looking for a way to shuffle the objects so that no object starts in a correct location . So we do n't devolve into a mad world of double negatives , I 'm going to call the `` correct answer '' locatio...
var sort_items = [ { `` avoid '' : [ `` target1 '' , `` target2 '' ] } , { `` avoid '' : [ `` target1 '' , `` target2 '' ] } , { `` avoid '' : [ `` target3 '' ] } , { `` avoid '' : [ `` target4 '' , `` target5 '' ] } , { `` avoid '' : [ `` target4 '' , `` target5 '' ] } , ] ; var sort_locations = [ { `` id '' : `` targ...
How to randomly map the elements of one array to those of another array when certain objects must avoid being paired together ?
JS
I want to understand that if I create two style sheetsStyle 1Style 2Now if these two styles are written in two different views , when rendering themon a layout as a Partial View , then in this case a conflict could occurand one could override the style of the other.BUTUsing angular ( see page 16 ) , how come these two ...
.heading { color : green ; } .heading { color : blue ; } import { Component } from ' @ angular/core ' ; @ Component ( { selector : 'app-user-item ' , template : ' < p class= '' heading '' > abc < /p > ' , styleUrls : [ './user-item.css ' ] } ) export class UserItemComponent implements OnInit { constructor ( ) { } ngOnI...
How does Angular Component CSS encapsulation work ?
JS
I have 6 `` blocks '' and each contains different texts , for the sake of simplicity let 's just consider these as my `` blocks '' I have 3 of them visible and 3 hidden . I have a button which replace the corresponding blocksIt works fine but have no idea how to revert it . I tried to clone the elements to a variable a...
< div id= '' block1 '' > < h2 > Block1 < /h2 > < /div $ ( `` .showmore '' ) .click ( function ( ) { $ ( `` # block1 '' ) .fadeOut ( `` slow '' , function ( ) { $ ( this ) .replaceWith ( $ ( `` # block4 '' ) .html ( ) ) ; $ ( this ) .fadeIn ( `` slow '' ) ; } ) ; $ ( `` # block2 '' ) .delay ( 400 ) .fadeOut ( `` slow ''...
How to reverse animation on every second click ?
JS
I want to create a rainbow view stack like so : I know about border radius property , but I need also hover , width-changing and staking of those elements.I see the solving of this problem with using clip-path property : And it looks like this : But those elements are straight , how can I bend them ? Edited : Here is t...
.item { height : 760px ; width : 65px ; background-color : aqua ; transition : 0.3s ease-in-out ; clip-path : polygon ( 100 % 0 % , 75 % 50 % , 100 % 100 % , 25 % 100 % , 0 % 50 % , 25 % 0 % ) ; }
How to create hoverable rainbow with CSS ?
JS
This may be completely stupid but given I type this into my browser console : What is the arr ; syntax doing behind the scenes ? I 'm assuming console.log ( arr ) ; is iterating all the properties of the arr object but what is arr ; doing ? Also does [ ] tell me I 'm dealing with an object of type array and { } tells m...
var arr = [ ] ; arr.item = 'val ' ; console.log ( arr ) ; arr ;
Javascript arrays ?
JS
I built an image slider with jQuery and thought it would be a good exercise to do the same in vanilla javascript ( Which is an awesome framework btw ; ) ) . It 's good to know that though I can build things with jQuery , I have very little understanding of what 's actually going on under the hood.Anyways , here is my p...
console.log ( 'Yeh , bitch ! Programming ! ' ) ; function slider ( ) { var settings = { width : `` 700px '' } ; // end settings objectvar sliderImages = document.getElementById ( 'slider-images ' ) .querySelectorAll ( 'img ' ) , prevImg = document.getElementById ( 'prev-img ' ) , currentImg = document.getElementById ( ...
Setting Width to Appended Child Image - VANILLA javascript
JS
I am trying to understand or refresh my logic on this better - for example in angular it has the angular.forEach ( ) . I thought it was because the code in a controller ( or module in general ) - did n't have access to the browser api ( functions and objects , etc ) - and for that matter the forEach function of the bro...
angular.module ( 'myApp ' , [ ] ) .controller ( 'JCtrl ' , [ ' $ scope ' , function ( $ scope ) { $ scope.test = 'scope and binding works ' ; [ 0 , 1 , 4 ] .forEach ( function ( value ) { console.log ( value ) ; } ) ; console.log ( [ ] .forEach ) ; } ] ) ;
Why do projects like angular have their own version of common functions ?
JS
I have a lot of elements with the same class . These elements are divided into groups by means of attribute `` data-xxx '' How to perform a function on each item , but only once in each group using something like this ?
< div class= '' myclass '' data-n= '' group1 '' > < /div > < div class= '' myclass '' data-n= '' group1 '' > < /div > < div class= '' myclass '' data-n= '' group1 '' > < /div > ... . < div class= '' myclass '' data-n= '' group2 '' > < /div > < div class= '' myclass '' data-n= '' group2 '' > < /div > ... < div class= ''...
Run each for a class but once for group
JS
Hello who just have come.I 'm learning JavaScript RegExp rules . And i have wrote email validation pattern . But unfortunatley it allowing double `` @ '' in examples.Please help me to improve it.Also screenshot available :
^ ( ? : \s| ( ? : [ a-z ] ) ) ( ? : [ a-zA-Z0-9 ] +. ) + @ ( ? : [ a-zA-Z ] ) + . [ a-z ] +\s+
My RegExp pattern alllowing double `` @ '' in email
JS
Thats just stupid looking , but its the best way i can think of writing it . I tried parentsUntil ( 'li ' ) but that didnt work at all and i also tried parents ( 'li ' ) and closest ( 'li ' ) . Isnt there something in jQuery with the equivalent of : If not i think ill try submitting it to the jQuery core ... Here is my...
$ ( this ) .parent ( ) .parent ( ) .parent ( ) .parent ( ) .find ( ' [ name=reply_to_id ] ' ) ; $ ( this ) .firstParentThatMatchesThis ( 'li ' ) .find ( ' [ name=reply_to_id ] ' ) ;
This is ugly and there has to be a better way to write it in jQuery
JS
I 'm trying to write a function that can perform permutation.For example , if I input [ 1 , 2 , 3 ] , the expected answer will beBut instead of showing the answer , it returns [ [ ] , [ ] , [ ] , [ ] , [ ] ] Any ideas ?
[ [ 3 , 2 , 1 ] , [ 3 , 2 , 1 ] , [ 3 , 2 , 1 ] , [ 3 , 2 , 1 ] , [ 3 , 2 , 1 ] , [ 3 , 2 , 1 ] ] var permute = ( nums ) = > { results = [ ] ; var backtrack = ( nums , result ) = > { if ( nums.length === result.length ) { results.push ( result ) ; } else { for ( var i = 0 ; i < nums.length ; i++ ) { if ( result.indexOf...
Unexpected output of Javascript function
JS
I understand that `` this '' keyword refers to the currrent/immediate object . While watching a React.js tutorial , I saw the instructor using the keyword with multiple objects . The code looks like this : Inside formatCount ( ) , why we are referring to this.state instead of state.count ? Also , why not formatCount ( ...
class Counter extends Component { state = { count : 0 } ; styles = { fontSize : 10 } ; render ( ) { return ( < div > < h1 style= { this.styles } > Hello < /h1 > < span > { this.formatCount ( ) } < /span > < /div > ) ; } formatCount ( ) { const { count } = this.state ; return count === 0 ? `` Zero '' : count ; } }
`` this '' keyword with multiple objects
JS
Suppose I have a class ( very simple scenario ) It 's compiled by TypeScript compiler to : Now if I create an object and call a method , everything works fine.But if I invoke that method from callback , it breaks ( this is referencing a Window as expected ) I 'm aware of the difference between this in JavaScript and C ...
class Student { name = `` John '' ; sayHello ( ) { console.log ( `` Hi , I 'm `` + this.name ) ; } } var Student = ( function ( ) { function Student ( ) { this.name = `` John '' ; } Student.prototype.sayHello = function ( ) { console.log ( `` Hi , I 'm `` + this.name ) ; //here is the problem . Accessing name via this ...
Why compiler does n't translate `` this '' link into context-agnostic variable ?
JS
All these input tags are inside < form > < /form > tags The script below does n't work . Can sombody help me ?
< input type= '' text '' placeholder= '' username '' > < br / > < input type= '' text '' placeholder= '' Name '' > < br / > < input type= '' text '' placeholder= '' Lastname '' > < br / > < input id= '' mail '' type= '' text '' placeholder= '' E-mail '' > < br / > < input id= '' mail_1 '' type= '' text '' placeholder= ...
jquery validation - with form tag
JS
I 'm a bit confused on what 's required to dynamically load a JS file into the DOM.When I include in my HTML file , example.js will run normally.When I include it will add to the DOM but not run it.I previously believed that I had to recreate , then append ( ) it to the tag . I feel as if I am missing a crucial step , ...
< ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < script src= '' example.js '' > < /script > < ! -- working -- > < script src= '' add-example-dynamically.js '' > < /script > < ! -- not working -- > < /head > < body > < script > execute ( anyScriptElement ) ; // not working < /script > < /body > < /ht...
How to Dynamically Load Javascript File into HTML
JS
First , some psuedo-psuedo-code : In this example we 're getting a collection of DOM elements based on some selector logic , then iterating over each one . For each element we 're calling someLogic ( ) . If that returns true we abort the each loop . Otherwise , we perform some logic on the element and then move on to t...
$ ( `` some-selector-logic '' ) .each ( function ( ) { if ( someLogic ( $ ( this ) ) ) { return false ; } // Otherwise do stuff related to $ ( this ) } ) ; someMoreExcitingCode ( ) ; var aborted = false ; $ ( `` .. '' ) .each ( function ( ) { if ( someLogic ( $ ( this ) ) ) { aborted = true ; return false ; } } ) ;
How can I tell if a $ ( `` .. '' ) .each ( ) call was aborted prematurely ?
JS
I have created an interactive map that when areas are selected then the related content should show/hide , which is working correctly.link to previewThe issue I 'm having is actually connecting trail lines from the areas/dots to the related content boxes.How would I go about this with the JavaScript that I already have...
< style > /* Fonts */ @ font-face { font-family : 'Newbaskn ' ; src : url ( 'fonts/Newbaskn.eot ' ) ; src : url ( 'fonts/Newbaskn.eot ' ) format ( 'embedded-opentype ' ) , url ( 'fonts/Newbaskn.woff2 ' ) format ( 'woff2 ' ) , url ( 'fonts/Newbaskn.woff ' ) format ( 'woff ' ) , url ( 'fonts/Newbaskn.ttf ' ) format ( 'tr...
JavaScript show/hide borders / lines
JS
I am using 2 JSON feeds to check the date and display the data from them depending on the current date and the date in one of the objects , but for some reason variable c which is object is undefined . When I replace the data in 'elements ' function with hardcoded urls , everything works fine , but I am not sure why da...
jQuery ( function ( $ ) { var url1 = 'feed1.json ' ; var url2 = 'feed2.json ' ; var id = shop_id.replace ( /\ [ |\ ] |\ '' /g , `` ) ; var c = { } ; var logo ; $ .when ( request1 ( ) , request2 ( ) ) .done ( function ( r1 , r2 ) { var results1 = $ .grep ( r1 [ 0 ] , function ( e ) { return e.id == id } ) ; var results2...
Javascript variable from JSON feed object not recognized
JS
I 'm learning Backbone and had some issues with the on ( ) -function . But actually it 's a very basic JavaScript question.Why is it that the first line of code below works , and the second does n't ? Using the second line , the render-function is never triggered . Mind the brackets.WorksFails
this.collection.on ( 'reset ' , this.render , this ) ; this.collection.on ( 'reset ' , this.render ( ) , this ) ;
jQuery on ( ) ; function
JS
I 'm quite a beginner at coding and StockOverflow . This is my first post ever so please pardon if my post is not formatted correctly as I am only a junior in high school . On that note however , I had a question regarding my code below . Just a little background , this code is supposed to generate a list of fortunes a...
var fortunesList = [ `` die 2mrrw '' , `` find a dollar '' , `` become poor '' , `` jump off a cliff '' , `` turn into Batman '' ] ; //if any fortunes are added to the list above , make sure to change `` for loop '' paramter one value ( var i = `` `` ; ) and stats function at bottom function generateFortuneCookie ( ) {...
When running a function again it does not read global array
JS
Is there any way that I can use the word only that I click on e.g if I click on car only 'car ' is used . if I click on this only 'this ' is used . i.e . the only word that I click on.p.s I need to use only a single word that is clicked . My p element contains at-most 10 words.Thanks in advance
< p > this is a car < /p > //HTML p element < p id= '' demo '' onclick= '' myFunction ( ) '' > This is a car < /p > myFunction ( ) { var my ; my=document.getElementbyID ( `` demo '' ) [ 1 ] ; //to get 'is ' }
using particular word of < p > element in html
JS
I am using a function in a JavaScript framework where the return value can be ANY of the followinga single xy coordinate pairan array of xy coordinate pairsan array of arrays of xy coordinate pairsThe return value depends on the geometry of the object ( single point , line , or multiple lines ) . Regardless of the retu...
[ x , y ] [ [ x , y ] , [ x , y ] , ... ] [ [ [ x , y ] , [ x , y ] ] , [ [ x , y ] , [ x , y ] ] , ... ] //here is the magic method that can return one of three things : ) var mysteryCoordinates = geometry.getCoordinates ( ) ; var firstCoord ; if ( typeof mysteryCoordinates [ 0 ] === 'number ' ) { firstCoord = mystery...
Get first array of numbers in array of variable depth
JS
Currently I have a display where I have a button START , on click of this button the timer starts and it gets replaced by 2 buttons . these 2 buttons are submit and walkaway . on the submit of each of these buttons a script is run . on the click of submit button , test.php is initiated.Everything is working fine , but ...
/*******Code for the three buttons*********/ $ ( document ) .ready ( function ( ) { $ ( `` # startClock '' ) .click ( function ( ) { $ ( `` # startClock '' ) .fadeOut ( function ( ) { $ ( `` # walkaway '' ) .fadeIn ( ) .delay ( 120000 ) .fadeOut ( ) ; $ ( `` # submitamt '' ) .fadeIn ( ) .delay ( 120000 ) .fadeOut ( fun...
Change the functionality of a button
JS
EDIT : after some comments , i realize that i need to prefix my JSON keys better . I 'm adding a bounty because learning this is important to me . I am making a form and i save it to JSON . Then I made a function to display the form data on a table below it . The problem is that when the page loads , it loads data from...
getData : function ( ) { var ORMcount = localStorage.length , i = 0 ; if ( ORMcount > 0 ) { var renderData = `` < table > '' ; renderData += `` < tr > < td > ORM Matrix < /td > < /tr > < br / > < tr > < th > Plan < /th > < th > Reward < /th > < th > Risks < /th > < th > < /th > < /tr > '' ; for ( i = 0 ; i < ORMcount ;...
JSON load function reads keys from other programs
JS
If I list out checkboxes manuallyChecking one checkbox checks all of the checkbox.But if I use ng-repeatChecking one checkbox only checks one of themIs there a reason for this ? From the DOM they both looks the same .
< ul > < li > < input type= '' checkbox '' ng-model= '' checkState '' / > < /li > < li > < input type= '' checkbox '' ng-model= '' checkState '' / > < /li > < /ul > < div > < ul > < li ng-repeat= '' elem in someArray '' > < input type= '' checkbox '' ng-model= '' checkState '' / > < /li > < /ul > < /div >
Why angular ` ng-repeat ` have different checkbox differentiate behavior then listing out checkbox manually ?
JS
I am using OpenLayers 6 and I import parts of the library using this notation : When running npm run dev I get a 9MB file for my project.For testing purpose , I tried to replace these named imports by default imports : Surprisingly , it reduced my bundled file to 6MB ! It 's 33 % lighter , why is that ? Should n't name...
import { Map , View } from 'ol ' ; import { Vector as VectorSource } from 'ol/source ' ; import { Vector as VectorLayer } from 'ol/layer ' ; // More in other files [ ... ] import Map from 'ol/Map ' ; import View from 'ol/View ' ; import VectorSource from 'ol/source/Vector ' ; import VectorLayer from 'ol/layer/Vector ' ...
Why is my ES6 webpack bundle larger when using default imports instead of named imports ?
JS
I have run the following lines in my console ( once a jquery script has been loaded ) , and received the following results : And I do n't know what steps to take to figure out what is going on . My guess is that there is some object that holds a time based value which is changing , but I wonder if it 's something diffe...
$ ( this ) > [ Window ] $ ( this ) ! = $ ( this ) > true $ ( this ) == $ ( this ) > false $ ( this ) === $ ( this ) > false
In JQuery , why does $ ( this ) == $ ( this ) return false ?
JS
I 'm writing in two files - one is html and one is JavaScript . So to call an object I doand in the JavaScript file I dobut now I 'm trying to optimize my code and to call a function with objects in it . I created sections ( 4 of them ) and I 'm trying to change the color with onmouseover and onmouseout . Here is the c...
document.getElementById ( `` nameObj '' ) .onmouseover = changeMe ; changeMe = function ( ) { //and here i write the function } < ! DOCTYPE html > < html > < head > < link rel= '' stylesheet '' href= '' style.css '' > < script src= '' script.js '' > < /script > < title > test 2 < /title > < /head > < body > < header > ...
the difference between calling object and function in javascript
JS
I 'm trying to learn object-oriented javascript . Working with a simple method I want to do this : However , I 've learned that it 's often a good idea to pass variables into functions when working with normal functions , in objects however , this seems a bit clunky.Both methods work . What are the pros and cons of the...
var users = function ( url ) { this.url = url ; this.log = function ( ) { console.log ( this.url ) ; } } var apiPoint = `` https : //www.zenconomy.se/api/admin/tracking ? format=json '' var liveUsers = new users ( apiPoint ) liveUsers.log ( ) var users = function ( url ) { this.url = url ; this.log = function ( url ) {...
Should I pass an object property into an object method ?
JS
I am facing difficulty understanding the below code.Its output comes as 2 , 4 , 2 which I am not able to understand .
function foo ( ) { console.log ( this.a ) ; } var obj = { a : 2 , foo : foo } ; var a = 4 ; obj.foo ( ) ; setTimeout ( obj.foo , 100 ) ; setTimeout ( obj.foo.bind ( obj ) , 100 ) ;
`` this '' context output not able to understand
JS
Ok so i 've made this function which works fine for converting most urls like pies.com or www.cakes.com to an actual link tag.I would like to update this function to add no-follow tags to links to my competitors , so i would have certain keywords ( competitor names ) to nofollow for example if my site was about baking ...
function render_hyperlinks ( $ str ) { $ regex = '/ ( http : \/\/ ) ? ( www\. ) ? ( [ a-zA-Z0-9\-_\. ] +\ . ( com|co\.uk|org ( \.uk ) ? |tv|biz|me ) ( \/ [ a-zA-Z0-9\-\._\ ? & = # \+ ; ] + ) * ) /ie ' ; $ str = preg_replace ( $ regex , '' ' < a href=\ '' http : //www.'. ' $ 3 ' . '\ '' target=\ '' _blank\ '' > '.strtol...
help with regex - how can i make some urls no-follow ?
JS
I have the problem in this JS Fiddle.Main problem is with the float : left property.I have the code which allows to drag and drop the elements which have the float : left property . They are creating the problem when I want to placing the controls parallel in the next div area.The problem is more clear , if you look in...
< input type= '' button '' class= '' Mybutton '' value= '' Add div '' / > < br / > < div class= '' selectorField draggableField ui-draggable ui-resizable '' style= '' width:250px ; '' > < div id= '' new '' style= '' margin-bottom:10px ; `` > < div style= '' width:80px ; float : left ; '' > < span id= '' LabelU1 '' > Fi...
Unable to clear float : left
JS
So i am trying to transfer my code into the `` Promise world '' , and in many places when i had to `` loop '' with async functionality - i simply used recursion in such a wayNow i am trying to make the change into the Promise world , and i am quite stuckThanks .
function doRecursion ( idx , callback ) { if ( idx < someArray.length ) { doAsync ( function ( ) { doRecursion ( ++idx , callback ) } ) ; } else { callback ( 'done ! ' ) } } doRecursion ( 0 , function ( msg ) { // ... } ) ; var Promise = require ( 'bluebird ' ) function doRecursion ( idx ) { return new Promise ( functi...
Async recursive using promise
JS
I need help with modifying the code below.I have two tables , table one has two rows and six columnstable two has two rows and six columns with each cell colored either red or yellow creating two congruent shapes.I want to display an alert when the cells in `` table one '' match the congruent shapes and their colors of...
jQuery ( function ( ) { var brush = `` white_block '' ; jQuery ( 'input.block ' ) .on ( 'click ' , function ( ) { brush = jQuery ( this ) .data ( 'brush ' ) ; } ) ; function cellCheck ( ) { var reds = jQuery ( ' # two .red_block ' ) .length , yellows = jQuery ( ' # two .yellow_block ' ) .length , cells_colored = reds +...
Display alert when two tables color congruent patterns match
JS
I have a custom directive that looks like this : In my directive definition object I reference my controller and scope like so : In my controller I set var vm = this so I can refer to scope variables as vm.variable . However this does not work for id and version . I 've found that I need to inject $ scope and reference...
< my-queue id= '' report.id '' version= '' report.version '' > < /my-queue > controller : 'QueueController ' , controllerAs : 'myQueue ' , scope : { id : '= ' , version : '= ' }
Reference directive attribute with vm rather than $ scope
JS
I 'm trying to add an event listener to all elements with a class of section , however it only applies it to the last object in the node list.Is there a way I can add the event listener for each one ?
var section = document.querySelectorAll ( '.section ' ) ; for ( var i=0 ; i < section.length ; i++ ) { var elem = section [ i ] ; elem.addEventListener ( 'click ' , function ( ) { move ( elem ) } , false ) ; }
addEventHandler to every element in a class
JS
Say you have this function : And doSomething should be used like this : My question is : Is there an official way in JSDoc to document fn parameters ? May be something like :
/** * doSomething description * @ param { function } fn - A function that accepts an argument . */function doSomething ( fn ) { fn.call ( this , 'This is a test ' ) ; } doSomething ( function ( text ) { console.log ( text ) ; } ) ; /** * doSomething description * @ param { function } fn - A function that accepts an arg...
Is there a way to document parameters of a function parameter ?
JS
I am looking at a Javascript emulator of a NES to try and understand how it works.On this line : The opcode is incremented by two . However , the documentation ( see appendix E ) I 'm reading says : Zero page addressing uses a single operand which serves as a pointer to an address in zero page ( $ 0000- $ 00FF ) where ...
addr = this.load ( opaddr+2 ) ; -- -- -- -- -- -- -- -- -- -- -- -- -| 0 | 1 | 2 | 3 | 4 | 5 | < - index -- -- -- -- -- -- -- -- -- -- -- -- -| a | b | c | d | e | f | < - memory -- -- -- -- -- -- -- -- -- -- -- -- - ^ \ PC var pc= 0 ; //for example 's sakevar opcode= memory [ pc ] ; //a var first_operand = memory [ pc...
Why is the operation address incremented by two ?
JS
It is not a real jQuery plugin , but for my problem i did n't know what title was appropriate.This is the `` Plugin '' -- > http : //jsfiddle.net/djrikyx/GuumY/9/There are 3 Youtube player , with the possibility of Pop out them into draggable DIVs and also minimize them to the right.I ca n't explain my problem only wit...
var countMP = $ ( '.uiVideoHandleMin ' ) .length ; uVC.removeClass ( 'uiVideoContainerMin ' ) ; if ( countMP > 0 ) { $ ( '.uiVideoHandleMin ' ) .each ( function ( ) { var top = parseInt ( $ ( this ) .css ( 'top ' ) , 10 ) ; top = top-30 ; $ ( this ) .css ( { top : top } ) ; } ) ; }
Javascript/ jQuery plugin
JS
For example i have such list ( which i use with ng-repeat ) : and i have filter arrays : how is it possible in filter function to combain all this filters ? And to return only such items from the list , which are equal to filter arrays ? BUT ! ! ! I can have : filter only by name , or only by type , or 2 fields , or al...
var myList = [ { id : 1 , name : 'Peter Ollison ' , type : 'Driver ' , status : 'Working ' } , { id : 2 , name : 'Maya Nameson ' , type : 'Manager ' , status : 'Not ' } , { id : 3 , name : 'Iki Jonny ' , type : 'Driver ' , status : 'Paused ' } , { id : 4 , name : 'Nikolay Ivanov ' , type : 'Manager ' , status : 'Workin...
Javascript ( angularJS ) : filter by multiple field
JS
I 'm new to Javascript and am wondering if intentionally returning a value of undefined from a function is a common practice.For example , should a divide ( ) function be implemented like this : or like this ? I assume that returning undefined is typically reserved for functions with no return values ( equivalent of vo...
var divide1 = function ( x , y ) { if ( y === 0 ) { return undefined ; } return x/y ; } ; var divide2 = function ( x , y ) { if ( y === 0 ) { throw new Error ( `` Ca n't divide by 0 '' ) ; } return x/y ; } ;
Is it typical for a Javascript function to return a value of undefined intentionally ?
JS
I want to know if it is possible to use universal selector with $ ( this ) .When , for example , I want delete all inline CSS from the element and its children I use this code : But if i have $ ( this ) what is the code ? Maybe I have to try :
$ ( ' # element , # element * ' ) .attr ( 'style ' , '' ) ; $ ( this , this+'* ' ) .attr ( 'style ' , '' ) ;
Is possible to use $ ( this ) and universal selector ( * ) ?
JS
I would like to know what is the recommaned way of nesting Backbone Views.Possible ways to nest views : Render all views and put them together in the RouterLet an IndexView do all the nesting which is called in the routerInclude views in underscore templatesI tried my luck already in this fiddle : http : //jsfiddle.net...
var IndexView = Backbone.View.extend ( { tagName : `` div '' , className : `` container '' , template : LayoutTemplate , render : function ( ) { this. $ el.html ( LayoutTemplate ) ; this. $ ( 'div.content ' ) .html ( ContentTemplate ) ; this. $ ( 'div.sidebar ' ) .append ( new LoginView ( ) .render ( ) .el ) ; this. $ ...
What is the recommended way to nest views ?
JS
I have a series of articlesarranged in a grid of three per rowand I want that they expand horizontally to fully occupy its row when clicked . so I create an expanded class and apply it on clickI am almost there , as you can see in the fiddle here http : //jsfiddle.net/aqw339r0/1/When I click on any of the articles they...
< section > < article > 1 < /article > < article > 2 < /article > < article > 3 < /article > ... . < article > 999 < /article > < section > section { position : relative } article { display : inline-block ; width : 33 % ; } .expanded { position : absolute ; left:0px ; width : 100 % ; } $ ( `` article '' ) .click ( func...
expanding an inline-block jumps to above row
JS
I found this awesome way to detect emojis using a regex that does n't use `` huge magic ranges '' by using a Unicode property escape : But when I shared this knowledge in this answer , @ Bronzdragon noticed that \p { Emoji } also matches numbers ! Why is that ? Numbers are not emojis ?
console.log ( /\p { Emoji } /u.test ( 'flowers ' ) ) // trueconsole.log ( /\p { Emoji } /u.test ( 'flowers ' ) ) // false console.log ( /\p { Emoji } /u.test ( 'flowers 123 ' ) ) // unexpectdly true// regex-only workaround by @ Bonzdragonconst regex = / ( ? =\p { Emoji } ) ( ? ! \p { Number } ) /u ; console.log ( regex...
Why do Unicode emoji property escapes match numbers ?
JS
I 'm just a bit confused about how the this keyword is used in this context . It is placed in an anonymous function with the parameter callback and is then used as such : callback ( this [ i ] , i , this ) . The exercise does n't go into depth , but I understand that the this is referring to the ar object that is in th...
Array.prototype.map = function ( callback ) { let arr = [ ] ; for ( let i = 0 ; i < this.length ; i++ ) { arr.push ( callback ( this [ i ] , i , this ) ) } return arr ; } let ar = new Array ( )
What does 'this ' keyword Refer to in this Method
JS
I can write the following : Which means files can be downloaded in parallel but executed only one after another . However , I can add async attribute to allow browser execute code in a random order.If I 'm interested in the performance boost , can the second block be executed faster ? As I see it if a browser executes ...
< script src= '' file1.js '' defer > < /script > < script src= '' file2.js '' defer > < /script > < script src= '' file3.js '' defer > < /script > < script src= '' file1.js '' async > < /script > < script src= '' file2.js '' async > < /script > < script src= '' file3.js '' async > < /script >
Do browsers execute loaded scripts in a single thread ?
JS
Here is the code that I am using , do n't understand why is there a difference in the output of ng-bind and { { } } .This is the output that I am getting
angular.module ( 'Test ' , [ ] ) ; < script src= '' https : //ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js '' > < /script > < div ng-app= '' Test '' > < input type= '' text '' ng-model= '' foo.bar '' / > < input type= '' text '' ng-model= '' foo.baz '' / > < p ng-bind= '' foo '' > < /p > < p > { { foo ...
Why is ng-bind and { { } } giving different outputs for a json ?
JS
I have an object which has a property called tier which has 9 possible values - IRON , BRONZE , SILVER , GOLD , PLATINUM , DIAMOND , MASTER , GRANDMASTER and CHALLENGER.Based on that property , I want to display the emblem corresponding to the tier , however , whilst the tier might be called IRON , the image file with ...
< img class='ranked-emblem ' : src= '' '../emblems/ ' + rankedEmblem ( league.tier ) + '.png ' '' alt= '' '' > rankedEmblem ( tier ) { if ( tier === 'IRON ' ) { return 'Emblem_Iron ' } else if ( tier === 'BRONZE ' ) { return 'Emblem_Bronze ' } else if ( tier === 'SILVER ' ) { return 'Emblem_Silver ' } else if ( tier ==...
Is there a more elegant way of writing a function that returns the name of an image based on the argument of the function ?
JS
Often , for programming languages implementations , it is desirable to tag numbers using bitwise operators . In C , you could tag a double by using an union : What is a way to mimic this behavior on JavaScript ? Using bitwise operators is ruled out , since it converts the doubles to Uint32s . I need a mathematical solu...
typedef union Tag_ { double d ; long long i ; } Tag ; double tag ( double x ) { Tag tmp ; tmp.d = x ; tmp.i |= 1 ; return tmp.d ; } ; double isTagged ( double x ) { Tag tmp ; tmp.d = x ; return tmp & 1 ; } ;
Performant way to tag a number on JavaScript , using its less significant bit ?
JS
I want to be able to scroll both sides endlessly meaning it will clone elements before reaching the end.example : https : //codepen.io/rKaiser/pen/wOGmqNExample starts with scrollbar being center . So it should clone original elements before reaching either side . I 'm not sure about the performance , would it be bette...
$ ( '.timeline-container ' ) .on ( 'scroll ' , function ( ) { //columns = innerContent.length * 101 ; // multiply by column width console.log ( this.scrollLeft ) //console.log ( columns + ' whole width ' ) ; if ( this.scrollLeft < 1000 ) { cloneTimelinesleft ( ) ; console.log ( 'test ' ) ; $ ( this ) .off ( 'scroll ' )...
Never ending scroll , clone items both sides
JS
I 'm loading Brython and iFlyChat but Brython wo n't work if the iFlyChat script is uncommented . I 've tried all sorts of async combinations but there seems to be something more fundamental.JSFiddle here and code below : https : //jsfiddle.net/tutmoses/c09dhbrq/
< html lang= '' en '' > < head > < meta charset= '' UTF-8 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1.0 '' > < title > Title < /title > < ! -- BRYTHON -- > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.js '' integrity= '' sha256-rA89wPrTJJQFWJaZveK...
Two scripts conflicting in the HTML head ( Brython & iFlyChat )
JS
Let 's say if I have a classIs there any implementation to automatically intercept/catch any error that happens in this class and redirect it to an error handling method , in this case handleError ( ) e.gThat should trigger errorHandler ( ) . Angular has such implementation and I am not sure how it got done .
class Foo { doSomething ( ) { throw 'error ' ; } doOtherthing ( ) { throw 'error2 ' ; } handleError ( e ) { } } const foo = new Foo ( ) foo.doSomething ( )
How to intercept all errors in a class instance ?
JS
I have a plus sign that appears if you push the space button . But now it appears once . Can you help me to make it appear every time I press the space button ? Here is my Code Pen .
import './style.scss ' ; let counter = 0 ; document.addEventListener ( 'keydown ' , ( { keyCode } ) = > { const increment = document.getElementsByClassName ( 'increment ' ) [ 0 ] ; if ( keyCode === 32 ) { counter++ ; document.getElementsByClassName ( 'counter ' ) [ 0 ] .innerText = counter ; increment.classList.remove ...
How to reset CSS transition once it played
JS
Is there anybody would explain why the result is different below ? result is 17958result is 15714When the position of the function 'computeMaxCallStackSize ' is different , the result is different too . What 's the reason ? Thanks very much ! Running environment : node.js v6.9.1OS : Win7
// test onefunction computeMaxCallStackSize ( ) { try { return computeMaxCallStackSize ( ) + 1 ; } catch ( e ) { return 1 ; } } console.log ( computeMaxCallStackSize ( ) ) ; // test two function computeMaxCallStackSize ( ) { try { return 1 + computeMaxCallStackSize ( ) ; } catch ( e ) { return 1 ; } } console.log ( com...
javascript recursive stack overflow
JS
I am new to Javascript and now studying it ... Let 's suppose we have two functions shown above . It seems that objects can be created by using either of the functions . For example ) My question is : What 's difference between person vs person2 ? Are they exactly the same ? If not which one is a more preferable way to...
var person = function ( ) { this.name = `` name '' } ; var person2 = function ( ) { var obj = { } ; obj.name = `` name '' ; return obj ; } ; var p = new person ( ) ; var p2 = new person2 ( ) ;
Two different ways to make javascript objects
JS
I 'm using some accounts-* packages in my application . At very first times it was working without any problem . Then I commited it to github and pulled from somewhere else . Afterwards , I could n't login with any accounts-* package , including facebook , password , github , google etc.Note that , I 've reseted my mon...
Meteor.loginWithFacebook ( ) undefinedMeteor.logout ( ) undefinedMeteor.loggingIn ( ) true // it 's always true
Accounts-UI hangs on loading during login
JS
I came across this Javascript snippet : This example evaluates to 36.What is happening here and what 's the best way to understand/read it ?
var sum = + ( ( ! + [ ] + ! ! [ ] + ! ! [ ] + [ ] ) + ( ! + [ ] + ! ! [ ] + ! ! [ ] + ! ! [ ] + ! ! [ ] + ! ! [ ] ) ) ;
Understanding some Javascript code
JS
I found some code about authentication with angular and i ca n't understand this trick : What does ! ! mean 'different of userId ' ? whenever true = ! ! true = ! ! ! ! true = > etc , it do n't understand this.Somebody can help me ? ( https : //medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-...
authService.isAuthenticated = function ( ) { return ! ! Session.userId ; } ;
Meaning of ! ! javascript
JS
I have a problem understanding the order of events when building 2 observables that depend on the same underlying source . I hope you can not only help me with a working solution , but also explain why I get the outcome below . My goal is that observable2 never emits before observable1.CodeExpected outcomeActual outcom...
const filters $ = new Subject ( ) ; const observable1 = filters $ .pipe ( map ( ( ) = > 'obersvable1 ' ) ) ; const observable2 = observable1.pipe ( map ( ( ) = > 'observable2 ' ) ) observable2.subscribe ( ( v ) = > console.log ( v ) ) ; observable1.subscribe ( ( v ) = > console.log ( v ) ) ; observable1observable2 obse...
How do I make an observable depend on another observable
JS
This works.This causes syntax error . Why ? This works .
var a = 'ontouchstart ' in window ; for ( ; ; ) { console.log ( a ) ; break ; } for ( var a = 'ontouchstart ' in window ; ; ) { console.log ( a ) ; break ; } for ( var a = ( 'ontouchstart ' in window ) ; ; ) { console.log ( a ) ; break ; }
Why does 'in window ' in for loop initialization cause syntax error ?
JS
A ReactJS component needs to listen for events emitted by a WebSocket.For each inbound event the component should render a DOM node.It should then wait for the CSS animation associated with the DOM node to complete , and then remove the DOM node.This is a sketch of my intended implementation . Does this approach look w...
class MyComponent extends React.PureComponent { componentDidMount ( ) { this.props.webSocket.on ( 'myEvent ' , componentDidReceiveEvent ) } componentWillUnmount ( ) { this.props.webSocket.off ( 'myEvent ' , componentDidReceiveEvent ) } // is this method style valid syntax ? componentDidReceiveEvent = limit ( ( evt ) = ...
How to design a ReactJS component that listens to a WebSocket and interacts with CSS animation
JS
I understand how private static mechanism works in javascript ; but that screws in inheritance.For example : Is there any way to avoid this pitfall ?
var Car = ( function ( ) { var priv_static_count = 0 ; return function ( ) { priv_static_count = priv_static_count + 1 ; } } ) ( ) ; var SedanCar = function ( ) { } ; SedanCar.prototype = new Car ( ) ; SedanCar.prototype.constructor = SedanCar ;
Private static in JavaScript and Inheritance
JS
For reference , this is the JSON I 'm working with : http : //goo.gl/xxHci0In regular JavaScript , using the code below works fine and I can manipulate it easily : But I 'm working on a jQuery version of the same code to avoid using methods like iFrames to get this data . My jQuery function is : I found ways to convert...
var info = JSON.parse ( document.getElementsByTagName ( `` pre '' ) [ 0 ] .innerHTML ) ; alert ( info [ 0 ] [ `` AssetId '' ] ) ; $ .get ( page , function parse ( data ) { var r = $ .parseJSON ( data ) ; alert ( r [ 0 ] [ `` AssetId '' ] ) ; } ) ;
Converting JSON using jQuery
JS
I have read about the nested component in React.I tried with this example and noticed that each time I updated the state of the parent component ( todolist ) . The DOM tree re-render the whole instead of add new.My question is : Is it an anti-pattern that we should avoid ? Here is my testing
const TodoList = ( { todos , onTodoClick } ) = > { const Todo = ( { completed , text , onClick } ) = > { return ( < li onClick= { onClick } style= { { textDecoration : completed ? 'line-through ' : 'none ' } } > { text } < /li > ) ; } ; return todos.map ( todo = > < Todo key= { todo.id } { ... todo } onClick= { ( ) = >...
React anti pattern , defined a component inside the definition of another component
JS
I am developing an app in aureliajs . The development process is started for many months and now , the back-end developers want to make their services versioned . So I have a web service to call to get the version of each server side ( web api ) app and then , for the further requests , call the right api address inclu...
export class App { async constructor ( ... ) { ... await this.initializeHttp ( ) ; ... } initializeHttp ( ) { // get the system meta from server } }
Aureliajs Waiting For Data on App Constructor
JS
This video is a good representation of the issue I am facing : https : //drive.google.com/file/d/1jN44lUpnbVDv_m3LuPhlJl6RFUu884jz/view . I can not copy and paste a table from another a tab without it breaking down . Because this uses local storage , here is a JSFiddle : https : //jsfiddle.net/znj537w0/1/ .
var app = angular.module ( `` TodoApp '' , [ `` LocalStorageModule '' , 'ngSanitize ' ] ) ; app.controller ( `` TodoController '' , function ( $ scope , localStorageService ) { if ( ! localStorageService.get ( `` taskListActive '' ) ) { $ scope.tasksActive = [ { text : `` Do me next '' , priority : 1 , complete : false...
Copy and Paste Table Using ContentEditable
JS
How to find and pair the alphabets after the numbers in a string in order to reduce one expression ? Lets assume we have a string like string = `` 20hc+2a+2hc+9op+330o+10op '' , and we want to find the pair which same alphabet after numbers . First we should do split . ( '+ ' ) and then we get an array [ ... . ] , then...
20+2 = 22hc2 = 2a9+10 = 19op330 = 330o 22hc+2a+19op+330o
How to reduce a string expression like `` 20hc+2a+2hc+9op '' to `` 22hc+2a+9op ''
JS
I 've got this code in twigI just wanted to change content and functionality to button on click and tried this code with jQueryWith this code on page source I see different ID and different text on button but when click second time I call first button like it had never changed . Is there some way to refresh memory for ...
{ % if followsId == null % } < div id= '' followUser '' class= '' follow '' data-userId= '' { { profileUserData.id } } '' data-currentUserId= '' { { loggedUserData.id } } '' data-action= '' follow '' > Follow < /div > { % else % } < div id= '' unFollowUser '' class= '' follow '' data-followsId= '' { { followsId } } '' ...
Change button functionality jQuery
JS
For the semicolon key , ; , this gives 59 in Firefox and 186 in Chrome . However , from the jQuery reference page for the keydown event , it says '' While browsers use differing properties to store this information , jQuery normalizes the .which property so you can reliably use it to retrieve the key code . This code c...
$ ( document ) .keydown ( function ( event ) { alert ( event.which ) ; } ) ;
Trying to figure out if there is a bug in jQuery or if it 's something I 'm doing
JS
I have not worked with Javascript in a long time , so now promises are a new concept to me . I have some operations requiring more than one asynchronous call but which I want to treat as a transaction where steps do not execute if the step before failed . Currently I chain promises by nesting and I want to return a pro...
myfunction ( key ) = > { return new Promise ( ( outerResolve , outerReject ) = > { return new Promise ( ( resolve , reject ) = > { let item = cache.get ( key ) ; if ( item ) { resolve ( item ) ; } else { //we didnt have the row cached , load it from store chrome.storage.sync.get ( key , function ( result ) { chrome.run...
Am I chaining Promises correctly or committing a sin ?
JS
I 'm making an application . As an example , I tried to print the letter ' a ' 16 times in the following code . But it did n't work . This is because I do use 'return ' . I know that . But it does not use error . How do I print the letter ' a ' 16 times ?
import React from `` react '' ; import Game from `` ./game '' ; class App extends React.Component { constructor ( props ) { super ( props ) ; this.Game = new Game ( ) ; console.log ( this.Game.play ( ) ) ; } draw = ( ) = > { for ( let a = 0 ; a < 4 ; a++ ) { for ( let b = 0 ; b < 4 ; b++ ) { return < div > a < /div > ;...
Is it possible to print 16 times in React
JS
Because javascript functions are not serializable , in order to pass them into new contexts sometimes ( albeit rarely ) it can be useful to stringify them then re-evaluate them later like : However , if foo references another function bar , the scope is not stringified , so if bar is not defined in the new context , th...
const foo = ( ) = > { // do something } const fooText = foo.toString ( ) // later ... in new context & scopeconst fooFunc = new Function ( ' return ( ' + fooText + ' ) .apply ( null , arguments ) ' ) fooFunc ( ) // works ! let bar = ( ) = > { alert ( 1 ) } let foo = ( ) = > { bar ( ) } // what toString doeslet fooStrin...
How can I `` recursively '' stringify a javascript function which calls other scoped functions ?
JS
Can you please explain the difference between two codes mentioned below ? and I am little confused at these lines : and I came to know the second one supports Inheritance and the first one not , Can you explain me what is the magic in the second one ?
function Person ( ) { } Person.prototype.dance = function ( ) { } ; function Ninja ( ) { } Ninja.prototype = Person.prototype ; function Person ( ) { } Person.prototype.dance = function ( ) { } ; function Ninja ( ) { } Ninja.prototype = new Person ( ) ; Ninja.prototype = Person.prototype ; Ninja.prototype = new Person ...
Question regarding Inheritance in JavaScript
JS
I 'm currently developing an image editor with HTML5 Canvas , and I 'm having a problem detecting the image coordinates when mousing over the canvas.I have replicated the problem in a code snipped with a rectangle : When : The red part is the border of the canvas . The canvas size is 400x400 pixels.The green part is a ...
const RECT_SIZE = 200const ZOOM = 1const svg = document.createElementNS ( 'http : //www.w3.org/2000/svg ' , 'svg ' ) const svgPoint = svg.createSVGPoint ( ) const xform = svg.createSVGMatrix ( ) const canvas = document.querySelector ( 'canvas ' ) const ctx = canvas.getContext ( '2d ' ) const res = document.querySelecto...
Canvas HTML5 : Display rect coordinates on mousemove
JS
The code ( a simple replace loop ) : So in this case both data and tree have the same output : What I want to do is to preserve the original value of data in tree so that only data changes but not tree.How to do that ? tree should remain like this :
fs.readFile ( filename , 'utf8 ' , function ( err , data ) { if ( err ) throw err data = data.split ( '\n\n ' ) var tree = data for ( var i = 0 ; i < tree.length ; ++i ) { if ( tree [ i ] .match ( /^ # /g ) ) { data [ i ] = data [ i ] .replace ( /^ # # # # ( . * ) /gm , ' < h4 > $ 1 < /h4 > ' ) .replace ( /^ # # # ( . ...
How do I create a clone of the following array rather than a reference ?
JS
On the gif , you can see input with consistent select ( ) behavior ( content selected on every click ) and second input where every 2nd click fails to select anythingI have global styles historically added to the projectWhat I found - user-select : none set on the parent is breaking select ( ) method for its children i...
* { user-select : none ; } input { user-select : text ; } .buggy * { user-select : none ; } .buggy input { margin-top : 10px ; user-select : text ; } < input type='text ' value='normal input ' onclick='this.select ( ) '/ > < div class='buggy ' > < div > < input type='text ' value='buggy input ' onclick='this.select ( )...
Inconsistent select ( ) bahavior for input when parent has user-select : none ( chromium-based browsers )
JS
In both Firefox 4 beta and Chrome latest.It 's like ... when is a boolean , not a boolean ?
> ( function ( ) { return this ; } ) .call ( false ) false > ! ! ( function ( ) { return this ; } ) .call ( false ) true
Please explain bizarre behavior of .call ( false )
JS
When clicked , I want a button to produce three child options , which then when tapped again should do retract and then disappear when behind the parent button . I hope this is clear from the code ( note this is a nativescript application , hence the slightly strange css choices ) .However , as you can see from the gif...
exports.fabTap = function ( args ) { var google = page.getViewById ( `` google '' ) ; var facebook = page.getViewById ( `` facebook '' ) ; var amazon = page.getViewById ( `` amazon '' ) ; if ( clicked == false ) { google.style.visibility = `` visible '' ; facebook.style.visibility = `` visible '' ; amazon.style.visibil...
JavaScript animations not running in order ?
JS
How would I make this jQuery shorter ? I assume there must be a better way of working than this ! ? ( bare in mind I am new to jQuery ) ... Any help or directions would be greatt as I am down to the last step on this site and want it finished : )
< script > jQuery ( function ( ) { var White = jQuery ( `` # white '' ) .hide ( ) ; jQuery ( `` # firstpagename '' ) .on ( `` click '' , function ( ) { White.toggle ( ) ; } ) ; } ) ; < /script > < script > jQuery ( function ( ) { var Black2 = jQuery ( `` # v2black '' ) .hide ( ) ; jQuery ( `` # secondpagename '' ) .on ...
Shortening my jQuery
JS
For object const a = { b : 1 , c : 2 , d : 3 } , we can do destructuring like this : const { b , ... rest } = a.I 'm wondering if it 's also possible for imports.Say I have a file file1.js : Can I import from this file by importing one and the rest like destructuring ?
// file1.jsexport const a = 1 ; export const b = 2 ; export const c = 3 ; // file2.jsimport { a , ... rest } from `` file1 '' ;
Javascript : import one and the rest ?
JS
Example input : Expected outputAttempt ; expanded from my previous one-liner ( for debugging ) : Runnable ( mocha+chai in a plnkr ) Note : ranges are guaranteed to be non-overlapping , and there may be other things in the array like 'foo ' which should be put in whatever order at the end of the array.Ideas : I could bu...
[ '50-59 ' , '60-69 ' , '40-49 ' , ' > =70 ' , ' < 40 ' ] [ ' < 40 ' , '40-49 ' , '50-59 ' , '60-69 ' , ' > =70 ' ] export function sort_ranges ( ranges : string [ ] ) : string [ ] { const collator = new Intl.Collator ( undefined , { numeric : true , sensitivity : 'base ' , ignorePunctuation : true } ) ; return ranges....
Sort array of ranges [ '55-66 ' , ' > 55 ' , ' < 66 ' ] ?
JS
I am looking for a way to add an item to an array that belongs to an item within another array using knockout and knockout mapping.I have the following , a Person which has an array of WorkItems that has an array of ActionPlans . Person > WorkItems > ActionPlans Knockout code is as follows - Array mappingArray item map...
var PersonViewModel = function ( data ) { var self = this ; ko.mapping.fromJS ( data , trainingCourseItemMapping , self ) ; self.addWorkItem = function ( ) { var WorkItem = new WorkItemVM ( { Id : null , JobSkillsAndExpDdl : `` '' , JobSkillsAndExperience : `` '' , ActionPlans : ko.observableArray ( ) , PersonId : data...
Knockout add to array of an array
JS
I was perusing the underscore.js annotated source when I encountered this : I now know from this stackoverflow question that the plus sign ( + ) operator returns the numeric representation of the object.That said , obj.length returns a number . When would obj.length not be equal to +obj.length ?
if ( obj.length === +obj.length ) { ... }
When is obj.length not equal to +obj.length ?