MajAfy
MajAfy

Reputation: 3097

Remove :focus with jquery

I have an input field. When a user focuses on this field, the background of this field will change.

I have a link on my page, too. I want to remove :focus when the mouse hovers on this link and the user is on that input field.

I use removeClass(':focus') but this code does not work!

HTML:

<form>
    <input type="text" name="email" />
</form>
<a href="#" id="link">Sample Link</a>

Javascript:

$(document).ready(function () {
    $('#link').hover(function (){
        $('form input[name=email]').removeClass(':focus');        
    }, function (){
        $('form input[name=email]').addClass(':focus');        
    });
});

CSS:

form input[name=email]:focus {
    background-color: yellow;    
}

Here is a fiddle for the above

What should I do?

Upvotes: 21

Views: 75198

Answers (3)

Somnath Kharat
Somnath Kharat

Reputation: 3610

Try this:

$(document).ready(function () {
    $('#link').hover(function (){
        $('form input[name=email]').blur();  
        $('form input[name=email]').css("background-color","");     
    }, function (){
        $('form input[name=email]').focus(); 
        $('form input[name=email]').css("background-color"," yellow");       
    });
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Try this:

$(document).ready(function () {
$('#link').hover(function (){
     $("input").blur(); 
 }, function (){
      //mouse leave  
});
});

Working FIddle

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78535

You need to use the in-built blur and focus methods:

$(document).ready(function () {
    $('#link').hover(function (){
        $('form input[name=email]').blur();
    }, function (){
        $('form input[name=email]').focus();
    });
});

Upvotes: 40

Related Questions