How to cache selectors?

var buttons = $("a.validSelector");

$(window).load(function (){
    // Partle partle partle
});

$(document).ready(function (){
	$("a.validTrigger").click(function (){
		buttons.fadeIn();                // DOESN'T WORK
		$("a.validSelector").fadeIn();   // DOES WORK
	});
});

What am I doing wrong? This isn’t OOP nor PHP functions where variables have to be in each other scopes. I clearly defined buttons in global scope. And there are no errors in console.

Where do you have that code? If it iis anywhere other than just before the tag then your problem is that you are running it too soon.

That your code includes ready (never necessary when the code is attached to the page correctly) and load (almost never necessary) makes it look like you are attaching the script in the wrong place.

Where do you have that code?
In the file, that I include into <head> through script.

Try moving iit to where 99.999999%+ of al JavaScript belongs - just before the tag.

It is included there in head. Just before the ending tag.

when it should be in the body. It doesn’t work because you have tags following it other than </body></html> which are the only two tags that should come after </script>

So, where do I put it, before </body>?

All the scripts should be attached at the very bottom like this:

<script src="yourscript1.js"></script>
<script src="yourscript2.js"></script>
</body></html>
1 Like

The problem is that when you search for “a.validSelector” those elements don’t exist in the page yet, like felgall says if you move the scripts to the end of the body then those elements will exist.

Or, you can re-arrange the scripts to run when the document has fully loaded.

$(document).ready(function(){
  var buttons = $("a.validSelector");
  $("a.validTrigger").click(function (){
    buttons.fadeIn();
  });
});
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.