jQuery UI multiple selectable tooltips are collapsing - jquery-ui

I'm new to jQuery UI.
I'm trying to create a selectable jQuery UI tooltip. The tooltip is associated with the links on a page.
When the link is surrounded by just text, it works fine. But when there are few links next to each other, the functionality overlaps and tooltips don't show smoothly anymore.
you can find the code on http://jsfiddle.net/zumot/Hc3FK/2/
Below the JavaScript code
$("[title][data-scan]").bind("mouseleave", function (event) {
event.stopImmediatePropagation();
var fixed = setTimeout('$("[title][data-scan]").tooltip("close")', 100);
$(".ui-tooltip").click(function () {
alert("I am clickable");
return false;
});
$(".ui-tooltip").hover(
function () {
clearTimeout(fixed);
},
function () {
$("[title][data-scan]").tooltip("close");
});}).tooltip({
items: "img, [data-scan], [title]",
content: function () {
var element = $(this);
if (element.is("[data-scan]")) {
var text = element.attr("href");
return "<a href='http://www.google.com'>You are trying to open a tooltip <span>" + text + "</span></a>";
}
if (element.is("[title]")) {
return element.attr("title");
}
if (element.is("img")) {
return element.attr("alt");
}
},
position: {
my: "right center",
at: "left center",
delay: 200,
using: function (position, feedback) {
$(this).css(position);
$("<div>")
.addClass(feedback.vertical)
.addClass(feedback.horizontal)
.appendTo(this);
}
}});

My attempt to fix the issue was by making the variable fixed global (to make it accessible by other jQuery UI properties), and on Open event, hide any other previously opened tooltips and clear the timeout id saved in fixed variable.
You can find the solution here http://jsfiddle.net/zumot/dVGWB/
, though to see the code working properly, you'll have to run it directly on your browser.
Here's the snapshort of the fixed code.
// Make the timeout id variable global
var fixed = 0;
$("[title][data-scan]").tooltip({
items: "img, [data-scan], [title]",
content: function () {
var element = $(this);
if (element.is("[data-scan]")) {
var text = element.attr("href");
return "<a href='http://www.google.com'>You are trying to open a tooltip <span>" + text + "</span></a>";
}
if (element.is("[title]")) {
return element.attr("title");
}
if (element.is("img")) {
return element.attr("alt");
}
},
open: function (event, ui) {
// When opening a new div, hide any previously opened tooltips first.
$(".ui-tooltip:not([id=" + ui.tooltip[0].id + "])").hide();
// clear timeout as well if there's any.
if (tf > 0) {
clearTimeout(tf)
};
},
position: {
my: "right center",
at: "left center",
delay: 200,
using: function (position, feedback) {
$(this).css(position);
$("<div>")
.addClass(feedback.vertical)
.addClass(feedback.horizontal)
.appendTo(this);
}
}
}).bind("mouseleave", function (event) {
// stop defeulat behaviour
event.stopImmediatePropagation();
fixed = setTimeout('$("[title][data-scan]").tooltip("close")', 100);
$(".ui-tooltip").hover(
function () {
clearTimeout(tf);
}, function () {
$("[title][data-scan]").tooltip("close");
})
});

Related

How to update a collection on jQuery (drag and) drop

