Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the call to this jQuery function fail in Firefox?

I have the following line of code in a link on my webpage:

<a href="javascript:$('#comment_form').toggle('normal')" title="Comment on this post">

This produces a link that should pop open a hidden form. It works on Safari, but in Firefox, I just get an almost-empty page with nothing but the following text:

[object Object]

I'm sure this has something to do with the value returned by the jQuery function, but I'm not sure how to fix the call to the JavaScript function so it works in Firefox, too.

like image 833
mipadi Avatar asked Jan 12 '09 17:01

mipadi


3 Answers

For the love of...

<script type='text/javascript'>
jQuery(function($){   # Document ready, access $ as jQuery in this scope
    $("a#comment").click(function(){  # bind a click event on the A like with ID='comment'
         $('#comment_form').toggleClass('normal');  # Toggle the class on the ID comment form
         return false;  # stop the href from being followed. 
    }); 
});
</script>
....
<a id="comment" href="/you_need_javascript_sorry.html" title="Comment on this post">
   [Comment]
</a>

Please, don't embed JavaScript like you just did in the HTML.

If you embed JavaScript in HTML like that, you :

  1. Make messy code.
  2. Have weird problems like you just did with hacks to get around it
  3. Users trying to middle click links will get sent nowhere.
  4. Maintaining the executable part of your code interspersed in page links will end in failure.
  5. Don't gracefully degrade when users don't have javascript
  6. Become problematic when you start needing to do stuff like store quotes more than 2 layers deep.
like image 140
Kent Fredric Avatar answered Nov 06 '22 22:11

Kent Fredric


Try:

<a href="javascript:void($('#comment_form').toggle('normal'))" title="Comment on this post">

Containing the script inside a void() will suppress the browser from displaying the result of the execution.


Update

I directly answered the original question, with the solution that would take the least amount of effort. As it's mentioned in some of the other answers here, I personally would keep my markup and JavaScript separate and dynamically add an onclick handler instead of embedding the script inside the href attribute.

like image 40
Ates Goral Avatar answered Nov 06 '22 22:11

Ates Goral


Tried moving what's in href to onclick. In general, you should avoid JavaScript code in the href attribute.

like image 22
John Sheehan Avatar answered Nov 07 '22 00:11

John Sheehan