I’m new to jquery but I’m trying to learn. I’m working with a drop down button that works just fine in jsfiddle. However, when I try it in my rails 3 app, it won’t work. (nothing drops down when you click the link). working jsifiddle http://jsfiddle.net/rKaPN/32/
If I remove the line $(".menu").fixedMenu(); and add it into the html like this it works. I’m stumped as to why its not working unless I remove the $(".menu").fixedMenu(); line
NOT working
(function ($) {
$.fn.fixedMenu = function () {
return this.each(function () {
var menu = $(this);
$("html").click(function() {
menu.find('.drop-down').removeClass('drop-down');
});
menu.find('ul li > a').bind('click',function (event) {
event.stopPropagation();
//check whether the particular link has a dropdown
if (!$(this).parent().hasClass('single-link') && !$(this).parent().hasClass('current')) {
//hiding drop down menu when it is clicked again
if ($(this).parent().hasClass('drop-down')) {
$(this).parent().removeClass('drop-down');
}
else {
//displaying the drop down menu
$(this).parent().parent().find('.drop-down').removeClass('drop-down');
$(this).parent().addClass('drop-down');
}
}
else {
//hiding the drop down menu when some other link is clicked
$(this).parent().parent().find('.drop-down').removeClass('drop-down');
}
})
});
}
$(".menu").fixedMenu();
})(jQuery);
Working
html
<script>
$('document').ready(function(){
$('.menu').fixedMenu();
});
</script>
js
(function ($) {
$.fn.fixedMenu = function () {
return this.each(function () {
var menu = $(this);
$("html").click(function() {
menu.find('.drop-down').removeClass('drop-down');
});
menu.find('ul li > a').bind('click',function (event) {
event.stopPropagation();
//check whether the particular link has a dropdown
if (!$(this).parent().hasClass('single-link') && !$(this).parent().hasClass('current')) {
//hiding drop down menu when it is clicked again
if ($(this).parent().hasClass('drop-down')) {
$(this).parent().removeClass('drop-down');
}
else {
//displaying the drop down menu
$(this).parent().parent().find('.drop-down').removeClass('drop-down');
$(this).parent().addClass('drop-down');
}
}
else {
//hiding the drop down menu when some other link is clicked
$(this).parent().parent().find('.drop-down').removeClass('drop-down');
}
})
});
}
})(jQuery);
The line:
cannot be executed until the page has been loaded and the DOM is fully in place.
Thus, it works when you surround it with
$(document).ready()and doesn’t work when you directly executed it in your startup JS. When it’s executed before the DOM is ready, the DOM object$(".menu")can’t be found so it does nothing.It works in the jsFiddle because ALL your code is wrapped in an onload handler (per the settings in the upper left of the jsFiddle).