Add line break within tooltips - html

How can line breaks be added within a HTML tooltip?
I tried using <br/> and \n within the tooltip as follows:
Hover me
However, this was useless and I could see the literal text <br/> and \n within the tooltip. Any suggestions will be helpful.

Just use the entity code 
 for a linebreak in a title attribute.

Just add a data attribute
data-html="true"
and you're good to go.
Eg. usage:
<i data-html="true" class="tooltip ficon-help-icon" twipsy-content-set="true" data-original-title= "<b>Hello</b> Stackoverflow"> </i>
It has worked in majority of the tooltip plugins i have tried as of now.

The 
 combined with the style white-space: pre-line; worked for me.

This CSS is what finally worked for me in conjunction with a linefeed in my editor:
.tooltip-inner {
white-space: pre-wrap;
}
Found here:
How to make Twitter bootstrap tooltips have multiple lines?

\n
with the styling
.tooltip-inner {
white-space: pre-line;
}
worked for me.

Give \n between the text. It work on all browsers.
Example
img.tooltip= " Your Text : \n"
img.tooltip += " Your text \n";
This will work for me and it's used in code behind.
Hope this will work for you

I found it. It can be done by simply doing like this
<a ref="#" title="First Line
Second Line
Third line">Hover Me</a>

just use \n in title and add this css
.tooltip-inner {
white-space: pre-wrap;
}

The javascript version
Since 
 (html) is 0D (hex), this can be represented as '\u000d'
str = str.replace(/\n/g, '\u000d');
In addition,
Sharing with you guys an AngularJS filter that replaces \n with that character thanks to the references in the other answers
app.filter('titleLineBreaker', function () {
return function (str) {
if (!str) {
return str;
}
return str.replace(/\n/g, '\u000d');
};
});
usage
<div title="{{ message | titleLineBreaker }}"> </div>

You can use bootstrap tooltip, and don't forget to set the html option to true.
<div id="tool"> tooltip</div>
$('#tool').tooltip({
title: 'line one' +'<br />'+ 'line two',
html: true
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<br /> did work if you are using qTip

Just add data-html="true"
Hover me

it is possible to add linebreaks within native HTML tooltips by simply having the title attribute spread over mutliple lines.
However, I'd recommend using a jQuery tooltip plugin such as Q-Tip: http://craigsworks.com/projects/qtip/.
It is simple to set up and use. Alternatively there are a lot of free javascript tooltip plugins around too.
edit: correction on first statement.

For me, a 2-step solution (combination of formatting the title and adding the style) worked, as follows:
1) Format the title attrbiute:
<a ref="#" title="First Line
Second Line
Third line">Hover Me</a>
2) Add this style to the tips element:
white-space: pre-line;
Tested in IE8, Firefox 22, and Safari 5.1.7.

So if you are using bootstrap4 then this will work.
<style>
.tooltip-inner {
white-space: pre-wrap;
}
</style>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<a data-toggle="tooltip" data-placement="auto" title=" first line
next line" href= ""> Hover me </a>
If you are using in Django project then we can also display dynamic data in tooltips like:
<a class="black-text pb-2 pt-1" data-toggle="tooltip" data-placement="auto" title="{{ post.location }}
{{ post.updated_on }}" href= "{% url 'blog:get_user_profile' post.author.id %}">{{ post.author }}</a>

Well if you are using Jquery Tooltip utility, then in "jquery-ui.js" Javascript file find following text:
tooltip.find(".ui-tooltip-content").html(content);
and put above that
content=content.replace(/\</g,'<').replace(/\>/g,'>');
I hope this will also work for you.

Just use the entity code
for a linebreak in a title attribute.
<a title="First Line
Second Line">Hover Me </a>

Just add this code snippet in your script:
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
and ofcourse as mentioned in above answers the data-html should be "true". This will allow you to use html tags and formatting inside the value of title attribute.

