Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using :remote => true with hover event

I want to invoke an Ajax call in Rails. I've seen a good way of doing so with the :remote option. I've got this working example:

<%= button_to('Get Transfers', {:action => 'get_transfers', :section_id => params[:section_id]}, :method => :get, :remote => true) %>

However, I don't want the user to invoke the call by pressing a button or clicking a link, but rather invoke it on a Javascript event (hovering over an element).

Is there a way to use :remote => true, but invoke it automatically when hovering over an element? If yes, how?

like image 473
Uri Klar Avatar asked Jun 29 '26 18:06

Uri Klar


1 Answers

Option 1

To make the button respond to click and hover over some other div you can try doing the following:

In your view you give the button a unique id and add some class to an element that should be act as a trigger:

<%= button_to('Get Transfers', {action: 'get_transfers', section_id: params[:section_id]}, method: :get, remote: true}, {id: 'remote_hover_button'}) %>
<div class="some_trigger">Hover me!</div>

In your js you want to bind to that trigger element and trigger the click event on the button:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $('#remote_hover_button').trigger('click');
  });
});

Option 2

Write the ajax manually by creating a div that you hover and provide it with an url to call:

<div class="some_trigger" data-url="<%= url_for(action: 'get_transfers', section_id: params[:section_id]) %>">Hover me!</div>

Bind to the div and do an ajax call:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $.ajax($(this).data('url'));
  });
});

This will actually just trigger the action and not perform anything with the response. You can bind to the result with something like this:

$(document).ready(function(){
  $('.some_trigger').hover(function(){
    $.ajax($(this).data('url'))
      .done(function() { alert("success"); })
      .fail(function() { alert("error"); })
      .always(function() { alert("complete"); });
  });
});

For more information on ajax function look at the documentation.

like image 121
Milan Köpke Avatar answered Jul 01 '26 08:07

Milan Köpke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!