I have an odd issue when using jQuery UI to position a div. Calling the function the first time places the div in the expected location. Subsequent calls place the div further and further to the right and bottom of the window. Below is the least amount of code I could reproduce the problem with.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Position Test </title>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<style type="text/css">
#header {
height: 100px;
background: orange;
}
#content {
height: 300px;
background: blue;
}
#message {
width: 300px;
background: yellow;
position: absolute;
display: none;
}
</style>
</head>
<body>
<div id="header"></div>
<div id="message">a message to the user</div>
<div id="content">
<input id="ShowMessageButton" type="button" value="Show Message" />
</div>
<script>
$(document).ready(function () {
$('#ShowMessageButton').bind("click", function () {
$('#message').position({ my: "center top", at: "center bottom-12", of: "#header" });
$('#message').fadeIn(800).delay(1000).fadeOut(1000);
});
});
</script>
</body>
</html>
If you run the code the first time you get this, which is what I expected.
Screen Shot 1 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen1.png
After the second call
Screen Shot 2 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen2.png
After the third call
Screen Shot 3 http://www.michaelware.net/OutsideImages/jQueryPositionIssue/Screen3.png
Please note you have to let the fadein/fadeout finish or the problem will not occur.
Two things. First .bind()
has been deprecated in favor of .on()
. Second, you need to change the order of your calls to:
$('#ShowMessageButton').on("click", function () {
$('#message').fadeIn(800).position({
my: "center top",
at: "center bottom-12",
of: "#header"
}).delay(1000).fadeOut(1000);
});
jsFiddle example
As the docs for position state, "Note: jQuery UI does not support positioning hidden elements". Since you are trying to use position on a hidden element, you need to make it visible first. You can witness this if you don't totally fade the element out in this example using the format of your original code.
Try This -
$('#message').position({ my: "center top", at: "center bottom-12", of: "#header" });
$('#ShowMessageButton').bind("click", function () {
$('#message').fadeIn(800).delay(1000).fadeOut(1000);
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With