Search code examples
javascriptjqueryhtmlsearch-box

How to make better jQuery search box with resize from right to left then mine?


Im trying about same search box like here in top right side of page: Search Box

I have this, but it doesn't work correctly:

$(document).ready(function(){
	$("#search").mouseenter(function(){
		$(this).stop().animate({marginLeft:'-40',width:"181"},300) 
		/*function(){
			$(this).animate({marginLeft:'0',width:"141"},300)
		});*/
	});
	$("#search").mouseleave(function(){
		$(this).animate({marginLeft:'0',width:"141"},300);
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="cs-cz">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<meta name="viewport" content="width=device-width" />
	<link rel="stylesheet" href="index.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script src="script.js" type="text/javascript"></script>
</head>
<body>
	<form id="searchbox" action="">
    <input id="search" type="text" placeholder="Type here">
    <input id="submit" type="submit" value="Search">
</form>
</body>
</html>


Solution

  • Give a float: right or text-align: right:

    $(document).ready(function() {
      $("#search").css({
        marginLeft: 0,
        width: 141
      });
      $("#search").mouseenter(function() {
        $(this).stop().animate({
          marginLeft: '-40',
          width: "181"
        }, 300);
      });
      $("#search").mouseleave(function() {
        $(this).animate({
          marginLeft: 0,
          width: "141"
        }, 300);
      });
    });
    #searchbox {
      text-align: right;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="searchbox" action="">
      <input id="search" type="text" placeholder="Type here">
      <input id="submit" type="submit" value="Search">
    </form>