Get the size of the screen, current web page and browser window

You can get the size of the window or document with jQuery: // Size of browser viewport. $(window).height(); $(window).width(); // Size of HTML document (same as pageHeight/pageWidth in screenshot). $(document).height(); $(document).width(); For screen size you can use the screen object: window.screen.height; window.screen.width;

How can I guarantee that my enums definition doesn’t change in JavaScript?

Since 1.8.5 it’s possible to seal and freeze the object, so define the above as: const DaysEnum = Object.freeze({“monday”:1, “tuesday”:2, “wednesday”:3, …}) or const DaysEnum = {“monday”:1, “tuesday”:2, “wednesday”:3, …} Object.freeze(DaysEnum) and voila! JS enums. However, this doesn’t prevent you from assigning an undesired value to a variable, which is often the main goal of … Read more

How to get the children of the $(this) selector?

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection. jQuery(“img”, this); Which is the same as using .find() like this: jQuery(this).find(“img”); If the imgs you desire are only direct descendants of the clicked element, you can also use .children(): jQuery(this).children(“img”);

Generating random whole numbers in JavaScript in a specific range

There are some examples on the Mozilla Developer Network page: /** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max – min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than … Read more

How to print a number with commas as thousands separators in JavaScript

I used the idea from Kerry’s answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have: function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, “,”); } function numberWithCommas(x) { return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, “,”); } function test(x, expect) { const result = numberWithCommas(x); const pass = result === expect; … Read more

.prop() vs .attr()

Update 1 November 2012 My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr() to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John … Read more

Get all unique values in a JavaScript array (remove duplicates)

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values: function onlyUnique(value, index, self) { return self.indexOf(value) === index; } // usage example: var a = [‘a’, 1, ‘a’, 2, ‘1’]; var unique = a.filter(onlyUnique); console.log(unique); // [‘a’, … Read more

error code: 521