I'm building a Meteor app that let's the user organize lists of items in tags.
I use jQuery draggable and droppable to update a collection when a user drags an item from one tag to another.
I find it hard to understand how/where/when I should call the function. I've tried a few different options (including this "hacky way of doing it". The Blaze documentation mentions that functions can be called on DOM events, but lacks the drag and drop events that I'm looking for. I've currently settled on calling the function under Template.rendered, but that means the item can only be dropped once per render. I've tried to counter this with Tracker.autorun, but I don't think I understand how it works and the item can still only be dropped once per render.
How can I make the .item draggable several times per render?
Template.tag.rendered = function () {
//wait on subscriptions to load
if (Session.get('DATA_LOADED')) {
Tracker.autorun(function () {
$(".item").draggable({
revert: true,
start: function (event, ui) {
var movingItem = Blaze.getData(this)._id;
Session.set('movingItem', movingItem);
},
});
$(".tag").droppable({
hoverClass: 'droppable',
drop: function () {
var movingItem = Session.get('movingItem');
var acceptingTag = Blaze.getData(this)._id;
Items.update(movingItem, {
$set: {"parents": acceptingTag}
});
}
});
});
}
};
I found the solution.
By separating the .draggable and .droppable into two different Template.rendered the function is now correctly called each time an item is moved.
No need for the Tracker.autorun
Template.item.rendered = function () {
if (Session.get('DATA_LOADED')) {
$(".item").draggable({
revert: true,
start: function (event, ui) {
var movingItem = Blaze.getData(this)._id;
Session.set('movingItem', movingItem);
console.log('moving ' + movingItem);
},
});
}
};
Template.tag.rendered = function () {
if (Session.get('DATA_LOADED')) {
$(".tag").droppable({
hoverClass: 'droppable',
drop: function () {
var movingItem = Session.get('movingItem');
var acceptingTag = Blaze.getData(this)._id;
Items.update(movingItem, {
$set: {"parents": acceptingTag}
});
console.log('Dropped on ' + acceptingTag);
}
});
}
};

Angularjs: jquery selectable

i have created a directive to handle selectable provided by Jquery
mydirectives.directive('uiSelectable', function ($parse) {
return {
link: function (scope, element, attrs, ctrl) {
element.selectable({
stop: function (evt, ui) {
var collection = scope.$eval(attrs.docArray)
var selected = element.find('div.parent.ui-selected').map(function () {
var idx = $(this).index();
return { document: collection[idx] }
}).get();
scope.selectedItems = selected;
scope.$apply()
}
});
}
}
});
to use in html
<div class="margin-top-20px" ui-selectable doc-array="documents">
where documents is an array that get returned by server in ajax response.
its working fine i can select multiple items or single item
Issue: i want to clear selection on close button
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview
i can write jquery in controller to remove .ui-selected class but its not recommended approach
can some one guide me whats the best practice to achieve these type of issue
Update:
i fixed the issue by broadcasting event on cancel and listening it on directive
$scope.clearSelection=function() {
$scope.selectedItems = [];
$timeout(function () {
$rootScope.$broadcast('clearselection', '');
}, 100);
}
and in directive
scope.$on('clearselection', function (event, document) {
element.find('.ui-selected').removeClass('ui-selected')
});
is this the right way of doing it or what is the best practice to solve the issue.
http://plnkr.co/edit/3cSef9h7MeYSM0cgYUIX?p=preview

Set Umbraco Property Editor Input to jQueryUI Datepicker

