On Clicking Link Highlight the Text Within Tooltip - javascript

I would like to highlight the text within a tooltip when the user clicks the Short Url anchor so he can copy paste it. The tooltip is served by Twitter Bootstrap and the markup looks like this:
<div class="shorturl">
Short URI
</div>
I found this snippet which I think would work just right except that I have not yet figured out how to handle the clicking of the link (which both does not scroll and highlights the text within the tooltip).
function selectText() {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementByClass('tooltip'));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementByClass('tooltip'));
window.getSelection().addRange(range);
}
}
How can I make this work? Input very much appreciated!

This is what I would suggest to you : Live demo (jsfiddle)
var selector = '[rel="tooltip_r"]'; // Links that will have the feature
var tooltipOptions = { // Some options for the tooltips (careful if you override the "defaults" set below)
placement: 'right'
};
var attribute = 'data-url'; // Attribute where to find the url, could be href
/* Be sure of what you are doing if you modify below this */
$elts = $(selector);
var defaultOptions = {
trigger: 'manual',
title: '<input type="text" readonly="readonly"/>'
};
var opts = $.extend({}, defaultOptions, tooltipOptions);
$elts.each(function() {
var $this = $(this);
var url = $this.attr(attribute);
$this.tooltip(opts);
$this.on('click.tooltip',function(e) {
$this.tooltip('show');
$this.data('tooltip').$tip.find('input').val(url).select()
.on('click', function(e){ e.stopPropagation(); });
e.preventDefault();
e.stopPropagation();
});
});
$('html').on('click.tooltip', function() {
$elts.tooltip('hide');
});
And you might use some styles to improve the input in the tooltip. For example :
.tooltip .tooltip-inner > input[type="text"] {
background: transparent;
border: none;
max-width: 100%;
width: auto;
padding: 0;
color: inherit;
}
Update
If you need the same feature in dynamically loaded content, delegated events need to be used. Here is a working jsfiddle.
var selector = '[rel="tooltip_r"]'; // Links that will have the feature
var tooltipOptions = { // Some options for the tooltips (careful if you override the "defaults" set below)
placement: 'right'
};
var attribute = 'data-url'; // Attribute where to find the url, could be href
var onClass = 'on'; // Class used to determine which tooltips are displayed
/* Be sure of what you are doing if you modify below this */
var defaultOptions = {
trigger: 'manual',
title: '<input type="text" readonly="readonly"/>'
};
var opts = $.extend({}, defaultOptions, tooltipOptions);
var selectorOn = selector+'.'+onClass;
$('body').on('click.tooltip', selector, function(e) {
var $this = $(this);
var url = $this.attr(attribute);
$this.data('tooltip') || $this.tooltip(opts);
$this.tooltip('show').addClass(onClass);
$this.data('tooltip').$tip.find('input').val(url).select()
.on('click', function(e){ e.stopPropagation(); });
e.preventDefault();
e.stopPropagation();
})
.on('click.tooltip', function() {
var $elts = $(selectorOn);
$elts.tooltip('hide');
});

Related

CodeMirror - insert text into editor when there are multiple editors

I have two codemirror editors on one page. A drop down list of items and radio group to target the correct editor.
What I want to do is on change of the drop down list insert the value of the item into the targeted editor (deleted by the radio group).
my code is as below: however the function isnt working. When I alert the item value and the target I get expected results, however the function to insert the text is failing:
<script type="text/javascript">
function editor(id) {
var editor = CodeMirror.fromTextArea(id, {
continuousScanning: 500,
lineNumbers: true
});
editor.setSize(null, 550);
}
var config_id = document.getElementById('id_config')
var config = editor(config_id);
var remote_config_id = document.getElementById('id_remote_config')
var remote_config = editor(remote_config_id);
function insertStringInTemplate(str, target) {
if (target== "id_config") {
var doc = config
} else {
var doc = remote_config
}
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}
$(function(){
// bind change event to select
$('#template_vars').on('change', function () {
var var_data = $(this).val(); // get selected value
var var_target = $('input[name=target]:checked').val();
insertStringInTemplate(var_data, var_target)
return false;
});
});
$("#template_vars").chosen({no_results_text: "Oops, nothing found!"});
</script>
however the function to insert the text is failing
That function (i.e. insertStringInTemplate()) is working good/properly; however, the problem is with the editor() function, where you forgot to return the editor (i.e. the CodeMirror instance).
So a simple fix would be:
function editor(id) {
var editor = CodeMirror.fromTextArea(id, {
continuousScanning: 500,
lineNumbers: true
});
editor.setSize(null, 550);
return editor; // <- here's the fix
}
Demo on CodePen.
However in that demo, I added an if block to the insertStringInTemplate() function, as in the following code:
function insertStringInTemplate(str, target) {
if (target== "id_config") {
var doc = config
} else {
var doc = remote_config
}
// If there's a selection, replace the selection.
if ( doc.somethingSelected() ) {
doc.replaceSelection( str );
return;
}
// Otherwise, we insert at the cursor position.
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}

