Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Thursday, 19 March 2020

Meteor VSCode esversion 6 jslint error

Problem:

When using Visual Studio Code to edit my Meteor project, I keep seeing the error:

'import' is only available in ES6 (use 'esversion: 6'). (W119) jshint(W119)

For example:

Workaround:

  • To hide the jshint errors: in the main folder of your Meteor project, if the file named ".jshintrc" does not exist then add it
  • In this .jshintrc file, add the following text:
    {
        "esversion": 6
    }
    

You may need to close and reopen the project in VSCode. If the workaround is successful, you should no longer see the esversion 6 error.

Notes:

This workaround was verified to help remove the jslint errors while using Visual Studio Code version 1.43.1 with Meteor 1.10.1. Your results may vary given different versions. Please also note that this workaround hides the jshint error from being highlighted, but it won't fix compilation errors if your Meteor project isn't properly setup to compile esversion 6.

References:

Sunday, 11 December 2016

Javascript Unix time to UTC string in Chrome console

Problem:

In the Chrome Dev Tools console, I'd like to view a Unix Time numerical value/timestamp as a human-readable UTC date/time string.

Solution:

In the Chrome Dev Tools console (and in general), one way to view a Unix (POSIX/Epoch) Time as a human-readable UTC string is to use Javascript Date.

For example, if the number of seconds since Epoch is 1480528272, we can convert this in the console by:

new Date(1480528272*1000).toUTCString()

Note that we need to convert the number of seconds to milliseconds since Epoch by multiplying by 1000.

Notes:

Note that due to the size of a Javascript integer, overflow may occur if the desired timestamp is larger than Number.MAX_SAFE_INTEGER.

A Javascript Date object also has a valid range that must be adhered to. More information can be found in here.

References:

Tuesday, 29 November 2016

View GWT emulated Long in browser developer tools

Problem:

I would like to see the long value of a GWT emulated Long in my browser's developer tools.

I already know how to pause and debug my web app, but when I inspect a Long value, it looks similar to {h:0, m:544, l:54210}.

Solution:

Imagine that we have an emulated Long value: myLongVal={h:1, m:234, l:567}

To translate this to a human-readable Long (in most, but not all cases), type the following in the developer tools console:

myLongVal.h*Math.pow(2,44) + myLongVal.m*Math.pow(2,22) + myLongVal.l

(See screenshot)

Notes:

This was verified to work in GWT 2.7. Your mileage may vary for other versions.

The above method should work for Long values that are low enough. However, overflow may occur for larger emulated Long values as the cast to a Javascript double does not cover as many bits as a long integer.

Note that if you have a browser that actually supports 64-bit integers or larger, you might be able to use the following:

(myLongVal.h << 44) + (myLongVal.m << 22) + myLongVal.l

References:

Friday, 30 November 2012

Check if a javascript variable contains a function

Problem:

How do I check if a value stored in a javascript variable is a function?

Solution:

While there are many ways to do this, the following code should work:

function isFunction(toCheck){
  return toCheck != null 
      && {}.toString.call(toCheck) == '[object Function]';
}

Notes:

Note that the first conditional, toCheck != null, may not be necessary. However, if null or nothing is passed to the function the result could be undefined otherwise (this was encountered, at least, in some older (or buggy?) implementations of javascript but might be a non-issue today -- feel free to test it out).

An alternative (and closely-related) method of checking is to directly call Object.prototype.toString.call() instead of instantiating an anonymous object.

References:

Monday, 22 October 2012

Find the min and max value of a javascript array

Problem:

I'd like to quickly find the minimum and maximum values stored in a javascript array without having kept track of them in advance, and without using a loop.

Solution:

One of the easiest ways to do this is to use Function.prototype.apply with Math.min and Math.max, e.g.

var min = Math.min.apply(null, myArrOfNumbers);
var max = Math.max.apply(null, myArrOfNumbers);

Notes:

