Reputation: 175
Super weird problem here. I'm having trouble getting jQuery to bind any selectors except document, inside a .js file.
example code:
$(document).click(function () {
$("#nav_primary").empty();
});
when I click anywhere, the nav_primary div empties, as expected, however, when I use this code:
$("div").click(function () {
$("#nav_primary").empty();
});
nothing happens when I click. UNLESS I enter it into my console. When I paste the above code into my firebug console, it loads as expected, and clicking anywhere empties out the div as expected.
I know javascript and jquery are both running, as I have this in my js and it logs as expected:
console.log("js is running");
if (jQuery) {console.log('jQuery is loaded!');}
I've heard there are conflicts with prototype, but I don't think i'm running it. here's my head:
<head>
<link href="/assets/application.css?body=1" media="all" rel="stylesheet" type="text/css" />
<script src="/assets/jquery.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
<script src="/assets/portfolio.js?body=1" type="text/javascript"></script>
<script src="/assets/application.js?body=1" type="text/javascript"></script>
<link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<meta content="authenticity_token" name="csrf-param" />
<meta content="(token here)" name="csrf-token" />
<!--[if !IE 7]>
<style type="text/css"> #main {display:table;height:100%} </style>
<![endif]-->
<!--[if lt IE 9]>
<script src='//html5shiv.googlecode.com/svn/trunk/html5.js'></script>
<![endif]-->
</head>
Upvotes: 0
Views: 343
Reputation: 14219
Without seeing your DOM and assuming you're putting those events inside $(function() { });
...
Try:
$(document).on('click', 'div', function () {
$("#nav_primary").empty();
});
Upvotes: 0
Reputation: 4942
Stupid answer. but did you put your code in ready
function
e.g.
$(function() {
$("div").click(function () {
$("#nav_primary").empty();
});
});
Upvotes: 2
Reputation: 262734
$("div").click(function () {
$("#nav_primary").empty();
});
Most likely the div you wanted to attach on was not yet in the DOM when you ran your code (and $("div")
was just an empty list).
Try this instead:
$(document).on("click", "div", function () {
$("#nav_primary").empty();
});
Upvotes: 0