jQuery function does not work on mouseover and click state

Building a new site and trying to reuse a JavaScript from the current site that change image on hover. I have a hard time to understand JavaScript so I hope someone can help me to see what I'm missing or doing wrong.
The current site (where I copied from) has many more script running and I don't know if some other script is missing. I have tried to change the initializing part of the script to fit the new site. Please have a look at the puzzlepiece on the current page. http://www.collyfiltreringsteknik.se.
I have got the script running to a point where it adds the four "quad" divs but the mouseover and click function does not work.
This is the html code
<div id="companyvalues" class="clearfix">
<div class="valueimage"></div>
</div>
The jQuery part
(function($){
$.fn.extend({
companyvalues: function(kwargs) {
var defaults = {
static_base:''
};
var options = $.extend(defaults, kwargs);
return this.each(function() {
var obj = $(this);
var div = $('div', obj);
var topleft = $('<div class="quad topleft" data-image="i0000" data-href="/grundpelare/tillganglighet/"></div>');
var topright = $('<div class="quad topright" data-image="i0003" data-href="/grundpelare/konkurrenskraft/"></div>');
var bottomleft = $('<div class="quad bottomleft" data-image="i0002" data-href="/grundpelare/miljoforbattring/"></div>');
var bottomright = $('<div class="quad bottomright" data-image="i0001" data-href="/grundpelare/kostnadsreducering/"></div>');
obj.prepend(bottomright);
obj.prepend(bottomleft);
obj.prepend(topright);
obj.prepend(topleft);
var divs = $('div.quad', obj);
$([ '/uploads/pages/varden_0000_yellow.png',
'/uploads/pages/varden_0001_red.png',
'/uploads/pages/varden_0002_green.png',
'/uploads/pages/varden_0003_blue.png'
]).preload({base_url:options.static_base});
divs.mouseover(function(event) {
var item = $(this);
var data_image = item.attr('data-image');
div.addClass(data_image);
event.preventDefault();
event.stopPropagation();
});
divs.mouseout(function(event) {
var item = $(this);
div.removeClass('i0000');
div.removeClass('i0001');
div.removeClass('i0002');
div.removeClass('i0003');
event.preventDefault();
event.stopPropagation();
});
divs.click(function(event) {
var item = $(this);
var href = item.attr('data-href')
document.location.href=href;
event.preventDefault();
event.stopPropagation();
});
});
}
});
})(jQuery);
Initializing the script.
$(document).ready(function() {
$('#companyvalues').companyvalues();
});

How to get text value of same class in jquery

