Top javascript Questions

List of Tags

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how, and if not what plugin do you recommend?

Answered By: Artem Barger ( 1598)

You don't need jQuery for that purpose. You can use the pure JavaScript:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
1287
e-satis

Like the old Albert Einstein said: "If you can't explain it to a six-year old, you really don't understand it yourself.”. Well, I tried to explain JavaScript closures to a 27-year old friend and completely failed.

How would you explain it to a 6-year old person that is strangely interested in that subject?

EDIT:

I have seen the Scheme example given in Stack Overflow, and it did not help.

Answered By: Ali ( 942)

Whenever you see the function keyword within another function, the inner function has access to variables in the outer function.

function foo(x) {
  var tmp = 3;
  function bar(y) {
    alert(x + y + (++tmp));
  }
  bar(10);
}
foo(2)

This will always alert 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo.

That is not a closure. A closure is when you return the inner function. The inner function will close-over the variables of foo before leaving.

function foo(x) {
  var tmp = 3;
  return function (y) {
    alert(x + y + (++tmp));
  }
}
var bar = foo(2); // bar is now a closure.
bar(10);

The above function will also alert 16, because bar can still refer to x and tmp, even though it is no longer directly inside the scope.

However, since tmp is still hanging around inside bar's closure, it is also being incremented. It will be incremented each time you call bar. As a result of this it will alert 17 the second time bar(10) is called, 18 the third time, etc.

(Not for your 6 year old: It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same x and the same tmp, they don't make their own copies.)

Edit: And now to explain the part that isn't obvious.

Here the number x is a literal number. As with other literals in JavaScript, when foo is called, the number x is copied into foo as its argument x.

On the other hand, JavaScript always uses references when dealing with Objects. If say, you called foo with an Object, the closure it returns will reference that original Object!

function foo(x) {
  var tmp = 3;
  return function (y) {
    alert(x + y + tmp);
    x.memb = x.memb ? x.memb + 1 : 1;
    alert(x.memb);
  }
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);

As expected, each call to bar(10) will increment x.memb. What might not be expected, is that x is simply referring to the same object as the age variable! After a couple of calls to bar, age.memb will be 2!

This is the basis for memory leaks with HTML objects, but that's a little beyond the scope of this, ahem, article, ahem. How do JavaScript closures work?

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:

Problem at line 1 character 1: Missing "use strict" statement.

Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.

So what is "use strict"; all about, what does it imply, and is it still relevant?

Do any of the current browsers respond to the "use strict"; string or is it for future use?

Answered By: Pascal MARTIN ( 836)

This article about that might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More

To quote some interesting parts:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

And:

Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):

// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code... 

Which might be helpful if you have to mix old and new code ;-)

So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.

1177
venkatachalam

How can I redirect the user from one page to another using jQuery?

Answered By: Ryan McGeary ( 2737)

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
1019
gramm

How can I check if one string contains another substring in JavaScript?

Usually I would expect a String.contains() method, but there doesn't seem to be one.


Update: It seems that I have another problem.

When I use the ".indexof" method, Firefox refuses to start the JavaScript code (this is for an extension).

My code is:

var allLinks = content.document.getElementsByTagName("a");

for (var i=0, il=allLinks.length; i<il; i++) {
    elm = allLinks[i];
    var test = elm.getAttribute("class");
    if (test.indexof("title") !=-1) {
        alert(elm);
        foundLinks++;
    }
}

if (foundLinks === 0) {
    alert("No title class found");
} 
else {
    alert("Found " + foundLinks + " title class");
}

Firefox doesn't display an alert box. This works if I get rid of the .indexof() method. I already tried something like if (test=="title")..., but it didn't work.

Answered By: Fabien M&#233;nager ( 1602)

indexOf returns the position of the string in the other string. If not found, it will return -1:

var s = "foo";
alert(s.indexOf("oo") !== -1);
964
2cBGj7vsfp

When building a link that has the sole purpose to run JavaScript code, there are 2 ways to write the code. Which is better, in terms of functionality, page load speed, validation purposes, etc?

<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>

/* or */

<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
Answered By: AnthonyWJones ( 730)

I use javascript:void(0).

Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() {
    //Some code
    return false;
}

But then they forget to use return doSomething() in the onclick and just use doSomething().

A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.

A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:

onclick="someFunc.call(this)"

OR

onclick="someFunc.apply(this, arguments)"

Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.

So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:

Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

OR

Use href="javascript:void(0)"

The second is clearly much easier to communicate.

943
Jeffrey Schrab

What is the most efficient way to clone a JavaScript object? I've seen:

obj = eval(uneval(o));

but that's not cross platform (FF only). I've done (in Mootools 1.2) things like this:

obj = JSON.decode(JSON.encode(o));

but question the efficiency. I've also seen recursive copying function, etc. I'm pretty surprised that out-of-the-box JavaScript doesn't have a method for doing this.

Answered By: John Resig ( 1594)

I want to note that the .clone() method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.

908
Joneph O.

I'm using JSLint to go through some horrific JavaScript at work and it's returning a huge number of suggestions to replace == with === when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

I'm basically wondering if there is a performance benefit to replacing == with ===. Any performance improvement would probably be welcomed as there are hundreds (if not thousands) of these comparison operators being used throughout the file.

I tried searching for relevant information to this question, but trying to search for something like "=== vs ==" doesn't seem to work so well with search engines...


So... Would I be correct in assuming that if no type conversion takes place, there would be a small (probably extremely small) performance gain over ==?

Answered By: Bill the Lizard ( 962)

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

Reference: Javascript Tutorial: Comparison Operators

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

To quote Douglas Crockford's excellent JavaScript: The Good Parts,

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


Update:

A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning reference types. For reference types == and === act consistently with one another (except in a special case).

var a = [1,2,3];
var b = [1,2,3];

var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };

var e = "text";
var f = "te" + "xt";

a == b            // false
a === b           // false

c == d            // false
c === d           // false

e == f            // true
e === f           // true

The special case is when you compare a literal with an object that evaluates to the same literal, due to its toString or valueOf method. For example, consider the comparison of a string literal with a string object created by the String constructor.

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects.

798
Prasad

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if($('#isAgeSelected').attr('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

How do I successfully query the checked property?

Answered By: karim79 ( 1015)

Try this:

if ($('#isAgeSelected').is(':checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
} 

You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:

$('#isAgeSelected').is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

EDIT (14 months later): There's a much prettier way to do this, using toggle:

$('#isAgeSelected').click(function () {
    $("#txtAge").toggle(this.checked);
});

<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>​

Fiddle Demo