Erick
Erick

Reputation: 23

Need help on link_to with on click event ruby on rails 4.2.6

I'm new to Rails. If anyone could help me convert this code into a ruby link_to method:

<a href="#top" onclick=$("#menu-close").click();>Home</a>

I tried to search google for an answer. But it made me more confuse on how to implement it on my site.

<%= link_to "Home" , {:action => "index", :controller => "welcome", :anchor => "top", :onclick => '$("#menu-close").click()' } %> 

but still it does not close the sidebar.

Here is also the script I put below the footer :

$("#menu-close").click(function(e) { 
  e.preventDefault(); 
  $("#sidebar-wrapper").toggleClass("active"); 
});

Upvotes: 0

Views: 4092

Answers (2)

MZaragoza
MZaragoza

Reputation: 10111

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 :)

Upvotes: 3

Aleks
Aleks

Reputation: 5320

In your erb file put:

<%= link_to 'Home', '#', id: '#top' %>

And in some of your js files put:

$('#top).on('click', function(e){
  e.preventDefault();
  $("#menu-close").click()
});

Upvotes: 1

Related Questions