This question already has an answer here:
All right, something REALLY frustrating and weird is going on. I have JQuery installed on my server, and I know it's imported correctly because when I run a simple...
$(function() { alert('hello') });
It alerts "hello." However, when I try to use a css selector...
$(".image").css("border","3px solid red");
It does not work! Yes, I'm 100% sure there is something with that class name in the file. Here's the real kicker, when I COPY PASTED my code into a jsFiddle it worked just fine. What gives?!
Have you test adding inside
$(document).ready(function(){});
?Your jsFiddle is set for
onload
in the upper left of the jsFiddle window. If you set it to "No Wrap - in Head" which simulates code in the<head>
tag, then your jsFiddle no longer works.The
onload
setting means that jsFiddle doesn't run your javascript until the page has been loaded.In your real page, you are probably running the javascript too soon before the page has been loaded.
You can either fix that by putting your javascript in it's own
.ready()
function:Or, you can make sure the javascript isn't loaded/run until right before the
</body>
tag which is a simple way to make sure the content of your page is loaded before the script runs.See this answer for more details on placing the
<script>
tag appropriately.