I’m completely new to JQuery (and Javascript for that matter), but am willing to get down and dirty with it
However, it seems I’ve fallen at the first hurdle
I’d like to get your advice on best practice when beginning a script. I’ve heard that $(document).ready() is the best way to start a script, since it initiates the scripts contained within it at the earliest possible time. However, I’m having issues with combining multiple functions into one $(document).ready(). For example:-
$(document).ready(
function() {
var showText='more info';
var hideText='close';
var is_visible = false;
$('.toggle').prev().append('<a href="#" class="toggle-link">'+showText+'</a>');
$('.toggle').hide();
$('a.toggle-link').click(function() {
is_visible = !is_visible;
$(this).html( (!is_visible) ? showText : hideText);
$(this).toggleClass('close');
$(this).parent().next('.toggle').toggle('fast');
return false;
})};
function() {
// Next function
};
);
The above script is contained within a JS file that is used to store miscallaneous scripts; in this case, is it best practice to nest each script in a function, like I’m doing above?
In the above script, I believe I’ve closed all the parenthesis and curly brackets, so I’m unsure as to why it’s not working - the error is “missing ‘)’ after argument list”, which doesn’t make sense to me at all.
The ready() function accepts a function as its argument, not a list of statements (such as multiple other function definitions), which is where you went wrong.
jquery supports multiple event handlers for an event(including the ready event). Sometimes this might be more convenient. Btw- $(someFunction); is equivalent shorthand for $(document).ready(someFunction);
$(document).ready(function() {
hello(){
var showText='more info';
var hideText='close';
var is_visible = false;
$('.toggle').prev().append('<a href="#" class="toggle-link">'+showText+'</a>');
$('.toggle').hide();
$('a.toggle-link').click(function() {
is_visible = !is_visible;
$(this).html( (!is_visible) ? showText : hideText);
$(this).toggleClass('close');
$(this).parent().next('.toggle').toggle('fast');
return false;
});
hello2() {
// Next function
};
});
I have defined two functions, encapsulating them both in a document.ready() function. However, I’m still getting an error message; it’s saying there’s a missing semi colon before my first statement. However, my script is modelled exactly from the advice of you guys, so I’m unsure what’s wrong.
If you want to define a function called hello, then put the word function in front of it. It’s expecting hello() to be a function call, since nothing else really makes sense about that line to the interpreter.
If you just want that code to execute when the page loads, then take away the unnecessary wrapper.
If you did want to define two functions called hello and hello2, there’s no reason to do it inside of the document ready function. Define them outside and call them in there.