When expanded, note that the first of the above examples is roughly equivalent to Math.min(myArrOfNumbers[0], myArrOfNumbers[1], ...). With that in mind, it should be cautioned that the solution in this post should only be used with small arrays, as many javascript engines have a limit as to how many arguments a function can accept, leading to unpredictable behaviour when this limit is exceeded.

For those interested, see more details in the following linked reference for javascript's Function.prototype.apply.

Reference:

Saturday, 6 October 2012

Replace every instance of a word in a string with a word stored in a variable using javascript

Problem:

In javascript, I'd like to replace every instance of a word (or substring) in a longer string, with a string stored in a variable.

For example, if I had the following string:

The red strawberries fell off the red table.

And I wanted to replace the word "red" with "dark red", the result should be:

The dark red strawberries fell off the dark red table.

However, I'd like to substitute "dark red" with any arbitrary string stored in a variable.

Solution:

One of the simplest ways to do this is to use the regular expression constructor combined with the 'replace' function. The easiest way to show this is by an example:

var replaceThis = "red";
var replaceWith = "dark red";
var theString = "The red strawberries fell off the red table.";

var theNewString =
  theString.replace(new RegExp(replaceThis, "g"), replaceWith);

More details:

Using the 'replace' function is a simple way to replace something in a string. Unfortunately, if you want to replace more than one instance of a substring in a string, passing two strings as parameters to the 'replace' function, such as in "str.replace('this', 'that')", will not work because the function will simply replace only the first match. In the highlighted example above, only the first instance of 'red' would have been replaced with 'dark red'. To get around this issue, the first parameter should be a regular expression, with the desired search string being 'red' and the modifier being 'g' for global matching. In javascript, this regular expression would look like: /red/g

However, regular expressions cannot be passed simply as strings, therefore passing "/red/g" or a variable containing that string as the first parameter of replace would have been interpreted as the string "/red/g" rather than the regular expression /red/g. This problem is worked around by converting the string of the regular expression to a valid regular expression via the regular expression constructor.

Additional details can be found at the following references:

Tuesday, 26 June 2012

Navigate or redirect to a url using javascript

Problem:

How do I use javascript to navigate to another url?

Solution:

The follow are two ways that can redirect a user to another page:

// redirect without updating browser history
window.location.replace("my-next-page.html");

In the above and below example "my-next-page.html" should be replaced with your own URL. The above example shouldn't update the change of pages in the browser history, whereas the next example will.

// redirect and update in browser history
window.location.href = "my-next-page.html";

Notes:

This was tested on the iOS 5.1 browser, Firefox 12, and with PhoneGap 1.5.0 on iOS 5.1. This should also work with most other browsers.

Saturday, 2 June 2012

Stop and complete all jQuery animations immediately

Problem:

I'd like to stop and complete all jQuery animations immediately. At one point my web app needs to progress to another stage and the smooth completion of several pending, long animations isn't needed.

Solution:

Edit: have a look at the comment below by Navigator regarding .finish() (see jQuery doc for the .finish() function). It's valid for jQuery 1.9 and above =) The points written in this post were tested for the jQuery version that was used when this post was originally written June 2012.

There are several ways to immediately stop and complete all animations that are currently running or pending in jQuery. Two of those methods will be outlined here.

One way to do this is by setting the jQuery.fx.off parameter to true, e.g.

jQuery.fx.off = true;

This will cause all queued animations to skip immediately to the final frame and complete. Note that while this parameter is set to true all animations will skip to their final states. To allow jQuery animations later on, set this parameter back to false.

The second way is more of a shotgun approach and probably isn't a good way to skip over animations in the general case. However, if you haven't been keeping track of all the selected elements that have a pending animation and thereby can't use the stop() method on them individually, you can try selecting all elements and calling the stop() function, e.g.

$("*").stop(true, true);

Note that the latter is extremely inefficient since it selects all elements on the page!

Notes:

These methods were tested on jQuery version 1.7.2 on Firefox 12.0 and the iOS 5.1 browser.

It isn't quite clear whether the jQuery.fx.off method will skip currently running animations to the final frame.

References:

Saturday, 19 May 2012

