I can't change tooltip bootstrap position with jQuery - javascript

I can't change tooltip bootstrap position with jQuery.
Example on http://jsfiddle.net/2cast8g8/
If I enter a bigger value in text1 my function ck() need to change the position of tooltip.
Also it is possible to change the color of tooltip in red with jQuery?
<input type="text" id="text1" name="title" value="" data-toggle="tooltip" data-placement="top"title="this need to be less">
<input type="text" id="text2" name="title" value="" data-toggle="tooltip" data-placement="bottom"title="bigger ">
 
$('#text1').change(function () {
ck()
});
$('#text2').change(function () {
ck()
});
function ck() {
text1 = document.getElementById("text1").value;
text2 = document.getElementById("text2").value;
if (Number(text1) > Number(text2)) {
$("#text2").attr("data-original-title", "This value need to be bigger than ");
$("#text1").attr("data-placement", "top");
$(function () {
$('#text2').tooltip('hide').tooltip('show');
});
} else {
$("#text2").attr("data-original-title", "bigger");
}
}
$(function () {
$('[data-toggle="tooltip"]').tooltip('show')
})

$('body').tooltip({
placement: function(tip, element) {
//code to calculate the position here, return values: "left", "right", "top", "bottom"
},
selector: '[data-toggle="tooltip"]'
});

The Bootstrap tooltip plugin has a 'placement' option which controls the general position (top,bottom,left,right) of the tooltip, but it calculates the exact position in this function:
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
You could override this function to provide your own logic (perhaps by adding a 'custom' placement type. Note that the plugin applies the position type as a class to the element in addition to setting the css position properties. These classes are removed in the setContent function so you'd have to adjust that function to remove your new custom placement type class. It's likely there are other issues/considerations you'd have to account for as well - this wouldn't be a simple option. But it would be an interesting project and might even be worthy of a pull request :)
An alternative would be to simply move/override the position after the bootstrap plugin was done. There is a 'shown' event made available, but it is only triggered after the css transitions have been applied, so it may not suitable.
An example might be something like this (untested code):
$('#text2').on('shown.bs.tooltip', function () {
var left = $(this).css('left');
$(this).css({
left: left + 50
});
})
You might want to look at the jQueryUI tooltip widget - it has more features for positioning the tooltip (including adding custom offsets). http://api.jqueryui.com/tooltip/#option-position

Related

Accurate drop for draggable element on scaled div

