div div - 1 year ago 57
jQuery Question

JQuery .on("click") only firing after second click

so I've been trying to animate a menu by clicking on a menu box (similar to Medium's menu). So far everything works, and on a full blown page refresh the JQuery event fires the first time without any problems.

However, when I click on a link in the menu, it'll take me to the page but then the menu button doesn't work on the first click, but it works perfectly fine on the second click. This happens without fail.

I've looked at several other questions similar to this but none of their solutions are solving my problem. Does anyone have any ideas what might be going wrong? Oh, and I'm also using Ruby on Rails 4 if this affects it at all.

Menu Button HTML

<div id="menu-hex"></div>


<%= link_to(root_url) do %>
<h3 class="am"><span class="icon-home profile-icos"></span> Daily Feed</h3>
<% end %>
<li class="coming-soon">
<%= link_to(root_url) do %>
<h3 class="am"><span class="icon-fire profile-icos"></span> Improve</h3>
<% end %>
<li class="coming-soon">
<%= link_to(root_url) do %>
<h3 class="am"><span class="icon-star profile-icos"></span> Events</h3>
<% end %>
<li class="coming-soon">
<%= link_to("/login") do %>
<h3 class="am"><span class="icon-bookmarks profile-icos"></span> Communities</h3>
<% end %>


#menu-hex {
position: absolute;
left: 6px;
top: 7px;
background-image: url('homehex.png');
width: 65px;
height: 65px;
background-size: 100%;
cursor: pointer;
z-index: 20;

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;


var menuOn = false;
var duration = 250;

$(document).on("click", "#menu-hex", function(e) {
if(menuOn == false) {
}else {


$(document).on("click", ".overlay", function(e) {
if(menuOn == true) {


function openMenu() {

$(".overlay").css( "display", "block" );

$("#focusimage").animate({opacity: 0.2}, duration);
$("#spot-content").animate({"left":"-300px"}, duration, function()
{ $("#spot-content").css( "display", "none" ) });

$("#menu").animate({"left":"25px", opacity: 1.0}, duration);

menuOn = true;

function closeMenu() {

$(".overlay").css( "display", "none" );

$("#focusimage").animate({opacity: 1.0}, duration);

$("#spot-content").css( "display", "block");
$("#spot-content").animate({"left":"25px"}, duration);

$("#menu").animate({"left":"-300px", opacity: 1.0}, duration);

menuOn = false;

div div
Answer Source

Thanks for your responses.

I found out my problem. It's that Rails 4 uses turbolinks. My solution was found here: Rails 4: how to use $(document).ready() with turbo-links

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download