The solution for me was http://jqueryui.com/tooltip/:
And here the code (the part of script that make <br/> Works is "content:"):
HTML HEAD
<head runat="server">
<script src="../Scripts/jquery-2.0.3.min.js"></script>
<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="../Scripts/jquery-ui-1.10.3.min.js"></script>
<script>
/*Position:
my => at
at => element*/
$(function () {
$(document).tooltip({
content: function() {
var element = $( this );
if ( element.is( "[title]" ) ) {
return element.attr( "title" );
}
},
position: { my: "left bottom-3", at: "center top" } });
});
</script>
</head>
ASPX or HTML control
<asp:TextBox ID="Establecimiento" runat="server" Font-Size="1.3em" placeholder="Establecimiento" title="Texto 1.<br/>TIP: texto 2"></asp:TextBox>
Hope this help someone

Grater than Jquery UI 1.10 is not support to use html tag inside of the title attribute because its not valid html.
So the alternative solution is to use tooltip content option.
Refer - http://api.jqueryui.com/tooltip/#option-content

Use
&#013
There shouldn't be any ; character.

if you are using jquery-ui 1.11.4:
var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
Replace--> //return $( "<a>" ).text( title ).html();
by --> return $( "<a>" ).html( title );
},

AngularJS with Bootstrap UI Tolltip (uib-tooltip), has three versions of tool-tip:
uib-tooltip, uib-tooltip-template and uib-tooltip-html
- uib-tooltip takes only text and will escape any HTML provided
- uib-tooltip-html takes an expression that evaluates to an HTML string
- uib-tooltip-template takes a text that specifies the location of the template
In my case, I opted for uib-tooltip-html and there are three parts to it:
configuration
controller
HTML
Example:
(function(angular) {
//Step 1: configure $sceProvider - this allows the configuration of $sce service.
angular.module('myApp', ['uib.bootstrap'])
.config(function($sceProvider) {
$sceProvider.enabled(false);
});
//Step 2: Set the tooltip content in the controller
angular.module('myApp')
.controller('myController', myController);
myController.$inject = ['$sce'];
function myController($sce) {
var vm = this;
vm.tooltipContent = $sce.trustAsHtml('I am the first line <br /><br />' +
'I am the second line-break');
return vm;
}
})(window.angular);
//Step 3: Use the tooltip in HTML (UI)
<div ng-controller="myController as get">
<span uib-tooltip-html="get.tooltipContent">other Contents</span>
</div>
For more information, please check here

Using .html() instead of .text() worked for me. For example
.html("This is a first line." + "<br/>" + "This is a second line.")

Hi this code will work in all browser !!i used
for new line in chrome and safari and ul li for IE
function genarateMultiLIneCode(){
var =values["a","b","c"];
const liStart = '<li>';
const liEnd = '</li>';
const bullet = '• ';
var mergedString = ' ';
const unOrderListStart='<ul>'
const unOrderListEnd='</ul>'
const fakeNewline = '
';
for (let i = 0; i < values.length; i++) {
mergedString += liStart + bullet + values[i] + liEnd + fakeNewline;
}
const tempElement = document.createElement("div");
tempElement.innerHTML = unOrderListStart + mergedString + unOrderListEnd;
return tempElement.innerText;
}
}

This css will help you.
.tooltip {
word-break: break-all;
}
or if you want in one line
.tooltip-inner {
max-width: 100%;
}

Related

Change button / text on button after read less