THE PROBLEM
I'm having a minor problem dragging elements onto a scalable div container.
Once the element is actually in the container, the elements drag fine and work the way they are supposed to.
Larger elements that are dragged onto the scalable container don't have too much of an issue.
But when smaller elements are dragged, you can see that the mouse is no longer attached to said element and when it is dropped, it drops a little off where it is supposed to drop.
I'm trying to find a solution that my mouse stays on the element and it drops where it is supposed to drop.
I've solved problems bit by bit and you can see below but this is the last piece of the puzzle that's driving me mad. If anyone has the time to lend a hand, it would be greatly appreciated.
Here is a codepen - click and drag the two blue elements onto the white container to try it out
Codepen
Full Screen View
Short GIF in Action
This wil help making sure that the droppable area works with a scaled container.
$.ui.ddmanager.prepareOffsets = function(t, event) {
var i, j, m = $.ui.ddmanager.droppables[t.options.scope] || [],
type = event ? event.type : null,
list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
droppablesLoop: for (i = 0; i < m.length; i++) {
if (m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0], (t.currentItem || t.element)))) {
continue;
}
for (j = 0; j < list.length; j++) {
if (list[j] === m[i].element[0]) {
m[i].proportions().height = 0;
continue droppablesLoop;
}
}
m[i].visible = m[i].element.css("display") !== "none";
if (!m[i].visible) {
continue;
}
if (type === "mousedown") {
m[i]._activate.call(m[i], event);
}
m[i].offset = m[i].element.offset();
m[i].proportions({
width: m[i].element[0].offsetWidth * percent,
height: m[i].element[0].offsetHeight * percent
});
}
};
Enable the element to be resizable on a scaled container
function resizeFix(event, ui) {
var changeWidth = ui.size.width - ui.originalSize.width,
newWidth = ui.originalSize.width + changeWidth / percent,
changeHeight = ui.size.height - ui.originalSize.height,
newHeight = ui.originalSize.height + changeHeight / percent;
ui.size.width = newWidth;
ui.size.height = newHeight;
}
Makes it so drag works on a scaled container
function dragFix(event, ui) {
var containmentArea = $("#documentPage_"+ui.helper.parent().parent().attr('id').replace(/^(\w+)_/, "")),
contWidth = containmentArea.width(), contHeight = containmentArea.height();
ui.position.left = Math.max(0, Math.min(ui.position.left / percent , contWidth - ui.helper.width()));
ui.position.top = Math.max(0, Math.min(ui.position.top / percent, contHeight- ui.helper.height()));
}
Creating a draggable element that I can drag onto the box.
.directive('draggableTypes', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
element.draggable({
zIndex:3000,
appendTo: 'body',
helper: function(e, ui){
var formBox = angular.element($("#formBox"));
percent = formBox.width() / scope.templateData.pdf_width;
if(element.attr('id') == 'textbox_item')
return $('<div class="text" style="text-align:left;font-size:14px;width:200px;height:20px;line-height:20px;">New Text Box.</div>').css({ 'transform': 'scale(' + percent + ')', '-moz-transform': 'scale(' + percent + ')', '-webkit-transform': 'scale(' + percent + ')', '-ms-transform': 'scale(' + percent + ')'});
if(element.attr('id') == 'sm_textbox_item')
return $('<div class="text" style="text-align:left;font-size:14px;width:5px;height:5px;line-height:20px;"></div>').css({ 'transform': 'scale(' + percent + ')', '-moz-transform': 'scale(' + percent + ')', '-webkit-transform': 'scale(' + percent + ')', '-ms-transform': 'scale(' + percent + ')'});
}
});
}
};
})
Create draggable/resizable elements that may already be in the box and applying the drag/resize fix to these
.directive('textboxDraggable', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
element.draggable({
cursor: "move",
drag: dragFix,
start: function(event, ui) {
var activeId = element.attr('id');
scope.activeElement.id = activeId;
scope.activeElement.name = scope.templateItems[activeId].info.name;
scope.$apply();
}
});
element.resizable({
minWidth: 25,
minHeight: 25,
resize: resizeFix,
stop: function( event, ui ) {
var activeId = element.attr('id');
scope.activeElement.duplicateName = false;
scope.activeElement.id = activeId;
scope.activeElement.name = scope.templateItems[activeId].info.name;
scope.templateItems[activeId]['style']['width'] = element.css('width');
scope.templateItems[activeId]['style']['height'] = element.css('height');
scope.$apply();
}
})
}
};
})
What happens when an item is dropped
.directive('droppable', function($compile) {
return {
restrict: 'A',
link: function(scope,element,attrs){
element.droppable({
drop:function(event,ui) {
var draggable = angular.element(ui.draggable),
draggable_parent = draggable.parent().parent(),
drag_type = draggable.attr('id'),
documentBg = element,
x = ui.offset.left,
y = ui.offset.top,
element_top = (y - documentBg.offset().top - draggable.height() * (percent - 1) / 2) / percent,
element_left = (x - documentBg.offset().left - draggable.width() * (percent - 1) / 2) / percent,
timestamp = new Date().getTime();
//just get the document page of where the mouse is if its a new element
if(draggable_parent.attr('id') == 'template_builder_box_container' || draggable_parent.attr('id') == 'template_builder_container')
var documentPage = documentBg.parent().parent().attr('id').replace(/^(\w+)_/, "");
//if you are dragging an element that was already on the page, get parent of draggable and not parent of where mouse is
else var documentPage = draggable_parent.parent().parent().attr('id').replace(/^(\w+)_/, "");
if(drag_type == "textbox_item")
{
scope.activeElement.id = scope.templateItems.push({
info: {'page': documentPage,'name': 'textbox_'+timestamp, 'type': 'text'},
style: {'text-align':'left','font-size':'14px','top':element_top+'px','left':element_left+'px', 'width':'200px', 'height':'20px'}
}) - 1;
scope.activeElement.name = 'textbox_'+timestamp;
}
else if(drag_type == "sm_textbox_item")
{
scope.activeElement.id = scope.templateItems.push({
info: {'page': documentPage,'name': '', 'type': 'text'},
style: {'text-align':'left','font-size':'14px','top':element_top+'px','left':element_left+'px', 'width':'5px', 'height':'5px'}
}) - 1;
scope.activeElement.name = 'textbox_'+timestamp;
}
else {
scope.templateItems[scope.activeElement.id]['style']['top'] = draggable.css('top');
scope.templateItems[scope.activeElement.id]['style']['left'] = draggable.css('left');
}
scope.$apply();
}
});
}
};
})
last but not least, my controller
.controller('testing', function($scope, $rootScope, $state, $stateParams) {
$scope.templateItems = [];
$scope.activeElement = { id: undefined, name: undefined };
$scope.templateData = {"id":"12345", "max_pages":1,"pdf_width":385,"pdf_height":800};
$scope.clickElement = function(index) { $scope.activeElement = { id: index, name: $scope.templateItems[index].info.name } }
});
Here is the basis of my html
<div id="formBox" ng-style="formbox(templateData.pdf_width)" zoom>
<div class="trimSpace" ng-style="trimSpace(templateData.pdf_width)" zoom>
<div id="formScale" ng-style="formScale(templateData.pdf_width)" zoom>
<form action="#" id="{{ templateData.id }}_form">
<div ng-repeat="key in [] | range:templateData.max_pages">
<div class="formContainer" id="{{ templateData.id + '_' + (key+1) }}" ng-style="{width: templateData.pdf_width+'px', height: templateData.pdf_height+'px'}">
<div class="formContent">
<div class="formBackground" id="documentPage_{{ (key+1) }}" droppable>
<div ng-hide="preview" ng-repeat="item in templateItems">
<div ng-if="item.info.page == (key+1) && item.info.type == 'text'" id="{{ $index }}" data-type="{{ item.info.type }}" ng-click="clickElement($index)" class="text" ng-style="item.style" textbox-draggable>{{ item.info.name }}</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
For the cursor position while dragging, see this answer : Make Cursor position in center for ui.helper in jquery-ui draggable method
Basically, you can control the cursor position of the instance, allowing to have something more dynamic that cursorAt. Like this:
start: function(event, ui){
$(this).draggable('instance').offset.click = {
left: Math.floor(ui.helper.width() / 2),
top: Math.floor(ui.helper.height() / 2)
}
},
Then on the drop, you need to take into account the transform, but you can simplify by using the helper coordinates instead of the draggable. Like this:
element_top = (ui.helper.offset().top / percent) - (documentBg.offset().top / percent);
element_left = (ui.helper.offset().left / percent) - (documentBg.offset().left / percent);
Result: https://codepen.io/anon/pen/jamLBq
It looks like what is causing this to look strange is the following:
First, the small div is styled as display: block. This means that even though it looks like the div is small, that element actually stretches out to it's whole container.
Second, once you show the dragged square on the left screen, the relation between the mouse cursor and the element whole is technically centered, but you are cutting the size of the original element to a smaller one, and when the width and height get diminished, the result is rendered with the new width and height starting from the upper left corner of the original div. (If you style the small button to be display: inline, you can see what I mean. Try grabbing it from the upper left corner and the try the lower right one. You will see that the former looks fine but the latter is off).
So my suggestions are:
Make the draggabble elements display: inline
Make the dragged element on the left screen the exact height and width of the original element on the right screen.
Hope that helps!
I've forked your codepen and played around with it.
Take a look at it HERE, and see if it helps you find the "bug".
For your draggable script, I changed the code to this, adding margin-left and margin-right:
if(element.attr('id') == 'sm_textbox_item') { /* the small draggable box */
var el = {
pos: element.offset(), // position of the small box
height: element.outerHeight() + 20,
left: 0
}
var deduct = $('#formBox').innerWidth() - 20; // width of the element that's left of small box's container
el.left = el.pos.left - deduct;
return $('<div class="text" style="text-align:left; font-size:14px; width:5px; height:5px; line-height:20px;"></div>')
.css({
'margin-left': el.left + 'px',
'margin-top': el.pos.top - el.height + 'px',
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
});
}
Then, for your droppable script, I changed the formula for element_top and element_left:
// old formula
element_top = (y - documentBg.offset().top - draggable.height() * (percent - 1) / 2) / percent
element_left = (x - documentBg.offset().left - draggable.width() * (percent - 1) / 2) / percent
// new formula
element_top = (y - documentBg.offset().top) / (percent * 0.915)
element_left = (x - documentBg.offset().left) / (percent * 0.915)
It gives an "almost" accurate result, but you may be able to tweak it further to polish it. Hope this helps.
For attaching elements with cursor during dragging you just need to use
cursorAt: { top: 6, left: -100 }
And a little change in top and left parameters of "sm_textbox_item".
top: (y - documentBg.offset().top) / (percent) + "px",
left: (x - documentBg.offset().left) / (percent) + "px",
For the large box again some tweak in top and left element is required (pen updated).
top: element_top-3,
left: element_left+6.49,
I forked your pen and did some changes. I know that this is not a perfect solution, i am also trying to solve this bit by bit. You can check it here
#ITWitch is right, there have to be some bug in draggable().
Style margin: 0 auto; in #sm_textbox_item is the source of problem.
Try to add this to draggable options in your draggableType directive to correct the position:
cursorAt: {left: -parseInt(window.getComputedStyle(element[0],null,null)['margin-left'])},
This problem occurs when you add a transform to a element's style, then make it draggable. You'll have to make do without transform to have a perfect result. I spent 2 days debugging till I found it out, and I didn't want someone else to go through that pain.

