jQuery Popup Bubble/Tooltip [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm trying to make a "bubble" that can popup when the onmouseover event is fired and will stay open as long as the mouse is over the item that threw the onmouseover event OR if the mouse is moved into the bubble. My bubble will need to have all manners of HTML and styling including hyperlinks, images, etc.
I've basically accomplished this by writing about 200 lines of ugly JavaScript but I would really like to find a jQuery plugin or some other way to clean this up a bit.

Qtip is the best one I've seen. It's MIT licensed, beautiful, has all the configuration you need.
My favorite lightweight option is tipsy. Also MIT licensed. It inspired Bootstrap's tooltip plugin.

This can be done easily with the mouseover event as well. I've done it and it doesn't take 200 lines at all. Start with triggering the event, then use a function that will create the tooltip.
$('span.clickme').mouseover(function(event) {
createTooltip(event);
}).mouseout(function(){
// create a hidefunction on the callback if you want
//hideTooltip();
});
function createTooltip(event){
$('<div class="tooltip">test</div>').appendTo('body');
positionTooltip(event);
};
Then you create a function that position the tooltip with the offset position of the DOM-element that triggered the mouseover event, this is doable with css.
function positionTooltip(event){
var tPosX = event.pageX - 10;
var tPosY = event.pageY - 100;
$('div.tooltip').css({'position': 'absolute', 'top': tPosY, 'left': tPosX});
};

Although qTip (the accepted answer) is good, I started using it, and it lacked some features I needed.
I then stumbled upon PoshyTip - it is very flexible, and really easy to use. (And I could do what I needed)

Ok, after some work I'm able to get a "bubble" to pop up and go away at all the right times. There is a LOT of styling that needs to happen still but this is basically the code i used.
<script type="text/javascript">
//--indicates the mouse is currently over a div
var onDiv = false;
//--indicates the mouse is currently over a link
var onLink = false;
//--indicates that the bubble currently exists
var bubbleExists = false;
//--this is the ID of the timeout that will close the window if the user mouseouts the link
var timeoutID;
function addBubbleMouseovers(mouseoverClass) {
$("."+mouseoverClass).mouseover(function(event) {
if (onDiv || onLink) {
return false;
}
onLink = true;
showBubble.call(this, event);
});
$("." + mouseoverClass).mouseout(function() {
onLink = false;
timeoutID = setTimeout(hideBubble, 150);
});
}
function hideBubble() {
clearTimeout(timeoutID);
//--if the mouse isn't on the div then hide the bubble
if (bubbleExists && !onDiv) {
$("#bubbleID").remove();
bubbleExists = false;
}
}
function showBubble(event) {
if (bubbleExists) {
hideBubble();
}
var tPosX = event.pageX + 15;
var tPosY = event.pageY - 60;
$('<div ID="bubbleID" style="top:' + tPosY + '; left:' + tPosX + '; position: absolute; display: inline; border: 2px; width: 200px; height: 150px; background-color: Red;">TESTING!!!!!!!!!!!!</div>').mouseover(keepBubbleOpen).mouseout(letBubbleClose).appendTo('body');
bubbleExists = true;
}
function keepBubbleOpen() {
onDiv = true;
}
function letBubbleClose() {
onDiv = false;
hideBubble();
}
//--TESTING!!!!!
$("document").ready(function() {
addBubbleMouseovers("temp1");
});
</script>
Here is a snippet of the html that goes with it:
Mouseover this for a terribly ugly red bubble!

I have programmed an useful jQuery Plugin to create easily smart bubble popups with only a line of code in jQuery!
What You can do:
- attach popups to any DOM element!
- mouseover/mouseout events automatically managed!
- set custom popups events!
- create smart shadowed popups! (in IE too!)
- choose popup’s style templates at runtime!
- insert HTML messages inside popups!
- set many options as: distances, velocity, delays, colors…
Popup’s shadows and colorized templates are fully supported by
Internet Explorer 6+, Firefox, Opera 9+, Safari
You can download sources from
http://plugins.jquery.com/project/jqBubblePopup

QTip has bug with jQuery 1.4.2. I had to switch to jQuery Bubble Pop up http://www.vegabit.com/jquery_bubble_popup_v2/#examples and it works great!

Sounds to me you dn't want the mouse over events: you want the jQuery hover() event.
And what you seem to want is a "rich" tooltip, in which case I suggest jQuery tooltip. With the bodyHandler option you can put arbitrary HTML in.

I'm trying to make a "bubble" that can
popup when the onmouseover event is
fired and will stay open as long as
the mouse is over the item that threw
the onmouseover event OR if the mouse
is moved into the bubble. My bubble
will need to have all manners of html
and styling including hyperlinks,
images, etc.
All those events fully managed by this plugin...
http://plugins.jquery.com/project/jqBubblePopup

ColorTip is the most beautiful i've ever seen

The new version 3.0 of the jQuery Bubble Popup plugin supports jQuery v.1.7.2, currently the latest and stable version of the most famous javascript library.
The most interesting feature of the 3.0 version is that You can use together jQuery & Bubble Popup plugin with any other libraries and javascript frameworks like Script.aculo.us, Mootols or Prototype because the plugin is completely encapsulated to prevent incompatibility problems;
jQuery Bubble Popup was tested and supports a lot of known and “unknown” browsers; see the documentation for the complete list.
Like previous versions, jQuery Bubble Popup plugin continues to be released under the MIT license; You are free to use jQuery Bubble Popup in commercial or personal projects as long as the copyright header is left intact.
download the latest version or visit live demos and tutorials at
http://www.maxvergelli.com/jquery-bubble-popup/

Autoresize simple Popup Bubble
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="bubble.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript" src="bubble.js"></script>
</head>
<body>
<br/><br/>
<div class="bubbleInfo">
<div class="bubble" title="Text 1">Set cursor</div>
</div>
<br/><br/><br/><br/>
<div class="bubbleInfo">
<div class="bubble" title="Text 2">Set cursor</div>
</div>
</body>
</html>
bubble.js
$(function () {
var i = 0;
var z=1;
do{
title = $('.bubble:eq('+i+')').attr('title');
if(!title){
z=0;
} else {
$('.bubble:eq('+i+')').after('<table style="opacity: 0; top: -50px; left: -33px; display: none;" id="dpop" class="popup"><tbody><tr><td id="topleft" class="corner"></td><td class="top"></td><td id="topright" class="corner"></td></tr><tr><td class="left"></td><td>'+title+'</td><td class="right"></td></tr><tr><td class="corner" id="bottomleft"></td><td class="bottom"><img src="bubble/bubble-tail.png" height="25px" width="30px" /></td><td id="bottomright" class="corner"></td></tr></tbody></table>');
$('.bubble:eq('+i+')').removeAttr('title');
}
i++;
}while(z>0)
$('.bubbleInfo').each(function () {
var distance = 10;
var time = 250;
var hideDelay = 500;
var hideDelayTimer = null;
var beingShown = false;
var shown = false;
var trigger = $('.bubble', this);
var info = $('.popup', this).css('opacity', 0);
$([trigger.get(0), info.get(0)]).mouseover(function () {
if (hideDelayTimer) clearTimeout(hideDelayTimer);
if (beingShown || shown) {
// don't trigger the animation again
return;
} else {
// reset position of info box
beingShown = true;
info.css({
top: -40,
left: 10,
display: 'block'
}).animate({
top: '-=' + distance + 'px',
opacity: 1
}, time, 'swing', function() {
beingShown = false;
shown = true;
});
}
return false;
}).mouseout(function () {
if (hideDelayTimer) clearTimeout(hideDelayTimer);
hideDelayTimer = setTimeout(function () {
hideDelayTimer = null;
info.animate({
top: '-=' + distance + 'px',
opacity: 0
}, time, 'swing', function () {
shown = false;
info.css('display', 'none');
});
}, hideDelay);
return false;
});
});
});
bubble.css
/* Booble */
.bubbleInfo {
position: relative;
width: 500px;
}
.bubble {
}
.popup {
position: absolute;
display: none;
z-index: 50;
border-collapse: collapse;
font-size: .8em;
}
.popup td.corner {
height: 13px;
width: 15px;
}
.popup td#topleft {
background-image: url(bubble/bubble-1.png);
}
.popup td.top {
background-image: url(bubble/bubble-2.png);
}
.popup td#topright {
background-image: url(bubble/bubble-3.png);
}
.popup td.left {
background-image: url(bubble/bubble-4.png);
}
.popup td.right {
background-image: url(bubble/bubble-5.png);
}
.popup td#bottomleft {
background-image: url(bubble/bubble-6.png);
}
.popup td.bottom {
background-image: url(bubble/bubble-7.png);
text-align: center;
}
.popup td.bottom img {
display: block;
margin: 0 auto;
}
.popup td#bottomright {
background-image: url(bubble/bubble-8.png);
}

