Delicious Mangos
Delicious Mangos

Reputation: 55

Jquery Focusing on div to apply CSS style

I have various styles, such as:

.line{}

And:

.line:focus{}

Each have their own unique look.

What I want to do is have jquery focus on a div with the .line class and thus change it's style to line:focus. However, when using $('.line').focus();, the style does not change, and I'm reasonably sure the div with .line class is not focused on.

Any ideas/suggestions? Thanks in advance :).

Upvotes: 1

Views: 1741

Answers (4)

Joe
Joe

Reputation: 82554

jQuery's focus would work, demo


Edit:

Without a focus-able element, I would use toggleClass demo2

Upvotes: 1

WayHunter
WayHunter

Reputation: 1225

$('input').focus(function() {
     $(this).css('background','green'); 
});

See example

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83358

div elements don't support a focus state that I'm aware of, so you'll have to manually change the divs style anytime one of its inputs is focused (and of course change it back when the input is blurred).

$("div.line input").focus(function() {
    $(this).closest(".line").addClass("line-focus");
}).blur(function() {
    $(this).closest(".line").removeClass("line-focus");
});

And of course change

.line:focus {  }

to

.line-focus {  }

Upvotes: 0

Rodik
Rodik

Reputation: 4092

$(".").focus() only works on certain elements. DIV isn't a supported element to be focused.

You can try to recreate focus using .click

 $("div").click(function(){
   $(this).toggleClass('focused');
   if ($(this).hasClass('focused')){
      // do something
   }else{
      // do something else
   }
});

Upvotes: 0

Related Questions