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
Jenny Swift
21,999 PointsWhat's wrong with my jQuery?
Hi, I am trying to show an element with the class "message" when an text input element with the class "input" has received focus, and hide the message when the text input has lost focus. I know I can do this with .focus() and .blur(), but I want to know how to do it with "if" and "else", too, because I would also like to be able to show an element based on whether or not a certain radio button is selected and I don't think .blur() or .focus() works on radio buttons.
Can anyone please tell me what is wrong with the following code (I've tried it and it isn't working.), and also how I would show and hide an element based on whether a radio button is selected or not?
$(".message").hide();
function focused() {
if ($(".input").is(":focus")) {
$(".message").show();
} else {
$(".message").hide();
}
}
focused();
1 Answer
István Turupoli
11,950 PointsI think it's because the focused() function only gets executed once. If you wrap it in a setInterval method, that it will check the statement continuously. Something like this:
setInterval(function(){
focused();
},10);
I think this way the :checked selector will work on radio buttons too, but I haven't tried it.
Jenny Swift
21,999 PointsJenny Swift
21,999 PointsBrilliant. That worked for the input and the radio button too. Thank you so much!