0

I have html anchor tags in my page that just take me to another part of the page, the code below is the jquery that controls the animation and scroll speed for the movement.

$("a").click(function(){
    $("html, body").stop().animate({scrollTop:$($.attr(this,"href")).offset().top},750);
    
    return !1
  })

the problem is that "return !1" causes the url not to change. Meaning, if I"m at "localhost:8000/", and I click a link with href="#contact", the url normally changes to "localhost:8000/#contact". The return !1 prevents that from happening, though for the life of me I can't figure out why or find an online resource to explain it. I've toyed with it, and I have to return !num, where num is any number other than 0, positive or negative. Can anyone explain this to me? I want to understand why this happens and what return !# is used for.

Jerrod
  • 115
  • 12

3 Answers3

1

When you return false (!1) in a jQuery event handler, it prevents the default action from completing and bubbling up the DOM.

And !ing any number is going to try to cast the number to a boolean (anything >0 will return true) and cancel it to a false.

Given that:

0 = false

1 = true

>1 = true

<0 = true

The following is true:

!0 = not false = true

!1 = not true = false

!2 = not true = false

!3 = not true = false

...etc

Tor
  • 784
  • 1
  • 13
  • 25
1

In JavaScript, any value apart from following are truthy

  • false
  • ""
  • 0
  • undefined
  • null

So when you do !1 it's equivalent to false.

So why do this and not return false? Because false has 5 characters and !1 has 2.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Fire up node or your browser's console and see what's happening:

➜  ~ node
> !1
false
> !0
true
> !!'foo'
true
> !!''
false

Returning false from a jQuery event handler stops the default browser behavior.

Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83