Can you set variables in the beginning of a file to be set through out?
Example:
var works = $('#id1');
var span = $('.icon');
works.focus(function() {
if(this.value.length == 0)
span.hide();
});
works.keyup(function() {
if(this.value.length > 0 && !span.is(':visible'))
span.stop().show();
else if(this.value.length == 0)
span.stop().hide();
});
The variable span inside the function doesn’t work. Instead of adding var span = $('.icon'); in each function is it possible I can make it work?
Thanks alot
Yes, you can have global variables, but if you initialize them in a
<script>block in the<head>they’ll be empty. The DOM won’t have been loaded.You can instead do this:
Not quite the same as globals, but in a way that’s better since true globals are kind-of a bad idea. Anything declared with
varinside the$(function() { ... })code will be effectively global to all code in that initialization function.Oh, and note that putting the initialization code in a function invoked with
$()is the jQuery way of deferring execution until the DOM is ready. That will work in a script in the<head>, and it’ll also work if you import your scripts at the end of the<body>as many luminaries now advise.