raghavp raghavp - 5 months ago 10
jQuery Question

Bring Search to its original width when click elsewhere in page?



$('#toggle').click(function myFunction(){
$('.morphsearchinput').toggleClass('expanded');
});

.morphsearchinput {
-webkit-transition:width .8s ease;
-moz-transition:width .8s ease;
-ms-transition:width .8s ease;
-o-transition:width .8s ease;
transition:width .8s ease;

min-width:50px; /* min-width as the pixel value */
width:0%; /* width as the % value */
}

.expanded {
width:80% !important; /* !important because min-width is stronger than width */
}

body
{
background-color:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="morphsearch-form">
<input class="morphsearchinput" type="search" placeholder="Search..." id="toggle" onclick=myfunction()/>
<button class="morphsearch-submit" type="button">Search</button>
</form>





What is want to do is bring back the search to its original width (after expanding) when clicked outside input type i.e anywhere on the page .
But i don't know how to achieve that i can you javascript events but then how to define the area . Can anyone suggest something?

Answer

Use click blur events to get it working. I have also removed the inline onClick event, because you're bringing it using jQuery

$('#toggle').on('click blur', function(){
    $('.morphsearchinput').toggleClass('expanded');
});
.morphsearchinput {
    -webkit-transition:width .8s ease;
    -moz-transition:width .8s ease;
    -ms-transition:width .8s ease;
    -o-transition:width .8s ease;
    transition:width .8s ease;    
    
    min-width:50px; /* min-width as the pixel value */
    width:0%; /* width as the % value */
}

.expanded { 
    width:80% !important; /* !important because min-width is stronger than width */
}

body
{
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <form class="morphsearch-form">
			              <input class="morphsearchinput" type="search" placeholder="Search..." id="toggle" />
					      <button class="morphsearch-submit" type="button">Search</button>
				         </form>

Comments