Tiptip is also a nice library.

You can use qTip for this; However you'd have to code a little for launching it on mouseover event; And in case you want a default watermark on your text fields, you'd have to use the watermark plugin...
I realized that this leads to lot of repetitive code; So I wrote a plugin on top of qTip that makes it really easy to attach informational popup to form fields. You can check it out here: https://bitbucket.org/gautamtandon/jquery.attachinfo
Hope this helps.

Related

jQuery - have popup box appear on screen regardless of how low they scroll

I'm trying to create a popup box on a list of items that goes very much to the bottom of the browser.
I want the POPUP to be in the center of the page where the user is at regardless of how low they scrolled
i have to use POSITION ABSOLUTE not FIXED
but when i use POSITION ABSOLUTE the popup always appears on top and i know its due to my top: 0
.lightbox-container{
border: solid red 1px;
width: 100px;
height: 40px;
background: yellow;
position: absolute;
top: 0;
}
I want to use something like scrollTop or one of those to get the popup to always stay in the users viewpoint regardless of how low they scrolled
$('a').on('click', function(e){
var lightBox = $('<div class="lightbox-container"> <p>click to remove</p>');
lightBox.appendTo('body');
$('.lightbox-container').on('click', function(e){
$(this).remove();
});
});
here is the fiddle im working on http://jsfiddle.net/2RNAN/1/
I know there are other posts about this but im very new to jquery and cant seem to get it working.
This works working fiddle here
$('a').on('click', function (e) {
e.preventDefault();
var lightBox = $('<div class="lightbox-container"> <p>click to remove</p>');
lightBox.appendTo('body');
$('.lightbox-container').css('top', $(document).scrollTop() + 'px');
$('.lightbox-container').on('click', function (e) {
$(this).remove();
});
});
$(document).on('scroll', function () {
$('.lightbox-container').css('top', $(document).scrollTop() + 'px');
});
Edit: I think its a bit unclean and also unnecessary to center the pop-up box via jQuery. You can easily do this with CSS. Check out my updated JsFiddle: http://jsfiddle.net/kCC8p/9/ Edit End
I set the overflow to hidden on the body and included the pop-up outside the scrollable element. This way the scroll position of the user doesn't matter anymore.
JS
var lightbox = $('.lightbox-container');
$('a').click(function(e) {
e.preventDefault();
lightbox.show();
lightbox.addClass('open');
lightbox.append('<p>Click to remove</p>');
});
lightbox.click(function(e) {
lightbox.removeClass('open');
lightbox.find('p').remove();
$(this).hide();
});
See rest on jFiddle...
I may be a little late but I think this might be closer to what you were after:
Working Example
$(function () {
var lightbox = $('.lightbox-container'),
center = function () {
var T = $(window).height() / 2 - lightbox.height() / 2 + $(window).scrollTop(),
L = $(window).width() / 2 - lightbox.width() / 2;
lightbox.css({
top: T,
left: L
}).click(function () {
$(this).hide();
});
};
$('a').click(function (e) {
e.preventDefault();
lightbox.show().text('Click to remove');
center();
});
$(window).scroll(center);
$(window).resize(center);
});
Note that this method centers the popup and keeps it centered regardless of scrolling or re-sizing.
Are you avoiding the use of position fixed due to IE9 compatibility or some other reason? Using position fixed is probably the simplest answer and then address whatever compatibility issue you're having with specific browsers, such as with this answer for IE9 regarding quirks mode.

