0

Any one can tell me please, what is the different between this three things.

if ( document.location.href.indexOf('#Work') > -1 ) {
    $('#elementID').animate({"left": "250"}, "slow");
}


 if ( document.location.href.indexOf('#Work') > 0 ) {
    $('#elementID').animate({"left": "250"}, "slow");
}


if ( document.location.href.indexOf('#Work') != -1 ) {
    $('#elementID').animate({"left": "250"}, "slow");
}
Selvamani
  • 7,434
  • 4
  • 32
  • 43
  • 1
    `document.location.href.indexOf('#Work')` is vanila JavaScript not jQuery. – Ram Oct 29 '12 at 05:52
  • http://stackoverflow.com/questions/5757362/jquery-if-url-contains-work-then-do-something but here they answer is like this. – Selvamani Oct 29 '12 at 05:54
  • jQuery is only a JavaScript library, the part of your code that is related to the question is pure JavaScript. – Ram Oct 29 '12 at 05:57
  • okay, thank you for your command. Can you tell me please how this change to jquery code. – Selvamani Oct 29 '12 at 05:58
  • `$('#elementID').animate({"left": "250"}, "slow");` is jQuery. and jQuery is JavaScript. – Ram Oct 29 '12 at 06:18

3 Answers3

4

The "IndexOf" method will return the integer of location where a string was found within it's parent. In this case, "#Work" within document.location.href

  1. "> -1" Returned when string is found.

  2. "> 0" Returned when string is found after the first char

  3. "!= -1" Returned when string is found, regardless of place (same as #1)

BTW - This is core Javascript and not Jquery.

JAR.JAR.beans
  • 9,668
  • 4
  • 45
  • 57
1

The first and third examples are pretty much the same. indexOf only returns -1 when the substring could not be found, so they will work identically.

The second example will fail when href="#Work". #Work starts at the first character in the string, so indexOf would return 0.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

The javascript indexOf() method returns the position of the first occurrence of a specified value in a string and -1 if the value to search for never occurs. So technically the first and third are equivalent. And second one would not work as expected if the value to search appears at the beginning in the string.

Nils
  • 806
  • 1
  • 9
  • 24