I'm doing a free jQuery course on nettuts called 30 days to learn jquery by Jeffrey Way and I have four things I'm really stumped about, first off here's the code:
(function() {
$('html').addClass('js');
var contactForm = {
container: $('#contact'),
init: function() {
$('<button></button>', {
text: 'Contact Me'
})
.insertAfter('article:first-child ')
.on('click', this.show);
},
show: function() {
contactForm.container.slideDown(500);
}
};
contactForm.init();
})();
It basically slides down a contact form when you click the "contact Me" button on the website. My questions are:
.on('click', this.show);
why do you need this
in this.show
?contactForm.container.slideDown(500);
as in why can't you just say container.slideDown(500);
or $('form.contact').slideDown(500);
(by the way the id of the form that slides down is contact
.Whats the whole point of "init" and do you need it?
This code is creating a javascript object, with a function called init
, then calling that function. You could just as easily move this code outside of the object, but then you wouldn't be able to reuse it, and do other object oriented things with it.
why is the whole jquery code inside of a variable?
In Javascript (not just jQuery) everything is an object. Functions are an object, object are objects, etc. This code is creating an object with 3 variables: container
, which stores a jquery object; init
, which stores a function; and show
which stores a function. This is then being assigned to the contactform
variable.
on the string of code that says .on('click', this.show); why do you need this in this.show?
this.show
references the .show()
method on the this
object. In this context this
is the contactForm
object, and show
is the show function being passed as an object (but not called). The effect of this is when the button is clicked, the show function is called.
finally, why do you need contactForm.container.slideDown(500); as in why can't you just say container.slideDown(500); or $('form.contact').slideDown(500); (by the way the id of the form that slides down is contact.
Because container
is a property (i.e. a variable) that belongs to the contactform object. You could do something like $('#contact').slideDown(500);
but you already have a reference to $('#contact')
in contactform.container
, and not using it will cause unnecessary overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With