How to dynamically display position of a div on hover

Hi i am creating a website in wordpress,where i am using javascript to display a description div on hover a list of elements but my problem is according to screen size the description div must vary its position in order to display the content completely.I am not sure that i expressed my query clearly could anyone suggest me how can i get this.
jQuery:
(function($) {
$(document).ready( function() {
$('#linkcat-4 .xoxo li:nth-child(1)').mouseover(function(e) {
$('#text1').css(
'visibility' , 'visible'
);
$('#linkcat-4 .xoxo li:nth-child(1)').mouseout(function(e) {
$('#text1').css(
'visibility' , 'hidden'
);
});
});
});
})(jQuery);
HTML:
<ul class="xoxo blogroll">
<li>Admirality</li>
<li>Banking</li>
<li>Commercial</li>
<li>Contract</li>
<li>test</li>
<li>Corporate</li>
</ul>
<div class="desc-text" id="text1" style="visibility: hidden;">
<p>We represent protection and indemnity clubs that provide insurance
for many of the ships coming to Guyana. We deal with all the familiar
problems encountered by ships, both contentious and non-contentious,
including arrests arising from accidents and claims for wages and damaged
cargo. We advise masters, obtain surveys, note protests, negotiate
settlements and advise on or deal with stowaways and medical emergencies.
Our admiralty practice is the largest in Guyana.
</p>
</div>
CSS:
.desc-text {
position: absolute;
top: 12%;
left: 50%;
}
#text1 {
visibility:hidden;
background:#f1f1f1;
padding: 15px;
width: 150px;
}
You need to check the window.innerHeight and window.innerWidth properties before setting the top and left of your popup div. Here is a fiddle to get you started.
The important part is inside the .hover() call:
$( function() {
pop = $("#popup");
$(".item").hover( function() {
row = $(this);
pop.html(row.data("extra"))
.css("top", (function(r) {
if(r.offset().top > window.innerHeight - pop.height())
return window.innerHeight - pop.height();
else
return r.offset().top;
})(row))
.css("left", (function(r) {
if(r.offset().left + r.width() > window.innerWidth - pop.width())
return window.innerWidth - pop.width();
else
return r.offset().left + r.width();
})(row))
.show();
}, function() {
pop.hide();
});
});
Basically, .hover() takes two functions, one for mouseover and one for mouseout. On mouseout, I just hide the popup. On mouseover, I fill the popup div with content (here coming from the item's data-extra attribute, but it could come from anywhere) then decide where to put it based on the location of the item and the window bounds.
Hope that helps. Leave a comment if you need more.
Update
So, the short answer is to make your content fit a normal browser window. I have to maximize my browser to be able to see everything in that popup. It seems like important information, too. So maybe it deserves its own page? These are opinions, not facts, so I'll move on to the latest version of the fiddle which you can more easily look at here.
There were changes to make everywhere, in the CSS, HTML, and Javascript, to make this work. Probably the biggest issue is visibility:hidden. There might be a way to get jQuery to work with that, but I just use the default display:none, which is what .show() and .hide() toggle.
New css
#text1
{
display:none;
background:#f1f1f1;
padding: 15px;
width: 150px;
}
And I needed to wrap your ul with a div of id linkcat-4. Now for the new js. The most interesting change is that I realized we need to take the div's padding into account. Since the padding parameter applies to all sides, we actually need to double the padding and add that to our offset from the window bounds:
New javascript
(function($) {
$(document).ready( function() {
var pop = $("#text1");
$('#linkcat-4 .xoxo li:nth-child(1)').hover(function(e) {
var row = $(this);
pop.html(row.data("extra"))
.css("top", (function(r) {
if(r.offset().top > window.innerHeight - pop.height())
return window.innerHeight - pop.height() - parseInt(pop.css("padding"))*2;
else
return r.offset().top;
})(row))
.css("left", (function(r) {
if(r.offset().left + r.width() > window.innerWidth - pop.width())
return window.innerWidth - pop.width() - parseInt(pop.css("padding"))*2;
else
return r.offset().left + r.width();
})(row))
.show();
},
function(e) {
pop.hide();
});
});
})(jQuery);
Let me know if that works.

Background not appearing with customized pseudo-popup

I'm having a problem with the background of a pseudo-popup. I use jQuery (1.7) and this tutorial to create popups in my website. Basically I have two preformatted divs (one semi-opaque to hide the rest of the page and the other - with an image as the background - containing the actual popup, with the CSS already loaded in the page) that aren't displayed and that I show when I need them to display the popup, with additional fillings for the second div (to have different popups).
My problem is that the background of the popup doesn't load, and that I end up with only the semi-opaque background and the content of the popup. However, if disable/enable the CSS background property in the console, the background reappears as it should have in the first place.
This problem has appeared relatively recently not after any modification to the actual popup function, so I don't really know where it might come from. It can't be an issue of the background image not yet loaded since it is already there when the page has loaded.
Relevant pieces of code:
HTML:
<div id='popup_container'></div>
<div id='backgroundPopup'></div>
CSS:
#backgroundPopup{
display:none;
position: fixed;
_position:absolute; /* hack for internet explorer 6*/
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000000;
border: 1px solid #cecece;
z-index: 1;
}
#popup_container{
display: none;
position: fixed;
_position:absolute; /* hack for internet explorer 6*/
height: 526px;
width: 718px;
background: url(http://cdn.mojogroups.com/Layout/popup.png) no-repeat !important;
z-index: 2;
color: #000000;
}
Javascript:
//When initializing the page
$(document).ready(function(){
//[...]
popup = new Popup();
popup.initialize();
}
function Popup(){
var popupStatus = 0;
function togglePopup(){
if(popupStatus == 0){
centerPopup();
loadPopup();
}
else
disablePopup();
}
function loadPopup(){
if(popupStatus == 0){
$('#backgroundPopup').css({
"opacity": "0.7"
});
$('#backgroundPopup').fadeIn("fast");
$('#popup_container').fadeIn("fast");
$('body').scrollTop(0);
$('body').css('overflow', 'hidden');
popupStatus = 1;
}
}
this.disablePopup = function(){
if(popupStatus == 1){
$('#backgroundPopup').fadeOut("fast");
$('#popup_container').fadeOut("fast");
$('#popup_container').empty();
$('body').css('overflow', 'auto');
popupStatus = 0;
}
}
function centerPopup(){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $('#popup_container').height();
var popupWidth = $('#popup_container').width();
$('#popup_container').css({
"position": "absolute",
"top": windowHeight/2 - popupHeight/2,
"left": windowWidth/2 - popupWidth/2
});
$('#backgroundPopup').css({
"height": windowHeight
});
}
this.initialize = function(){
$('#backgroundPopup').click(function(){
popup.disablePopup();
});
$(document).keypress(function(e){
if(e.keyCode==27)
popup.disablePopup();
});
}
this.contacts = function(){
//Fill the popup container...
centerPopup();
loadPopup();
popupDiv.fadeIn('fast');
}
What could it be?
Thanks in advance for your help!
EDIT: the site (early version) can be found here
UPDATE: At some point I thought it was due to the opacity attribute added by the loadPopup() function, so I removed that part of the code; but the bug still appears (although maybe less frequently, but it's hard to be sure since it was transient in the first place).
I know its not the ways to as query in answer but i we cant add images in comments so i m asking here. I have just gone through with your problem, what i m getting is you cann see the below screen shot. Is it correct output or not.

JQuery UI sortable in a scrollable container - scroll position "jumps" when sorting

Please check this almost identical question first: jQuery Sortable List - scroll bar jumps up when sorting
I have exactly the same problem, only that I tried all the suggested solutions there with no luck
Here is the way to reproduce
create a sortable list
have it scrollable
scroll down
reorder items
scroll position "jumps" up
Here is the code (see also in JSFiddle)
Html
<ul id="panel" class="scroll">
<li class="content" style="background-color:red">item1</li>
<li class="content" style="background-color:green">item2</li>
<li class="content" style="background-color:blue">item3</li>
<li class="content" style="background-color:gray">item4</li>
<li class="content" style="background-color:yellow">item5</li>
</ul>​
JavaScript
$(function() {
$("#panel").sortable({
items: ".content",
forcePlaceholderSize: true
}).disableSelection();
$(".content").disableSelection();
});​
CSS
.scroll{
overflow: scroll;
border:1px solid red;
height: 200px;
width: 150px;
}
.content{
height: 50px;
width: 100%;
}
​
Here is the code (in JSFiddle) after trying the notion of the accepted answer (with no luck)
I can try to understand why it happens (list get's "shortened" for a quick second), but all attempts to use placeholders or helpers to avoid it didn't work either. I feel I tried almost any permutation of the "scrollable" options with no luck
Browsers I tried
IE9, Firefox 10.0.1, and Chrome 17
JQuery versions
core 1.7.1, UI v 1.8.17
Am I doing something wrong? Is there a solution? Could it be a bug?
If you modifiy your CSS for the .scroll element by adding:
position:relative;
That should resolve this issue.
Adding overflow-y:scroll to the sortable list even without the height property solved it for me. It only shows a disabled scrollbar, but that's okay.
아래로 스크롤 할때 는 이런식으로 하면 됩니다.
var cY = -1;
var base = 0;
$("").sortable({
sort: function(event, ui) {
var nextCY = event.pageY;
if(cY - nextCY < -10){
if(event.clientY + ui.helper.outerHeight(true) - 20 > document.body.clientHeight) {
base = base === 0 ? event.clientY : base;
var move = event.clientY - base;
var curScrollY = $(document).scrollTop();
$(document).scrollTop(curScrollY + move+3);
base = event.clientY;
}
}
},
// .....
});
Seems like jQuery UI 1.9.2 solved the issue.
If you are unable to change the library, there's a workaround including a simple scroll bar operation. The idea is simple:
Keep the previous scroll position every time you scroll.
Set scroll back to the previous position when you start dragging your element.
Here you go;
var lastScrollPosition = 0; //variables defined in upper scope
var tempScrollPosition = 0;
window.onscroll = function () { // Up to you requirement you may change it to another elemnet e.g $("#YourPanel").onscroll
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function () {
tempScrollPosition = lastScrollPosition; // Scrolls don't change from position a to b. They cover some numbers between a and b during the change to create a smooth sliding visual. That's why we pick the previous scroll position with a timer of 250ms.
}, 250));
lastScrollPosition = $(document).scrollTop(); // Up to you requirement you may change it to another elemnet e.g $("#YourPanel").onscroll
};
$("#YourSortablePanel").sortable({
start: function (event, ui) {
$(document).scrollTop(tempScrollPosition);
}
});
This is caused by the height of the container changing when sorting (just before the placeholder is created)
The problem is well described and answered in this stack overflow : https://stackoverflow.com/a/32477389/2604980
For me this sortable options were working if you don't want to remove overflow css from body:
start(e, ui) {
if (fixOffset) ui.item.css('transform', `translateY(${document.body.scrollTop}px)`);
fixOffset = true;
},
change(e, ui) {
ui.item.css('transform', `translateY(${document.body.scrollTop}px)`);
},
stop(e, ui) {
ui.item.css('transform', 'translateY(0)');
},

How do you listen for a HTML element moving in JavaScript?

I have an HTML element that I need to track another element. Specifically, I need to have the top left and top right corners of both elements be positioned the same. When a window gets resized, the resize event gets triggered and I can adjust the position of the dependent element. However, if the element being tracked is repositioned (but not resized), I do not see any DOM event.
How can we find out if a DOM element has been moved? We are using the latest jQuery.
Here is a code sample.
Note that elementOne and mouseTracking divs are there to show elements that get moved for "some" reason that is outside the control of my code.
This code works for the elementOne case.
MouseTrackingTracker does not track a moving element.
ResizerTracker does not put the border around the complete text in the overflow case.
I would like the trackingDivs to move and resize no matter the reason for the tracked element's reasons for changing.
This code relies on the window resize being the hooked event. Hooking some event that fires when the element changes its dimensions is closer to what I need.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<style type="text/css">
#elementOne { float : right;width : 200px; display:inline-block}
#resizer { float : left; display:inline-block}
.trackedDiv { width:50px; height:50px; background-color: blue }
.trackingDiv { position:absolute; z-index: 1; border:3px green; border-style: solid;}
</style>
<script>
$(function() {
$( window ).bind("resize",function(){
$("#elementOne").trigger("reposition");
$("#mouseTracking").trigger("reposition");
$("#resizer").trigger("reposition");
});
var repositionFunction = function(selfish, element){
var self = $(selfish);
var offset = self.offset();
var selfTop = offset.top;
var selfLeft = offset.left;
var selfWidth = self.width();
var selfHeight = self.height();
$(element).css({
top: selfTop,
left: selfLeft,
width : selfWidth,
height : selfHeight
});
}
$(document).mousemove(function(ev){
$("#mouseTracking").position({
my: "left bottom",
of: ev,
offset: "3 -3",
collision: "fit"
});
});
var timedShort = function() {
$('#resizer').html("Really short").resize();
setTimeout(timedLong, 10000);
}
var timedLong = function() {
$('#resizer').html("Really longggggggggggggggggggggggggggggggggggggggggggggggggggg text").resize();
setTimeout(timedShort, 10000);
}
setTimeout(timedLong, 10000);
$("#elementOne").bind("reposition",
function() { repositionFunction(this, "#elementOneTracker"); });
$("#mouseTracking").bind("reposition",
function() { repositionFunction(this, "#mouseTrackingTracker"); });
$("#resizer").bind("reposition",
function() { repositionFunction(this, "#resizerTracker"); });
});
</script>
</head>
<body>
<div class="trackedDiv" id="mouseTracking">tracks mouse</div>
<div class="trackingDiv" id="mouseTrackingTracker"></div>
<div style="clear:both;"></div>
<div class="trackedDiv" id="resizer">resizer: resizes</div>
<div class="trackingDiv" id="resizerTracker"></div>
<div class="trackedDiv" id="elementOne">elementOne: floats to the right</div>
<div class="trackingDiv" id="elementOneTracker"></div>
</body>
</html>
You can fire custom events with jquery whenever you reposition the element.
$( window ).bind("resize",function(){
$("#elementOne").css({
top: 200,
left: 200
}).trigger("reposition");
});
// and now you can listen to a "reposition event"
$("#elementOne").bind("reposition",function(){
var self = $(this);
$("#elementTwo").css({
top: self.css("top"),
left: self.css("left")
});
});
So you can provide event hooks yourself with some manual coding, which is useful since cool events like DOMAttrModified and so on, are not fully supported in all browsers. The downside, you have to do it all yourself.
Unfortunately, there are no reliable events to tell you when an element moves or is resized. You could resort to polling the element, though that won't necessarily be the most performant solution:
setInterval(repositionElement, 10);
Another option is to make your element "track" the other element purely through CSS. For this to work, you'll need a "wrapper" around the element you're tracking, and the other element:
#wrapper-around-element-to-track
{
position: relative;
}
#tracked-element
{
position: absolute;
/* set top and left to position, if necessary */
}
#tracking-element
{
position: absolute;
/* set top and left to position, if necessary */
}
Since you're already using jQuery, you can also use the resize event plugin to simulate the resize event on any element, but if I recall the last time I looked at it, it simply does the polling like I mentioned.
There is the DOMAttrModified event, but its only impleneted in Firefox and Chrome. But as you need a JavaScript function to start the element moving, you can firing a custom event with Jquery in this place.

Categories