Posts

Showing posts with the label Javascript

AddEventListener Vs Onclick

Answer : Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches. Event Listeners (addEventListener and IE's attachEvent) Earlier versions of Internet Explorer implement javascript differently from pretty much every other browser. With versions less than 9, you use the attachEvent [doc] method, like this: element.attachEvent('onclick', function() { /* do stuff here*/ }); In most other browsers (including IE 9 and above), you use addEventListener [doc], like this: element.addEventListener('click', function() { /* do stuff here*/ }, false); Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser. The examples above represent using an anonymous function[doc]. You can also add an event liste...

Angular 1.6.0: "Possibly Unhandled Rejection" Error

Answer : Try adding this code to your config. I had a similar issue once, and this workaround did the trick. app.config(['$qProvider', function ($qProvider) { $qProvider.errorOnUnhandledRejections(false); }]); The code you show will handle a rejection that occurs before the call to .then . In such situation, the 2nd callback you pass to .then will be called, and the rejection will be handled. However , when the promise on which you call .then is successful, it calls the 1st callback. If this callback throws an exception or returns a rejected promise, this resulting rejection will not be handled , because the 2nd callback does not handle rejections in cause by the 1st. This is just how promise implementations compliant with the Promises/A+ specification work, and Angular promises are compliant. You can illustrate this with the following code: function handle(p) { p.then( () => { // This is never caught. throw new Error(...

Are 301 Redirects Possible Using Javascript Or JQuery?

Answer : I know this is an old question but the answers don't really address the primary issue that was presented in the question which is a 301 redirect for SEO purposes (and the answer today may very well be different than it was when the question was originally asked and answered). The answer that no, you can't 301 redirect from the client is technically correct, however (and more importantly) you don't necessarily need to. While a true 301 would be preferred, in cases like this one where it's not possible (or transitioning away from hashbang URLs back to traditional URLs for example), the question is really whether or not there's a viable alternative that accomplishes the goal. Search Engine Land did a detailed test of Google's capabilities regarding JavaScript and this is the related excerpt from that article: JavaScript Redirects We first tested common JavaScript redirects, varying how the URL was represented in different ways. Th...

Chart Js 2 How To Set Bar Width

Answer : You were right : The attribute you have to edit is barPercentage . But maybe the error comes from where you edited the value. As you can see in the bar chart options : Name : barPercentage - Type : Number - Default : 0.9 - Description : Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. Read More The attribute is actually stored in scales.xAxes (" Options for xAxes " table). So you just have to edit your chart this way : var options = { scales: { xAxes: [{ barPercentage: 0.4 }] } } Here is a fully working example with a custom width ( 0.2 ) for the bar : var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", ...

.append VS .html VS .innerHTML Performance

Image
Answer : All three are slow to me. Modifying the dom on each iteration is slow. http://jsperf.com/jquery-append-vs-html-list-performance/24 I just added a new test in there: var html = []; for (var i = 0; i < len; i++) { html.push('<div>Test ' + i + '</div>'); } document.getElementById('list').innerHTML = html.join(''); This is much faster again. :) My method in Firefox does 26k Ops/sec vs 1,000, 10,000, and 13 That benchmark is worthless. innerHTML is always faster than DOM manipulation. jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can. jQuery from benchmark var html = ''; for (var i = 0; i < len; i++) { html += '<div>Test ' + i + '</div>'; } $('#list').html(html); innerHTML from benchmark var list = document.getElementById('l...

Array Of Object Deep Comparison With Lodash

Answer : You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not. var isArrayEqual = function(x, y) { return _(x).differenceWith(y, _.isEqual).isEmpty(); }; var result1 = isArrayEqual( [{a:1, b:2}, {c:3, d:4}], [{b:2, a:1}, {d:4, c:3}] ); var result2 = isArrayEqual( [{a:1, b:2, c: 1}, {c:3, d:4}], [{b:2, a:1}, {d:4, c:3}] ); document.write([ '<div><label>result1: ', result1, '</label></div>', '<div><label>result2: ', result2, '</label></div>', ].join('')); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script> UPDATE June 22, 2018 This update is in response to the comment below: @ryeballar if any of the array is undefined it returns true. How would you solve this. Thanks in advance buddy As stated in the differenceWith documentation: ...

Ajax - JSON Doesnt Get Sent In PATCH Only

Answer : First, check that you use latest version of jQuery library: Older versions directly restrict unknown methods (PATCH is new one). I've tested on jQuery 1.7 - PATCH method working without problems. Second, not all browsers supports PATCH method using XMLHttpRequest: Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH: new XMLHttpRequest().open('PATCH', '/'); //Illegal argument To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json', xhr: function() { return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null ? new window.ActiveXObject("Microsoft.XMLHTTP") : $.ajaxSettings.xhr(); } }); A bit late, but this worked for me when I got...

Asynchronously Updating A Bootstrap Progress Bar With JQuery's $.ajax

Answer : aren't you dividing by zero here when host = 0 in the for loop? updateProgress(100/host); you can use a variable hosts to keep track of the number of hosts you have.Then the progress will be as below. var hosts = 23;// total number of hosts updateProgress((host/hosts)*100); The other thing is the ajax you're firing is asynchronous, so what's happening is it fires and doesn't wait for the results. You can either "scan" each host serially one at a time updating the progress bar or scan all of them simultaneously having the progress bar update as the asynch results come back. Can you specify which behavior you're trying to achieve? [UPDATE] toggle async flag in the ajax call below for what you want. function updateProgress(percentage){ if(percentage > 100) percentage = 100; $('#progressBar').css('width', percentage+'%'); $('#progressBar').html(percentage+'%'); } var hosts = 23; va...

AWS DynamoDB Scan And FilterExpression Using Array Of Hash Values

Answer : You should make use of the IN operator. It is also easier to use Placeholders for attribute names and attribute values. I would, however, advise against using a Scan in this case . It sounds like you already have the hash key attribute values that you want to find, so it would make more sense to use BatchGetItem . Anyways, here is how you would do it in Java: ScanSpec scanSpec = new ScanSpec() .withFilterExpression("#idname in (:val1, :val2, :val3)") .withNameMap(ImmutableMap.of("#idname", "ID")) .withValueMap(ImmutableMap.of(":val1", "123", ":val2", "456", ":val23", "789")); ItemCollection<ScanOutcome> = table.scan(scanSpec); I would imagine using the Javascript SDK it would be something like this: var scanParams = { "TableName":"myAwsTable", "AttributesToGet": ['ID','COMMENTS','DATE'], "Filte...

Call Function OnPress React Native

Answer : In you're render you're setting up the handler incorrectly, give this a try; <View> <Icon name='heart' color={this.state.myColor} size= {45} style={{marginLeft:40}} onPress={this.handleClick} /> </View> The syntax you're using would make sense for declaring an anonymous function inline or something but since your handler is defined on the class, you just reference it (not call it) using this.functionName in the props. A little late to the party, but just wanted to leave this here if someone needs it export default class mainScreen extends Component { handleClick = () => { //some code } render() { return( <View> <Button name='someButton' onPress={() => { this.handleClick(); //usual call like vanilla javascript, but uses this operator }} ...

AngularJS : Difference Between The Observe And Observeandwatch Methods

Answer : $observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}" , then in a directive: attrs.$observe('attr1', ...) . (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined .) Use $watch for everything else. $watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is p a r s e ′ d ( i . e . , e v a l u a t e d a s a n A n g u l a r e x p r e s s i o n ) i n t o a f u n c t i o n . ( I t i s t h i s f u n c t i o n t h a t i s c a l l e d e v e r y d i g e s t c y c l e . ) T h e s t r i n g e x p r e s s i o n c a n n o t c o n t a ...

Asynchronously Delay JS Until A Condition Is Met

Answer : Consider this: (function wait() { if ( chatroom.json ) { chatroom.render(); } else { setTimeout( wait, 500 ); } })(); This will check every half second. Live demo: http://jsfiddle.net/kBgTx/

Accessing The Web Page's HTTP Headers In JavaScript

Answer : It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current. Use the following JavaScript code to get all the HTTP headers by performing a get request: var req = new XMLHttpRequest(); req.open('GET', document.location, false); req.send(null); var headers = req.getAllResponseHeaders().toLowerCase(); alert(headers); Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one. For AJAX Requests: If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be ap...

Code Folding In Bookdown

Answer : Global Hide/Show button for the entire page To use @Yihui's hint for a button that fold all code in the html output, you need to paste the following code in an external file (I named it header.html here): Edit: I modified function toggle_R so that the button shows Hide Global or Show Global when clicking on it. <script type="text/javascript"> // toggle visibility of R source blocks in R Markdown output function toggle_R() { var x = document.getElementsByClassName('r'); if (x.length == 0) return; function toggle_vis(o) { var d = o.style.display; o.style.display = (d == 'block' || d == '') ? 'none':'block'; } for (i = 0; i < x.length; i++) { var y = x[i]; if (y.tagName.toLowerCase() === 'pre') toggle_vis(y); } var elem = document.getElementById("myButton1"); if (elem.value === "Hide Global") elem.value = "Show Global"; else ...

Angularjs Directives Isolated Scope + One-way Data-binding Not Working For Objects?

Answer : passing text is one-way binding(@) and passing object is two-way binding(=) passing object as text <custom-directive config="{{config}}"></custom-directive> scope in directive scope: { config: "@" } converting the string back to object in link var config = angular.fromJson(scope.config); You are correct, the issue is that your JavaScript objects are being passed by reference. Using a one-way binding copies the reference, but the reference will still point to the same object. My impression from the Angular docs for directives has always been: The '@' binding is intended for interpolated strings The '=' binding is intended for structured data that should be shared between scopes The '&' binding is intended for repeatedly executing an expression that is bound to the parent scope If you want to treat the bound object from the parent as immutable, you can create a deep copy the objects inside y...

Change The Default Base Url For Axios

Answer : Instead of this.$axios.get('items') use this.$axios({ url: 'items', baseURL: 'http://new-url.com' }) If you don't pass method: 'XXX' then by default, it will send via get method. Request Config: https://github.com/axios/axios#request-config Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution. To append 'api' to my baseURL, I have my default baseURL set as, axios.defaults.baseURL = '/api/'; Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/' axios({ method:'post', url:'logout', baseURL: '/', }) .then(response => { window.location.reload(); }) .catch(error => { console.log(error); }); Create .env.development , .env.production files if not exists and add there your API endpoint, for example: VUE_APP_...

Capturing Window.onbeforeunload

Answer : You have to return from the onbeforeunload : window.onbeforeunload = function() { saveFormData(); return null; } function saveFormData() { console.log('saved'); } UPDATE as per comments, alert does not seem to be working on newer versions anymore, anything else goes :) FROM MDN Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog() , window.alert() , window.confirm() , and window.prompt() methods may be ignored during this event. It is also suggested to use this through the addEventListener interface: You can and should handle this event through window.addEventListener() and the beforeunload event. The updated code will now look like this: window.addEventListener("beforeunload", function (e) { saveFormData(); (e || window.event).returnValue = null; return null; }); There seems to be a lot of misinformation about how to use this event going around (even in upvoted answer...

Bootstrap-select Add Item And Select It

Answer : You have a typo. Instead of: $('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>'); You need: $('#myselect').append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); Here is a JSFiddle demo: http://jsfiddle.net/xbr5agqt/ The "Add and select 'Soy Sauce' option" button does the following: $("#myselect").append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); $("#myselect").val(4); $("#myselect").selectpicker("refresh"); One slightly faster approach (used by the "Add and select 'Relish' option" button) is to append the new <option> element with the selected attribute already applied: $("#myselect").append('<option value="'+newitemnum+'" selected=...

Autoclose Alert

Answer : jsFiddle Demo This functionality is not possible with an alert. However, you could use a div function tempAlert(msg,duration) { var el = document.createElement("div"); el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;"); el.innerHTML = msg; setTimeout(function(){ el.parentNode.removeChild(el); },duration); document.body.appendChild(el); } Use this like this: tempAlert("close",1000); You can't close alert any how . But you can use div To show your alert MSG. function Mymsg(msg,duration) { var alt = document.createElement("div"); alt.setAttribute("style","position:absolute;top:50%;left:50%;background-color:white;"); alt.innerHTML = msg; setTimeout(function(){ alt.parentNode.removeChild(alt); },duration); document.body.appendChild(alt); } You can use as : Mymsg('close',2000) jsFiddle Demo Basically you...

AngularJS 'scrollTop' Equivalent?

Answer : $window.pageYOffset This is property from service $window I don't believe there's anything in Angular to get the scroll position. Just use plain vanilla JS. You can retrieve the scrollTop property on any element. https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop document.body.scrollTop Fiddle for you: http://jsfiddle.net/cdwgsbq5/ Inject the $window into your controller and you can get the scroll position on scroll var windowEl = angular.element($window); var handler = function() { console.log(windowEl.scrollTop()) } windowEl.on('scroll', handler); Fiddle Adaptation from another stackoverflow answer