Trouble using 'link_to' and jQuery

3

I am using Ruby on Rails 3.0.7 and jQuery 1.6.1 and I am binding an AJAX click event to a link_to HTML output as in the following example:

link_to 'Link name', '#', :id => 'link_css_id'

As you can see I set the URL to '#'. Doing that when I click on the link the current view will be moved at the top of the page, as well. Since I don't like this behaviour, I set nothing (that is, nil or '') for the URL parameter, but on clicking on the link I get an alert message "error" that immediately after disappear. Then in the Firebug Console I get:

uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource://gre/components/nsPrompter.js :: openTabPrompt :: line 468" data: no]

How can I solve this issue and avoid the behavior of going at the top of the page on clicking the link?


The AJAX request is:

$jQ('#link_css_id').bind('click', function() {
  $jQ.ajax({
    type:    "POST",
    url:     "<%= user_url(@current_user)%>/test_method",
    data:    "test_data=test",

    error:   function(jqXHR, textStatus, errorThrown) {
      alert(textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
      $jQ('#css_id').html('error')
    },
    success: function(data, textStatus, jqXHR) {
      $jQ('#css_id').html('success')
    }
  });
});
jquery
ruby-on-rails
ruby
ruby-on-rails-3
link-to
asked on Stack Overflow Jun 23, 2011 by user502052 • edited Jun 23, 2011 by user502052

3 Answers

9

The url "#" means an internal anchor is being set. With no name attached to it, it simply focuses on the whole page, and scrolls back up to the top. As for using the link_to method, the url attribute is required and cannot be omitted.

With jquery, you can use preventDefault. This will prevent the default action from the event (e.g.., clicking on a link will open the href url). This is quite useful. You might want to link to an existing page for users that do not have javascript enabled (and where the ajax call won't work), while it is being ignored by those who do have javascript.

preventDefault documentation by jQuery.

answered on Stack Overflow Jun 23, 2011 by Justus Romijn • edited Jun 20, 2020 by Community
2

you can set javascript:void(0) instead of # it help me.

answered on Stack Overflow Jun 23, 2011 by bor1s
1

Keep the #, and use preventDefault to stop the default click event from moving the window.

http://api.jquery.com/event.preventDefault/

answered on Stack Overflow Jun 23, 2011 by Nick

User contributions licensed under CC BY-SA 3.0