2

There is a submit button. and a textbox. I would like to hover on button with classname: search ,then toggle class to my textbox. the problem is it is not work when I want to type in my textbox. How can I fix this? Here is my codes:

$(".search").hover(function () {
    $(".searchinput").toggleClass("searchinput2");
 });
.searchinput{width:2%; height:30px; background:yellow; font-size:1.5em;}
.searchinput2{width:50% !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="searchinput"/>
        <button type="submit" class="search">search</button>

1 Answer 1

2

You should use .mouseenter and .mouseleave events.

$(".search").mouseenter(function () {
    $("#searchinput").addClass('searchinput2');
 });
$(".searchinput").mouseleave(function () {
    $("#searchinput").removeClass('searchinput2');
 });
.searchinput{width:2%; height:30px; background:yellow; font-size:1.5em;}
.searchinput2{width:50% !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="searchinput" id="searchinput"/>
        <button type="submit" class="search">search</button>

You can bind .hover() event handler for input element.

$(".searchinput").hover(function () {
    $(".searchinput").toggleClass('searchinput2');
});
.searchinput{width:2%; height:30px; background:yellow; font-size:1.5em;}
.searchinput2{width:50% !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="searchinput"/>
        <button type="submit" class="search">search</button>

Sign up to request clarification or add additional context in comments.

4 Comments

i would like to use this code with hover not click event
Although this solution works. But, I don't understand why it didn't with hover. As the doc says: The .hover() method binds handlers for both mouseenter and mouseleave events.
@Alexandru-IonutMihai Thank you so much.
@Abhi, because hover is applied for button element and that's the reson for appearing this behavior. View updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.