READ MORE / READ LESS jQuery which I implemented on my HTML Bootstrap page, works BUT as a happy amateur I would like to change my blue text "Read More" to Black, after and if I read more. The page has many Read More sections.
// This function will handle hidden and read more events
$(document).on("click", ".toggle-text-button", function() {
if ($(this).text() == "Read More") {
var thisNow = document.getElementById('toggle-text-button')
console.log("this is now =", thisNow);
$(this).text("Read Less");
// Use a jquery selector using the `.attr()` of the link
$("#toggle-text-" + $(this).attr("toggle-text")).slideDown();
} else {
$(this).text("Read More");
// $(this).addClass("r-Less");
// Use a jquery selector using the `.attr()` of the link
console.log("SLIDE UP -- this is now =", $(this).attr("toggle-text"));
var BackToo = ("#" + "toggle-text-" + $(this).attr("toggle-text") + "b");
var BackCol = ("#" + "toggle-text-" + $(this).attr("toggle-text"));
// offset = $(BackToo).offset().top - document.getElementById(BackToo).clientHeight;
console.log("JUMP BACK =", BackToo)
// $(".r-More").css("color", "black!important");
// $(this).css("color" , "black!important");
$("#toggle-text-" + $(this).attr("toggle-text")).slideUp();
// $(this).addClass("r-Less");
//document.getElementById(BackToo).scrollIntoView();
// $(BackToo)[0].scrollIntoView();
// $('html,body').unbind().animate({scrollTop: $(element).offset().top-50},'slow');
$("html, body").delay(1000).animate({
scrollTop: $(BackToo).offset().top - 150
}, 1000);
// $(this).attr("toggle-text").css("color","blacl!important");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<a class="toggle-text-button item-link r-More" toggle-text="10">Read More<i class="fa fa-arrow-right"></i></a>
No need to script that
You can give the a an href and use :visited css
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<link rel="stylesheet" href="https://www.inspirothemes.com/polo/css/style.css" />
<style>
a.r-More:visited { color: black; }
</style>
Read More<i class="fa fa-arrow-right"></i>
Why are you changing css of class .r-More? Doing it, you are going to change all buttons.
Try remove this:
$(".r-More").css("color", "black!important");
And add just:
$(this).css("color" , "#000"); // avoid to use !important
Now, you have to back to the original color (blue, maybe), when the user clicks at "Read Less":
$(this).css("color" , "blue");
If you want to change others css parameters, I suggest you use some class, like ".readMoreClass". Then, you just have to use:
$(this).addClass(".readMoreClass") // to add class
$(this).removeClass(".readMoreClass") // to remove class
Hope have help you!
So the problem seems to be based on the strong Template from POLO, I was able to get it to work by adding a style directly on each ""Read More ""
and then in jQuere i only needed to use: "" $(".toggle-text-button").css("color" , "red");""
As stated before I do not have knowledge of jquery, so the problem may have been that I did try to change the color on the wrong reference...
Thanks for your Tips

Change page title when div is :target

I'm working on a one single page navigation system; Is there is a way to change the <title> of a page when a div is :target (#divname in url)?
EDIT: Yeah, sorry, a Jquery/javascript solution works as well.
If the url contains #somePage, use #somePage as a selector and retrieve it's data-title value.
Then set <title></title> as that value. location.hash produces #somePage
$('a').click(function(event){
event.preventDefault();
if(location.hash) {
var newPageTitle = $(location.hash).data('title');
$('title').text(newPageTitle);
}
});
Add a data attribute to your div and set it's value to what the page title should be when that link is clicked.
Some Page
<div id="somePage" data-title="This Is The Page Title"></div>
It can be done in following way:
Assume that you have this html element:
<a onclick="onClick1()" href="#test">
link
</a>
and you have this scripts:
<script>
function onClick1(){
setTimeout(onClick,100);
}
function onClick(){
alert(1);
if(document.URL.indexOf("#test")>=0){
document.title = "Your title";
}
}
</script>
then you'll get on click what you need.
Here is example.

How to remove extra <p> & </p> generated by adsense code

If you visit this link page you will see an extra space above tagline that is just above footer. How can I remove that?
This is the PHP inside which google adsense code is placed.
<?php cpotheme_show_taglines('post_bottom', 'tagline_bottom'); ?>
You can use jQuery to remove empty <p></p> tags
$('p').each(function() {
var $this = $(this);
if($this.html().replace(/\s| /g, '').length == 0)
$this.remove();
});
Or if you are concerned about the space it takes up, you could simply hide it using CSS
p:empty {
display: none;
}
Use jQuery :empty selector to find <p></p> in your document.
$(document).ready(function(){
$('p:empty').remove();
});

Make anchor links refer to the current page when using <base>

When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?
For example, if I have a page at http://example.com/foo/:
Current behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:
<base href="https://example.com/">
/test
Anchor
Or without inline JavaScript, something like this:
document.addEventListener('DOMContentLoaded', function(){
var es = document.getElementsByTagName('a')
for(var i=0; i<es.length; i++){
es[i].addEventListener('click', function(e) {
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});
A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}
Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});
You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test
I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.
If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz
To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})
You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.
From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".
If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.