iCyborg
iCyborg

Reputation: 4728

How to create a link which will execute js code in Rails

I was wondering how to create a link in a view (index.html.erb) which will execute js/jquery code.

I am using https://github.com/akzhan/jwysiwyg and is looking to hide the editor but not sure how to do it.

Right now I am doing

EDIT -

index.html.erb

<%= link_to "Hide", "#", onclick: "$('#email_body').hide();" %>

index.js.erb

$('#wysiwyg').wysiwyg('clear');

Thanks

Upvotes: 0

Views: 74

Answers (2)

Valentin V
Valentin V

Reputation: 25739

You can use rails link_to helper for this:

link_to "Hide", "#", confirm: "Are you sure?", onclick: "$('#wysiwyg').wysiwyg('clear');"

Better coding practice would be to separate the JavaScript code from your view code, for example:

link_to "Hide", "#", id: 'hide_editor'

then, in a separate JavaScript file:

(function(){
  $('#hide_editor').on('click', function(){
    $('#wysiwyg').wysiwyg('clear');
  });
})();

Then place a link to this JS before your closing BODY tag.

UPDATE: As I can see, this plugin doesn't support disabling, you can disable it by hiding the container: $('#wysiwyg').hide();

$('#wysiwyg').wysiwyg('clear') clears the contents of the editor, as I see it in the docs.

UPDATE2: @iCyborg, based on your code, here is the working example: http://jsbin.com/esuyij/1/

UPDATE3: I've looked into this editor and find its customization options not flexible enough. May I suggest you look into other editors? For example there is a line-up here: http://www.jquery4u.com/plugins/html5-wysiwyg/

Upvotes: 1

shweta
shweta

Reputation: 8169

Try:

<a href="#" onclick="$('#wysiwyg').wysiwyg('clear');" id="NOT_SURE_WHAT_ID_TO_GIVE">Hide Editor Controls</a>

Upvotes: 0

Related Questions