I have 10 records in my table. Each record having same class name. How can I alert the table data value(text) using jquery this.value while hover the data text.
Here is my code
<td>email1#domain.com</td>
<td>email2#domain.com</td>
<td>email3#domain.com</td>
<td>email4#domain.com</td>
<td>email5#domain.com</td>
<td>email6#domain.com</td>
<td>email7#domain.com</td>
<td>email8#domain.com</td>
<td>email9#domain.com</td>
<td>email10#domain.com</td>
Here is my script. I'm using webui api for iframe popover. For tables I have used datatables.
(function(){
var settings = {
trigger:'hover',
title:'Send Mail To User',
content:'',
multi:true,
closeable:false,
style:'',
cache:false,
delay:300,
padding:true,
backdrop:false,
};
$('a.show-pop-iframe').on('mouseenter',function () {
alert($(this).text());
settings.url='emailtype.php?id='+$(this).text();
function initPopover(){
var iframeSettings = {
placement:'auto', //values: auto,top,right,bottom,left,top-right,top-left,bottom-right,bottom-left,auto-top,auto-right,auto-bottom,auto-left,horizontal,vertical
container: document.body, // The container in which the popover will be added (i.e. The parent scrolling area). May be a jquery object, a selector string or a HTML element. See https://jsfiddle.net/1x21rj9e/1/
width:'auto', //can be set with number
height:'auto', //can be set with number
closeable:true,
padding:false,
type:'iframe',
url:settings.url
};
$('a.show-pop-iframe').webuiPopover('destroy').webuiPopover($.extend({},settings,iframeSettings));
}
initPopover();
});
})();
If you have class 'hover-cust' then
$('.hover-cust').on("mouseenter", function() {
alert($(this).text());
});
If you want to alert on td then
$('td').on("mouseenter", function() {
var link = $(this).find(".hover-cust");
if(link && link.length > 0) {
alert($(link).text());
}
});
$(".hover-cust").hover(function(){
alert($(this).text());
});
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>email1#domain.com</td>
<td>email2#domain.com</td>
<td>email3#domain.com</td>
<td>email4#domain.com</td>
<td>email5#domain.com</td>
<td>email6#domain.com</td>
<td>email7#domain.com</td>
<td>email8#domain.com</td>
<td>email9#domain.com</td>
<td>email10#domain.com</td>
</tr>
</table>
Adding many event listeners on a group of similar nodes is considered a bad practice.
const table = document.querySelector('#your_table_id');
table.addEventListener('mouseover', function(event) {
const target = event.target;
const tag = target.tagName;
const parentTag = target.parentNode.tagName;
if(tag !== 'a' || parentTag !== 'td') {
return; // not my target, leave the function
}
alert(target.textContent);
});

jQuery events not firing

I'm creating a simple jQuery editor, nothing complicated, and just can't seem to find out why the events do not work. See code below.
var $editor = $('<div>').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
var $b = $('<div>').addClass('button-wrapper')
.appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '')return true;
//Generate a button.
$('<div>').data('buttonName', button)
.addClass(button.toLowerCase())
.click(clicked)
.hover(hover, hover)
.appendTo($b);
});
To go over it, simply, $element represents the textarea that I am using as the base element, $b represents the button wrapper, and $editor is the div to wrap around all of these things. When I append the buttons to $editor none of the events fire, however, when I append to document.body it works perfectly fine. For the record, the event clicked and hover are nothing special, just testers to see if the events are working.
I guess the issue is actually at all places you are using <div> but it should be just div
like below -
var $editor = $('div').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
I've rewritten your code a little bit, just to figure out what you're doing. This seems to work for me, unless I didn't understand what the problem is that you're describing. The buttons react to hover as well as click events. Aside from writing the things you're doing differently, there's no substantial change in the code.
I suppose there's a chance that Val was right in that there may be other elements overlaying your buttons. You haven't shown us your CSS, so it's hard to tell what's going on on your side.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.bold, .italic, .underline{ width: 50px; height: 20px; background: green; margin: 10px; }
</style>
</head>
<body>
<textarea class="demo">
</textarea>
<script type="text/javascript">
jQuery(
function($)
{
(function($){
//Constructor to make a new editor.
function TEditor(element, opts)
{
//Load in the element.
this.$element = $(element);
this.opts = opts;
//Let the browser know the object is ready.
this.enabled = true;
}
//The actual editor class.
TEditor.prototype = {
display: function()
{
var
$editor = this.$element.wrap('<div class="editor" />').parent(),
$b = $('<div class="button-wrapper" />').appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '') return true;
//Generate a button.
$('<div class="' + button.toLowerCase() + '" />')
.data('buttonName', button)
.appendTo($b)
.click(clicked)
.hover(hover, hover);
});
},
enable: function()
{
this.enabled = true;
},
disable: function()
{
this.enabled = false;
},
validate: function()
{
if(!this.$element[0].parentNode)
{
this.destroy();
this.$element = null;
this.options = null;
}
}
}
//JQuery function extension.
$.fn.teditor = function(options)
{
options = $.extend({}, $.fn.teditor.defaults, options);
//On load create a new editor.
function get(ele)
{
var editor = $.data(ele, 'editor');
if(!editor)
{
editor = new TEditor(ele, options);
editor.display();
$.data(ele, 'editor', editor);
}
return editor;
}
//Initialize.
this.each(function(){get(this);})
return this;
};
$.fn.teditor.defaults = {
buttons: 'Bold Italic Underline',
height: '150px',
width: '500px'
};
function clicked(e)
{
alert(e);
}
function hover(e)
{
console.log('hover');
}
})(jQuery);
$('.demo').teditor();
}
);
</script>
</body>
</html>

