link_to method and click event in Rails
You can use link_to_function
(removed in Rails 4.1):
link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'
Or, if you absolutely need to use link_to
:
link_to 'Another link with obtrusive JavaScript', '#',
:onclick => 'alert("Please no!")'
However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.
Instead, your Rails code should simply be something like this:
link_to 'Link with unobtrusive JavaScript',
'/actual/url/in/case/javascript/is/broken',
:id => 'my-link'
And assuming you're using the Prototype JS framework, JS like this in your application.js
:
$('my-link').observe('click', function (event) {
alert('Hooray!');
event.stop(); // Prevent link from following through to its given href
});
Or if you're using jQuery:
$('#my-link').click(function (event) {
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).
Need help on link_to with on click event ruby on rails 4.2.6
I hope what you are asking is for this
<%= link_to 'Home', '#top',:onclick => '$("#menu-close").click()'%>
to remove the on click and move it you can do something like this:
<%= link_to 'Home', '#top',class: 'menu-close-btn'%>
this would be in a js file
$(".menu-close-btn").click(function(){
....
});
I created a example on github https://github.com/mzaragoza/sample-opne-close-sidebar
what I have:
Js that will open and close the page
#app/assets/javascripts/application.js
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
Now some basic CSS
#app/assets/stylesheets/application.css
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
and last but not least in the views
#app/views/layouts/application.html.erb
<div id="mySidenav" class="sidenav">
<%= link_to 'X', 'javascript:void(0)', class: 'closebtn', onclick: "closeNav()" %>
<%= link_to 'Page 1', '#' %>
<%= link_to 'Page 2', '#' %>
<%= link_to 'Page 3', '#' %>
<%= link_to 'Page 4', '#' %>
</div>
I hope that this is able to help you out more.
You can see how it all comes together here
Happy Coding :)
Adding an onclick option to link_to method in rails?
If you are using 2.3.8, you don't have :remote => true. You need to use link_to_remote if you are try to do an ajax action.
So it would look something like:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}%>
<div id="populate_me"></div>
and your new method would have to handle the ajax request with something like
countries_controller.rb
def new
<do something>
render :update do |page|
page.replace_html 'populate_me', :partial => 'whatever'
end
end
UPDATED
If you want the onclick in addition to the ajax action, you can just pass it into the html options:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}, :html => {:onclick => 'alert("some javascript executed before ajax")'} %>
rails link_to with remote = true and jquery on click
Good question!!
I'm not sure about overriding the click
event (I'm sure it will be fine to bind twice, but I've not got any references)
--
Ajax
In regards to calling a preloader
, you'll want to use one of the ajax
hooks that Rails UJS provides:
#app/assets/javascripts/application.js
$(".button_click").on("ajax:beforeSend", function(){
// preloader load
}).on("ajax:complete", function(){
//preloader hide
});
This will be what you need
Trigger a click with jQuery using link_to of rails 4
Solved! I've solved this by loading the correct JS and executing it directly, using the 'active' parameter and without need a click on the links.
Thanks to everyone who helped me!
If someone wants to know, this is the code I've used (its coffeescript):
tournament = $('#main-wrapper').data('tournament')
$.get '/manager/tournaments/' + tournament + '/fixture.js', (data) -> data
Attaching onClick event to Rails's link_to_function
Ok, I'm a little confused about what you are doing, but I'm going to try and make some suggestions.
Rather than use link_to_function, use link_to_remote. Link to function calls javascript, but what you actually want to do is call back to a controller that then runs some rjs to either replace the full partial or, more likely, append the new partial (containing the step) to the end of your current steps.
This is similar to all those examples you will have seen where people append a comment to the end of their blog comments (expect using link_to_remote rather than remote_form_for) see 3/4 of the way through http://media.rubyonrails.org/video/rails_blog_2.mov
You can see the docs for link_to_remote here: http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html
How to call rails method from view on button or link click
The view and the controller are independent of each other. In order to make a link execute a function call within the controller, you need to do an ajax call to an endpoint in the application. The route should call the ruby method and return a response to the ajax call's callback, which you can then interpret the response.
As an example, in your view:
<%= link_to 'Add', '#', :onclick => 'sum_fn()' %>
<%= javascript_tag do %>
function sum_fn() {
/* Assuming you have jQuery */
$.post('/ajax/sum.json', {
num1: 100,
num2: 50
}, function(data) {
var output = data.result;
/* output should be 150 if successful */
});
}
<% end %>
In your routes.rb
add a POST
route for your ajax call endpoint.
post '/ajax/sum' => 'MyController#ajax_sum'
Then suppose you have a MyController class in mycontroller.rb
. Then define the method ajax_sum
.
class MyController < ApplicationController
# POST /ajax/sum
def ajax_sum
num1 = params["num1"].to_i
num2 = params["num2"].to_i
# Do something with input parameter and respond as JSON with the output
result = num1 + num2
respond_to do |format|
format.json {render :json => {:result => result}}
end
end
end
Hope that hopes!
Related Topics
Ruby Array to String Conversion
Rails 4: How to Reset Test Database
Rails Mapping Array of Hashes Onto Single Hash
Why 'Self' Method of Module Cannot Become a Singleton Method of Class
In Ruby, When Should You Use Self. in Your Classes
Adding Attributes to a Ruby Object Dynamically
How to Convert a Comma-Separated String into an Array
How to Get the Parent's Class Name in Ruby
How to Use a Rack Middleware Only for Certain Paths
What Is Mattr_Accessor in a Rails Module
How to Create a Copy of Some Columns of a CSV File in Ruby with Different Data in One Column
If String Is Empty Then Return Some Default Value