Archives For jQuery

Scale Value with Javascript

I was looking for a quick and easy way to get a scale value of a css -webkit-transform with javascript.

The html and css:

<div id="transformed"></div>

#transform {
    -webkit-transform: scale(.8);

First, we need to get the property value of -webkit-transform. I’ll use jQuery.

var div = $('#transform').css('transform');

The transform property will return matrix(0.8, 0, 0, 0.8, 0, 0).

To get the scale from the matrix, we will need to turn the matrix into individual values, then we can do math:
var values = div.split(‘(‘)[1];
values = values.split(‘)’)[0];
values = values.split(‘,’);

var a = values[0];
var b = values[1];

var scale = Math.sqrt(a*a + b*b);
console.log(scale) // .80

In jQuery, getting a numeric property returns a string.
What if we want a css property value as an integer or float?


function linkify(text) {
    var exp = /(\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])))/ig;
    var linkedText = text.replace(exp,'<a href="$1" target="_blank">$1</a>');
    // when user puts in 'www' replace it with 'http://www'
    return linkedText.replace('="www.','="http://www.');

John Grubber’s RegEx for URL

Three different ways to check if an element exists using a selector in jQuery.

if ($("#mydiv").length > 0){
  // do something here

if ($("#mydiv").length){
  // do something here

if ($("#mydiv")[0]) {
  // do something

I want a click event on a div, and it will fire anywhere in the div except for the button inside it.

$(".div").click(function() {
    // Click event for the div, I'm slide toggling something
    alert("clicked div");

$(".button").click(function(e) {
    // Do stuff for the button click, but don't fire event above
    alert("clicked button");

source: Event Order

Javascript has a built in function encodeURIComponent(str) and encodeURI(str) to encode strings into url.


This function encodes special characters, except: , / ? : @ & = + $ #

var url = "1234 fake street";
url = encodeURI(url);
alert(url); // this prints out "1234%20fake%20street"


This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

var url ="san jose, ca";
url = encodeURIComponent(url);
alert(url); // this prints out "san%20jose%C%20ca"