Open Select using Javascript/jQuery?

Is there a way to open a select box using Javascript (and jQuery)?
<select style="width:150px;">
<option value="1">1</option>
<option value="2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc arcu nunc, rhoncus ac dignissim at, rhoncus ac tellus.</option>
<option value="3">3</option>
</select>
I have to open my select, cause of IE bug. All versions of IE (6,7,8) cut my options.
As far as I know, there is no CSS bugfix for this.
At the moment I try to do the following:
var original_width = 0;
var selected_val = false;
if (jQuery.browser.msie) {
$('select').click(function(){
if (selected_val == false){
if(original_width == 0)
original_width = $(this).width();
$(this).css({
'position' : 'absolute',
'width' : 'auto'
});
}else{
$(this).css({
'position' : 'relative',
'width' : original_width
});
selected_val = false;
}
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').change(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select option').click(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
selected_val = true;
});
}
But clicking on my select the first time will change the width of the select but I have to click again to open it.
I know this is pretty old and answered, but this worked for me in Safari and iOS UIWebView - I have it hidden, but want it to show and open when a different button is clicked.
$('#select-id').show().focus().click();
Try this:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
and this to close:
//close dropdown
myDropDown.attr('size',0);
Instead of using click, you could use the mousedown handler to capture the mousedown event.
mousedown fires before click, so you could call stopPropogation to break the event queue.
Try this:
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
Then call the function:
dropDown('elementId');
NO jQuery solution.
<SCRIPT>
function toggleDropdown(element){
if(element.size == 0) {
element.size = element.length;
element.focus();
}
else element.size = 0;
}
</SCRIPT>
Found this here.
First of all, I feel the pain of this limitation in IE - bleh!
Just thought I'd also share this as it seems to be working for me. I've taken almost the same approach, but on a per select element. In my case I know which lists could have long data.
Instead of making the select elements absolute, I've kept them inline and wrap them in a DIV with a hidden overflow as appearance needed to be consistent, also it only applies this 'hack' if it is IE and the expanded width is greater than the current width.
To use this for all select boxes you could use something like:
$("select").each(function(){
$(this).IELongDropDown();
});
Or obviously on a per element bases by id.
Here's the jquery plugin:
(function($) {
$.fn.IELongDropDown = function(cln) {
if (jQuery.browser.msie) { //only IE has problems with long select boxes
var el = this;
var previousWidth = el.width();
var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:"+ previousWidth +"px'></div>";
el.wrap(divWrapper);
var newWidth = el.width("auto").width();
el.width(previousWidth);
if(newWidth > previousWidth) {
el.bind("mousedown", function(){ return el.width("auto").focus(); });
el.bind("blur", function(){ return el.width(previousWidth); });
el.bind("change", function(){ return el.width(previousWidth); });
}
}
return this;
};
})(jQuery);
Hope this helps someone
I think that you need to return true from your event handlers (click, blur, etc.) so after your handler executes, the browser continues to propagate the event and open the select.
It is similar with href links, if they have an onclick handler and the handler returns false, the link is not followed (the browser stops the event after your handler executes).
EDIT: Based on your comment and answer, it seems that your handler gets the first chance to execute only after the browser decides to open the box.
I suggest that you try the focus event handler, it might get a chance to run earlier than the click handler and perhaps before the browser actually opens the box. It is also more consistent (applies both to mouse and keyboard navigation).
I prefer to set my CSS in a CSS file and then "addClass" but even so, your code (portion)
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
seems to be a duplicate
I would make it:
$('select').blur().css({
'position' : 'relative',
'width' : original_width
});
Not sure you really even need the .blur() here what with the .change() event (try taking it out see see if that addresses your issue...I use select often on IE and do not seem to have an issue.
Okay, I found another way fixing this problem.
Here is the fix:
Please give me feedback! I'm kind of proud on myself ;)
$(document).ready(function() {
if (jQuery.browser.msie) {
select_init();
}
});
function select_init () {
var selects = $('select');
for (var i = 0; i < selects.length; i++) {
_resizeselect.init(selects[i]);
}
}
var _resizeselect = {
obj : new Array(),
init : function (el) {
this.obj[el] = new resizeselect (el);
}
}
function resizeselect (el) {
this.el = el;
this.p = el.parentNode;
this.ht = el.parentNode.offsetHeight;
var obj = this;
this.set = false;
el.onmousedown = function () {
obj.set_select("mousedown");
}
el.onblur = function () {
obj.reset_select("blur");
}
el.onchange = function () {
obj.reset_select("change");
}
}
resizeselect.prototype.set_select = function (str) {
if (this.set) {
this.set = false;
return;
}
this.el.style.width = "auto";
this.el.style.position = "absolute";
this.p.style.height = this.ht + "px";
this.p.style.zIndex = 100;
this.set = true;
this.el.focus();
}
resizeselect.prototype.reset_select = function (str) {
this.el.style.width = "";
this.el.style.position = "";
this.p.style.height = "";
this.p.style.zIndex = 1;
this.set = false;
window.focus();
}
The mousedown event is raise before the click event :
first mousedown raise -> set the width to 'auto' (if the state of the dropdown is 'close')
click raise -> store in a var the state of the dropdown : 'open'
We select a value, the second mousedown is raised : nothing to do
click raise -> we need to restore the original width of the dropdown and change the state of the var to : 'close'
The blur and change event are needed to close the dropdown if the user clicked outside the dropdown.
Here the complete solution with Brendan's code :
(function ($) {
var open = {}
$.fn.IELongDropDown = function (cln) {
if (jQuery.browser.msie) { //only IE has problems with long select boxes
var el = this;
var id = el.attr('id');
var margin = 2; //Need to set a margin however the arrow is cut
var previousWidth = el.width() + margin;
var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:" + previousWidth + "px'></div>";
el.wrap(divWrapper);
var newWidth = el.width("auto").width();
el.width(previousWidth);
if (newWidth > previousWidth) {
el.mousedown(function () {
if (!open[id]) {
el.width("auto");
el.focus();
}
});
el.click(function () {
if (!open[id])
open[id] = true;
else {
open[id] = false;
return el.width(previousWidth);
}
});
el.blur(function () {
open[id] = false;
return el.width(previousWidth);
});
el.change(function () {
open[id] = false;
return el.width(previousWidth);
});
}
}
return this;
};
})(jQuery);
Call the function :
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#mydropdownlist').IELongDropDown();
});
</script>
you can not open the select list but you can do it by changing the size of theselect list on click or any other event you want
$("#drpdwn").mousedown(bodyevent);
function bodyevent()
{
console.log("size changed");
$(this).attr('size',3);
}
$("#drpdwn").focus(function()
{
//alert("txt clicked from ");
var $el = $("#drpdwn");
var offset = $el.offset();
var event = jQuery.Event( "mousedown", {
which: 1,
pageX: offset.left,
pageY: offset.top
});
$el.trigger(event);
});
As an alternative you can use the select2 plugin and do the following:
$(element_select).focus();
$(element_select).select2('open').trigger('open');
It worked perfectly for me in Firefox version 79.0
There is an alternate solution i found for this problem. Just add a theme to your select box like Selectize.js it will convert your select box into ul li html tags but works as select box. You can easily hide show ul li's on jquery events.

Categories

Resources