I am trying to get a div to slide to the top of the screen when someone press enter in a input field. The issue I am having is that instead of the div moving 50px from the top of the screen it moves 50px from the top of the div it is in.
Here is the real code:
The HTML
<div class="home-nav">
<div style="display: none;position: absolute;margin-top: -1px" id="search-box">
<form action="/" method="get"><input type="text" name="q" class="q" /></form>
</div>
</div>
The JavaScript
$(".q").keydown(function(e){
if(e.keyCode == 13){
var val = $(this).val();
window.location = "#q="+val;
$(".space").animate({
width: "100px"
}, "slow");
$("#search-box").animate({
top: "50px"
}, "slow");
return false;
}
});
The CSS
div.home-nav{
line-height: 4em;
position: absolute;
top: 0;
bottom: 0;
left: 300px;
height: 300px;
margin: auto;
}
The reason I have the inner div positioned absolute, is because when you click on the link The div/input will cover the link for a little effect.
If you don't want .sub to be positioned relative to .main upon animation, don't put it inside .main in the HTML.
<div class="main"></div>
<div class="sub">
<form>
<input type="text" />
</form>
</div>
try setting the div to fixed if you want it to be placed relative to the top of your screen, rather than the div it's positioned inside.
div.home-nav{
line-height: 4em;
position: fixed;
top: 0;
left: 300px;
height: 300px;
margin: auto;
}
Okay, I got it! What I did, was remove the element from the div and place it in the body when someone presses enter. I then go and do the animation. If anyone has a better way please post!
$(".q").keydown(function(e){
if(e.keyCode == 13){
var val = $(this).val();
var item = $(this).closest("#search-box");
var left = item.offset().left;
var top = item.offset().top;
$(this).closest("#search-box").remove();
item.css({
top: top + "px",
left: left + "px",
zIndex: 100
})
$("body").prepend(item);
window.location = "#q="+val;
$(".space").animate({
width: "100px"
}, "slow");
item.animate({
top: "35px"
}, "slow");
return false;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.