jQuery animated fade out flickers before the callback is executed (chrome)

I made a little function that allows to click on a text element which then flys (animated top/left offset with absolute position) to a specific location and disappears.
Here is a fiddle of the problem.
Here is my code from the click handler (in coffescript):
var hoveringSelection = $ "<div class='flying cm-variable'>#{selection}</div>"
var dropdownToggle = $ '#watchlist-dropdown'
hoveringSelection.css({
position: 'absolute'
top: window.mouse.y
left: window.mouse.x
display: 'block'
opacity: 1
})
.appendTo('body')
.animate({
top: dropdownToggle.offset().top
left: dropdownToggle.offset().left
opacity: 0.0
},
{
duration: 1500
easing: 'easeOutCubic'
complete: () ->
hoveringSelection.remove()
updateQueueSize()
}
as you can see it should be at opacity 0 and then removed. The problem is that it shows for a split second (with a ~50% chance) before it gets removed.
I tested it with alerts before the .remove() is called so that the javascript execution halts, but it still did it before the alert was executed. Therefore the issue has to appear right before the completion callback of animate() is called.
I could not observe such behaviour in Firefox.
How can I avoid it?
I have seen that this is a bug (http://www.brycecorkins.com/blog/jquery-fadein-opacity-bug-in-chrome-and-ie-8/). The problem is the opacity. I made a few changes to your script to get your goal. At the end of animation I set opacity to 0.01 and then on complete I execute function that remove the element. I hope that this help you.
http://jsfiddle.net/XjesX/1/
$(function () {
$.extend($.easing, {
easeOutCubic: function (x, t, b, c, d) {
return c * ((t = t / d - 1) * t * t + 1) + b;
}
});
var mouseListener = function (event) {
if (!window.mouse) window.mouse = {
x: 0,
y: 0
};
window.mouse.x = event.clientX || event.pageX;
window.mouse.y = event.clientY || event.pageY;
};
document.addEventListener('mousemove', mouseListener, false);
var fly = function() {
var hoveringSelection = $("<div class='flying'>A word</div>");
var dropdownToggle = $('#flytome');
hoveringSelection.css({
position: 'absolute',
top: window.mouse.y,
left: window.mouse.x,
display: 'block',
opacity: 1.0
})
.appendTo('body')
.animate({
top: dropdownToggle.offset().top,
left: dropdownToggle.offset().left,
opacity: 0.01
}, 1500, 'easeOutCubic' ,function(){
alert($('.flying').length);
$('.flying').remove();
alert($('.flying').length);
});
};
$('#flyBtn').click(fly);
});
I have added alert($('.flying').length); before and after remove to show that that element is removed from the DOM. If you remove that 2 lines you'll see in a better way that there is no flickering effect.

Positioning an element relative to another

I'm making a plugin that makes a dropdown on an element and use a pre-defined element as the dropdown menu outside the applied element.
The markup looks like this
Click
<ul id="dropdown-element">
<li>First item</li>
<li>Second item</li>
</ul>
And using $("#some-menu").dropdown({ placement: 'top' }); will turn #dropdown-element to a dropdown. All good and dandy.
placement decides on how the dropdown is positioned according to the element (top, bottom, right, left) but this should be fairly easy to apply, when I have figured the default positioning out.
I tried using this code from Bootstrap's Tooltip plugin
pos = getPosition($element, inside);
actualWidth = $this[0].offsetWidth;
actualHeight = $this[0].offsetHeight;
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'top':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
break;
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
break;
}
But without luck.
This is what it looks like
And this is the wanted result
I want it horizontally centered to #some-menu and the dropdown to be applied to any element, inlines too and keep both the vertical and horizontal positioning.
Edit:
I found out that the dropdown was created inside a element with position: relative, which is why its offset is wrong. My question is now what the best way to move the element into the body (or perhaps a better solution for this) and keep good performance without touching the DOM more than needed.
This should put the menu in the center.
top = $('#some-menu').offset().top + 8; //Set the vertical position.
left = $('#some-menu').offset().left - $('#dropdown-element').outerWidth/2 + $('#some-menu').outerWidth/2; //Set the menu to the center of the button.
$('#dropdown-element').offset({top: top, left: left});

JS rubber band effect, anybody?

Given a div "square"
and given I already have a touchmove function on that div and I can detect the position X in real time:
how can I implement the rubber band effect?
I mean: tap and drag to the left until the resistance reach the limit and if ou release the finger the square div goes back to its initial position with an easing animation
there is a simple math for that? or a plugin?
UPDATE
w/o jquery would be better if possible
Store its original position somewhere.
Then on the dragend event:
$(this).animate({
top: original_top,
left: original_left
}, 'slow');
Demo: http://jsfiddle.net/maniator/T8zYt/
Full code (with jQuery draggable):
(function($) {
$.fn.rubber = function(resist) {
var self = this,
position = $(this).position(),
selfPos = {
top: position.top,
left: position.left,
maxTop: resist + position.top,
maxLeft: resist + position.left,
minTop: resist - position.top,
minLeft: resist - position.left
};
self.draggable({
drag: function() {
var position = $(this).position(), width = $(this).width(), height = $(this).height();
if (position.left > selfPos.maxLeft || (position.left - width) < selfPos.minLeft || position.top > selfPos.maxTop || (position.top - height) < selfPos.minTop) {
return false;
}
},
stop: function() {
$(this).animate({
top: selfPos.top,
left: selfPos.left
}, 'slow');
}
})
};
})(jQuery)
$('selector').rubber(10);​

Creating a dynamic jquery tooltip

I make a jquery tooltip but have problem with it, when mouse enter on linke "ToolTip" box tooltip don't show in next to link "ToolTip" it show in above linke "ToolTip" , how can set it?
Demo: http://jsfiddle.net/uUwuD/1/
function setOffset(ele, e) {
$(ele).prev().css({
right: ($(window).width() - e.pageX) + 10,
top: ($(window).height() - e.pageY),
opacity: 1
}).show();
}
function tool_tip() {
$('.tool_tip .tooltip_hover').mouseenter(function (e) {
setOffset(this, e);
}).mousemove(function (e) {
setOffset(this, e);
}).mouseout(function () {
$(this).prev().fadeOut();
});
}
tool_tip();
Something like this works, you've still got a bug where the tooltip sometimes fades away on the hover of a new anchor. I'll leave you to fix that, or for another question.
function setOffset(ele, e) {
var tooltip = $(ele).prev();
var element = $(ele);
tooltip.css({
left: element.offset().left - element.width() - tooltip.width(),
top: element.offset().top - tooltip.height(),
opacity: 1
}).show();
}
And here's the jsFiddle for it: http://jsfiddle.net/uUwuD/4/
you need to calculate the window width and minus it with the width of your tooltip and offset
if(winwidth - (offset *2) >= tooltipwidth + e.pageX){
leftpos = e.pageX+offset;
} else{
leftpos = winwidth-tooltipwidth-offset;
}
if you want more detail please refer :)

Categories

Resources