Css
There isn't a nice CSS selector that allows us to target a element when an other element is behing hovered.
There is a way, described in this question, but that expects the element to exist after the hover element seen in the DOM. Your current HTML is reversed, so that wont work.
The easiest way, in my opinion, is to use flex-direction
to reverse the DOM element so we can use the 'hack' described in the linked post.
Example:
a:hover ~ .search-text {
width:200px;
}
.search-box {
display: flex;
justify-content: flex-end;
flex-direction: row-reverse;
}
.search-button {
margin-left: 10px;
}
<div class = "search-box">
<a class="search-button" href="#">search</a>
<input class="search-text" type="text" placeholder="type something">
</div>
NB: Since the <input>
is getting larger, the mouse isn't hovering on the element anymore, therefor it will shrink again, letting the mouse back over the element, this causes the weird jumping effect.
jQuery
Of course we can create a jQuery based solution using the mouseover
and mouseleave
events. This way we
- Don't need to change the DOM order
- Prevent the
<input>
jumping by checking on mouseleave
on the <input>
instead off the <a>
Example:
let i = $('.search-text'),
a = $('.search-button');
i.width(150);
a.on('mouseover', function() {
i.width(300);
});
i.on('mouseleave', function() {
i.width(150);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "search-box">
<input class="search-text" type="text" placeholder="type something">
<a class="search-button" href="#">search</a>
</div>