JQuery animation: execute callback only once when all completed

Problem:

When using the animate function after selecting more than one item, my callback function is executed as many times as there are items. How do I get the callback function to execute only once when the entire animation is done?

Problem Example:

If, for example, you have five items with the class 'do-something', and you try the following code:

var ctr = 0;
var selected = $(".do-something");

var mycallback = function(){
  ctr++;
  alert(ctr);
}

selected.animate({
  // ... your animation stuff ...
}, 200, mycallback);

Rather than the hoped for single alert with the number 1, you'll receive five alerts with the numbers 1 through 5.

Solution:

As of JQuery version 1.6 you can use the promise() and done() functions to fire off your callback once after all the animations are completed.

For example, again if you have five items with the class 'do-something' the following code should now produce a single alert with the number 1:

var ctr = 0;
var selected = $(".do-something");

var mycallback = function(){
  ctr++;
  alert(ctr);
}

selected.animate({
  // ... your animation stuff ...
}, 200);

selected.promise().done(mycallback);

Other notes:

This was tested to work using JQuery 1.7.2 and Firefox 12.0.

References:

Tuesday, 8 May 2012

Clearing an array in Javascript

There are a few ways to clear an array in Javascript. Two particularly useful ways are as follows:
  1. Assigning a new array:
    myArray = [];
  2. Refactoring the current array:
    myArray.length = 0;

The first method will assign a new array to the myArray variable. If there are any other pointers to the previous array, these will still point to the old array.

The second method changes the array itself. If there are any other pointers to the previous array, they will all be updated to the cleared array.

Sunday, 29 April 2012

Web script measuring sizes of images or divs breaks the first time, but not the rest with Javascript or JQuery

Problem:

A script that uses the width or height function to measure a loaded div or an image seems to break the first time the page is loaded, but not any subsequent times.

Possible diagnosis:

There are actually two problems in the above situation. The first problem is that the bug seemingly cannot be reproduced. The second problem is that the script will break for any users seeing the containing page for the first time.

One situation where this can occur is because the script is run by the browser prior to an image being loaded. For instance, the following example script can have this error occur:

$(document).ready(function(){
var divWidth = $("#mydivwithanimage").width();
doSomethingImportantWithWidth(divWidth);
});

The reason this script fails is because even though JQuery waits until the DOM is loaded prior to executing this script, this doesn't necessarily mean that other page components being loaded, such as images, have completed loading before this script is run. This leads to the funny problem that the script will only fail the first time it is run in an open browser, as the browser will cache all loaded images and other page components and often load them before the script is run when the page is reloaded.

Solution (for debugging):

The solution to reproducing this error while debugging is to clear all browser caches (javascript variables as well as loaded components) prior to re-running the script. In Firefox, you can simply clear your cache prior to completely quitting your browser. This should work with most other browsers, too. After re-launching the browser, the bug should appear once again.

Solution:

To correct the script, you need to ensure that it is run after all page components, such as images, are loaded, and not simply just the DOM. If you are using JQuery, rather than using $(document).ready(), use $(window).load(), e.g.

$(window).load(function(){
// ... your stuff here ...
});

For regular javascript, you can use the 'complete' property, e.g.

var myImage = new Image();
myImage.src = "img/myimage.png";

// ... later on ...
if(myImage.complete){
// ... do stuff ...
}

Saturday, 3 March 2012

jquery .val() after key pressed

When entering data into a text input (for purposes such as auto-suggest), the following example code seems to always be one step behind, in other words .val() is called too early, i.e. seemingly before the keystroke is done:

$("#some-form-text-input").live("keypress", function(e){
  alert($("#some-form-text-input").val());
});


An example of why this is undesirable is: if the text field already contained the string "somethin" and "g" is typed next, the alert in the callback would only display "somethin" versus the desired "something".

Solution: use the "keyup" rather than the "keypress" event

E.g.

$("#some-form-text-input").live("keyup", function(e){
  alert($("#some-form-text-input").val());
});


This waits until the latest pressed key is lifted before firing the callback.