Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.