Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - making a floating element stick to another element

I'm using this jQuery form validation plugin. It shows field errors in a small floating div which is great.

The problem arises when the error div is shown and then the element it corresponds to moves out of it's original place. For example if above an input box I .show() an element that was previously hidden, it will push the input down, but the error prompt for that input will stay in place.

How can I make the floating div stick to/follow it's corresponding element?

The code for this plugin is here and examples are here.

like image 749
Chad Avatar asked Nov 04 '22 13:11

Chad


1 Answers

The plugin is using absolute positioning for the error messages.

If you are adding other DOM elements which move the input fields position relative to the document, then you will need to manually reposition all the validation <div>'s after your script that modifies the DOM runs.

You could try using the jQuery offset() method http://api.jquery.com/offset/ to get the new position of the input element relative to the document, and then tweak the validation <div>'s top and left properties accordingly.

Here is a .jsFiddle showing you what I mean: http://jsfiddle.net/ysQCf/2/

css

.errorMessage
{
    background-color: red; 
    position: absolute;
    left: 180px;
    top: 25px;
}

p
{
    display: none;   
}

html

<p id="hidden">if you display this the textbox will move down</p>
<input id="myInput" type="text" />
<div class="errorMessage">stick me to the div</div>
<br />
<input id="show" type="button" value="Show" />

javascript

$(function () {
    $("#show").click(function () {
        // Save the offset of the error against the input
        var offset = $(".errorMessage").offset();
        offset.left -= $("#myInput").offset().left;
        offset.top -= $("#myInput").offset().top;

        // Call your script to manipulate the DOM
        $("#hidden").show(); 

        // Move the error div to it's new position
        offset.left += $("#myInput").offset().left;
        offset.top += $("#myInput").offset().top;
        $(".errorMessage").offset(offset)
    });
});
like image 53
magritte Avatar answered Nov 09 '22 12:11

magritte