I'm close but still can't quite get this to work.
I have a new custom property editor that is loading correctly and is doing almost everything expected until I try to set the text field to be a jQuery UI element.
As soon as I add a directive in Angular for setting it to call the jQuery UI datepicker function, I get the following error suggesting it hasn't loaded the jQueryUI script library correctly:
TypeError: Object [object Object] has no method 'datepicker'
Trouble is, I can't see where I should be adding it as the logical places (to my mind, at least) seem to make no difference. Here is the code in full:
function MultipleDatePickerController($scope, assetsService) {
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
//assetsService
// .load([
// "http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"
// ])
// .then(function () {
// //this function will execute when all dependencies have loaded
// });
//load the seperat css for the editor to avoid it blocking our js loading
assetsService.loadCss("/css/jquery-ui.custom.min.css");
if (!$scope.model.value) {
$scope.model.value = [];
}
//add any fields that there isn't values for
//if ($scope.model.config.min > 0) {
if ($scope.model.value.length > 0) {
for (var i = 0; i < $scope.model.value.length; i++) {
if ((i + 1) > $scope.model.value.length) {
$scope.model.value.push({ value: "" });
}
}
}
$scope.add = function () {
//if ($scope.model.config.max <= 0 || $scope.model.value.length < $scope.model.config.max) {
if ($scope.model.value.length <= 52) {
$scope.model.value.push({ value: "" });
}
};
$scope.remove = function (index) {
var remainder = [];
for (var x = 0; x < $scope.model.value.length; x++) {
if (x !== index) {
remainder.push($scope.model.value[x]);
}
}
$scope.model.value = remainder;
};
}
var datePicker = angular.module("umbraco").controller("AcuIT.MultidateController", MultipleDatePickerController);
datePicker.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(function () {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(date);
});
}
});
});
}
}
});
I faced the same problem when adapting a jQuery Date Range Picker for my Date Range Picker package for Umbraco 7. It's frustrating! The problem (I think) is that Angular's ng-model listens for "input" changes to trigger events and so doesn't pick up on a jQuery triggered event.
The way around it I found was to force the input event of the element you wish to update to fire manually, using jQuery's .trigger() event.
For example, the date picker I was using had this code for when a date was changed:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
}
},
I just adapted it to force an input trigger by adding this.element.trigger('input') to the code block, so it now reads:
updateInputText: function () {
if (this.element.is('input')) {
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
this.element.trigger('input');
}
},
This forces Angular to "see" the change and then ng-model is updated. There may well be a more elegant way (as I'm an Angular newbie), but I know this worked for me.
Got it. This is probably a bit of a hack, but it's simple and effective so it's a win nonetheless.
The assetsService call is the key, where I've put code into the deferred .then statement to call jQueryUI's datepicker on any item that has the "jqdp" CSS class:
//tell the assetsService to load the markdown.editor libs from the markdown editors
//plugin folder
assetsService
.load([
"/App_Plugins/Multidate/jquery-ui.min.js"
])
.then(function () {
//this function will execute when all dependencies have loaded
$('.jqdp').datepicker({ dateFormat: 'dd/mm/yy' });
});
I've then gone and added that class to my view:
<input type="text" jqdatepicker name="item_{{$index}}" ng-model="item.value" class="jqdp" id="dp-{{model.alias}}-{{$index}}" />
Finally, I've added a directive to ensure that dynamically-added items also display a datepicker:
datePicker.directive('jqdatepicker', function () {
return function (scope, element, attrs) {
scope.$watch("jqdatepicker", function () {
try{
$(element).datepicker({ dateFormat: 'dd/mm/yy' });
}
catch(e)
{}
});
};
});
As I said, this is possibly a bit hacky but it achieves the right result and seems like a simple solution.

Showing Tool-tip & Cross-hair on two independent graphs from a single hover event?

Good day,
We are trying to develop a report which contains two charts. Each chart shows different metrics on the same timescale (unix timestamp). The aim is to show the tooltip & cross hair on both charts regardless of which you hover over.
In my head I would like to get the xAxis timestamp (time) from the tooltip hover event on chart A. I would then fetch the associated series on chart B and trigger the tooltip refresh event.
As it stands, it looks like highcharts only accepts points.
I've added a mouseOver/Out event to both charts. This obtains the hoverPoints
plotOptions: {
series: {
point: {
events: {
mouseOver: function () {
$el.trigger('tooltip-open', {"$sourceEl": $el[0], "point": this});
},
mouseOut: function () {
$el.trigger('tooltip-close', {"$sourceEl": $el[0], "point": this});
}
}
}
}
}
// Where $el is the highcharts container
// ..and tool-tip-XXXXX is a custom jQuery event.
My temporary work around is:
$el.bind('tooltip-open', function (e, data) {
var $el = $(this);
if (data.$sourceEl.id == $el.id) {
return;
}
var chart = $el.highcharts();
var points = $(chart.series).map(function () {
return this.points
}).get();
var pointsForTimestamp = $.grep(points, function (p) {
return p.x == data.point.x;
});
$(pointsForTimestamp).each(function () {
this.setState('hover');
});
chart.tooltip.refresh(pointsForTimestamp);
});
$el.bind('tooltip-close', function (e, data) {
var $el = $(this);
if (data.$sourceEl.id == this.id) {
return;
}
var chart = $el.highcharts();
chart.tooltip.hide();
});
var linkGraphs = function ($elA, $elB) {
function isEventHandled(data){
data.count = data.count || 0;
if(data.count > 0){
return true
}else{
data.count++;
return false;
}
}
function bindToOpen($elA, $elB) {
$elA.bind('tooltip-open', function (e, data) {
if(!isEventHandled(data)){
$elB.trigger('tooltip-open', data);
}
});
}
function bindToClose($elA, $elB) {
$elA.bind('tooltip-close', function (e, data) {
if(!isEventHandled(data)){
$elB.trigger('tooltip-close', data);
}
});
}
bindToOpen($elA, $elB);
bindToOpen($elB, $elA);
bindToClose($elA, $elB);
bindToClose($elB, $elA);
};

Sending information to the content script for a context-menu

I've seen many questions regarding context-menu and two-way communication and it appears that I know the answer to my question... "you can't", but I'm going to try anyway.
On each page there is a modal div that is created by a page-mod. This modal is designed to show up when a user hovers over words in text nodes to give a translation of the word. This works perfectly and I don't have any problems with the page-mod.
What I want to do now is allow the user to highlight a selection of text, right click to bring up the context menu where my new menu item will be to "Translate Selection", and then display the selection in the modal div. Here's where the problems begin. I can respond to the context and click events in the content script, which is fine if I didn't have to do a translation. The translation is done by a web service and the content script cannot call a web service because the callbacks don't exist in the context of the content script because it is in a proxy sandbox. That means that all web service calls need to come from main.js (this is how it works in the page-mod). The problem is that the context-menu object in main.js does not have access to the DOM to update the content of the modal div and show it, and it cannot send information to the content script so that the content script can update the DOM and show the modal div. So how do I get the translation to the DOM from the add-on script for the context-menu?
Is what I want to do possible with the SDK, or do I have to undo many hours of work to put my project back into the "old school" way of doing things so I can get the context menu to work correctly?
This is what I have (the page-mod works, need help with the context-menu):
exports.main = function (options, callbacks) {
'use strict';
var myAppMenuItem,
myAppContextMenu,
myAppPanel,
myAppMod,
self = require('self'),
contextMenu = require('context-menu');
myAppMenuItem = require('menuitems').Menuitem();
if (myAppMenuItem.getAttribute('checked') === 'false') {
return;
}
myAppMod = require('page-mod');
myAppMod.PageMod({
include: '*',
contentScriptWhen: 'ready',
contentScriptFile: [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppmod.js')],
contentStyleFile: self.data.url('myAppmod.css'),
onAttach: function (worker) {
worker.port.on(
'translate',
function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
worker.port.emit('translation', { response : response.text, elementId : data.elementId });
}
})
.get();
}
);
}
});
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : data.text
},
onComplete: function (response) {
<what can I do here to send the information to the content script?>
}
})
.get();
}
});
};
Thank you to Wladimir! The following code does what I want it to:
In the main.js for the context-menu:
myAppContextMenu = contextMenu.Item({
label: "Translate Selection",
context: contextMenu.SelectionContext(),
contentScriptFile : [self.data.url('jquery-1.7.2.min.js'), self.data.url('myAppcontextmenu.js')],
onMessage: function (data) {
var text = require('selection').text;
require('request')
.Request({
url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
content: {
appid : 'myappid',
to : data.to,
from : data.from,
text : text
},
onComplete: function (response) {
var index,
tabs = require('sdk/tabs');
for (index = 0; index < workers.length; index += 1) {
if (workers[index].tab === tabs.activeTab) {
workers[index].port.emit('selectionTranslation', { text: text, response : response.text, leftOffset : data.leftOffset, topOffset : data.topOffset });
}
}
}
})
.get();
}
});
and in the content script:
self.on(
'click',
function (node, data) {
'use strict';
var selectedElement = $(node),
messageData =
{
to : 'es',
from : 'en',
topOffset : selectedElement.offset().top + (selectedElement.height() / 2),
leftOffset : selectedElement.offset().left + (selectedElement.width() / 2)
};
self.postMessage(messageData);
}
);
There is a global workers array variable defined in the exports.main function that gets populated by the onAttach function of the page mod as so:
workers.push(worker);
worker.on(
'detach',
function () {
var index = workers.indexOf(worker);
if (index >= 0) {
workers.splice(index, 1);
}
}
);

Resources