Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Beginners JavaScript question

Hello,

I am new to coding with Javascript and I am relatively understanding the new concepts I am learning, the only thing I am confused about is the method of identifying elements.

        $("#form span").hide();
        $("input,textarea").focus(function() {
            $(this).next().fadeIn("slow");
            }).blur(function() {
                $(this).next().fadeOut("slow");
            }).keyup(function() {
                //Check all required fields         
            });

            $("#email").keyup(function() {
                //Check valid email
            });

In the above code I understand the simple functions like: $("#form span").hide(); You are identifying the div id form and the span within that form and telling it to hide that element. However, when it comes to this function:

            $("input,textarea").focus(function() {
                $(this).next().fadeIn("slow");
                });

I am a little confused. I realize we are calling out the input elements on the page and that when the user is selecting the form element to fade in the span. What I am not understanding is the $(this).next() part of the code. Could someone explain what that bit of code is referring to?

Thanks for your time!

1 Answer

$(this) will be the form element which has been focused on.

.next() will get the next sibling in the DOM. So as you focus on each element the DOM element beside it will fade in.

Thank you for your response. How do we know that in this case $(this) refers to the form element? and so .next() refers to the next sibling in the div then, correct?

It's running in a function bound to the focus event of the input,textarea selector :

$("input,textarea").focus(...

So that code only runs when this is one of those.