I have a <textarea /> as in the code below. How do I display the line numbers on the left hand side of it?
Is there a jQuery plugin?
<TEXTAREA name="program" id="program" rows="15" cols="65" ></TEXTAREA>
There is Lined TextArea (Link no longer valid, see mirror) plugin for jQuery by Alan Williamson
MIT License
jQuery 1.3+
You can very well try
Code Mirror, which is a JavaScript library for embedding a code editor in a web page.
With code lines, it has great features like
Autocompletion
Themes
Mixed language modes
Search
Merge/diff interface
Custom scrollbars etc.
This is a very simple, but effective trick. It inserts an image with the line numbers already added.
The only catch is you may need to create your own image to match your UI design.
https://jsfiddle.net/vaakash/5TF5h/
textarea {
background: url(http://i.imgur.com/2cOaJ.png);
background-attachment: local;
background-repeat: no-repeat;
padding-left: 35px;
padding-top: 10px;
border-color:#ccc;
}
Credit goes to: Aakash Chakravarthy
TLDR: Use CodeMirror
Someone else here recommended CodeMirror, and I can't hardly recommend it enough! But this answer didn't really provide any technical details.
Other solutions: Everything else I tried here has problems with line numbers not matching up with lines. I believe this is because I have monitor DPI (dots per inch) at 120%, and these solutions didn't take this into account.
So, how do you use CodeMirror??? Easy! Just look at the 21,000 words of the documentation! I hope to explain 99% of your questions on it in less than page or two.
Demo it Up!
100% working demo, and it's working perfectly in the StackOverflow sandbox:
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
lineNumbers: true,
mode: 'text/x-perl',
theme: 'abbott',
});
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/perl/perl.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/theme/abbott.min.css"></link>
<textarea id="code" name="code">
if($cool_variable) {
doTheCoolThing(); # it's PRETTY cool, imho
}</textarea>
Features!
Insert/overwrite mode.
Multiple row indenting simultaneously.
Tons of themes.
TLDR: How to Use CodeMirror, in a Page or Less
Step 1 - Load Basic Core Libraries
Add this to your <head> block...
<script language="javascript" type="text/javascript" src="/static/js/codemirror-5.62.0/lib/codemirror.js"></script>
<link rel="stylesheet" type="text/css" href="/static/js/codemirror-5.62.0/lib/codemirror.css"></link>
And, if you like to have extra-bracket color matching, also load this:
<script language="javascript" type="text/javascript" src="/codemirror-5.62.0/addon/edit/matchbrackets.js"></script>
Step 2 - Setup Syntax Highlighting
Check the /codemirror-5.62.0/mode/ dir to see what language matches the language you'll be coding in. There is extensive support in this area.
Add this to your <head> block...
<script language="javascript" type="text/javascript" src="/static/js/codemirror-5.62.0/mode/perl/perl.js"></script>
Step 3 - Initialize and Display CodeMirror
Have some textarea to use....
<textarea id="code" name="code"></textarea>
Initialize and set your codemirror in the JS. You need to use the Mimetype to indicate the mode you want to use, in this case, I'm indicating the Perl Mimetype...
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
lineNumbers: true,
mode: 'text/x-perl',
matchBrackets: true,
});
Step 4 - Pick a Theme
Choose some theme you like, 'liquibyte', 'cobalt' and 'abbott' are both pretty decent dark-mode-ish themes. Run this after defining editor...
editor.setOption('theme', 'cobalt');
And that's it!
No one tried to do this using HTML5 Canvas object and by painting line numbers on it.
So here what I've managed to pool in few hours.
Put canvas and textarea, one next to the other, and painted numbers on canvas.
https://www.w3schools.com/code/tryit.asp?filename=G68VMFWS12UH
true there is limitation we can't handle word-wrap easy in Paint() function without iterating entire textarea content and offdrawing to mirror object for measurements of each line height. Also would yield very complex code.
preview image
CodePress is the one used in WordPress.
function generateWithNumber() {
let inputTexts = document.getElementById("input").value
let textsByLine = inputTexts.split("\n");
const listMarkup = makeUL(textsByLine);
document.getElementById("output").appendChild(listMarkup);
}
function makeUL(array) {
let list = document.createElement('ol');
for (let i = 0; i < array.length; i++) {
let item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
// document.getElementById('foo').appendChild(makeUL(options[0]));
ol {
counter-reset: list;
}
ol > li {
list-style: none;
}
ol > li:before {
content: counter(list) ") ";
counter-increment: list;
}
<textarea id="input"></textarea>
<button onClick=generateWithNumber() >Generate</button>
<p id="output"></p>
Consider the use of a contenteditable ordered list <ol> instead of <textarea>
ol {
font-family: monospace;
white-space: pre;
}
li::marker {
font-size: 10px;
color: grey;
}
<ol contenteditable><li>lorem ipsum
<li>>> lorem ipsum
<li>lorem ipsum,\
<li>lorem ipsum.
<li>>> lorem ipsum
<li>lorem ipsum
<li>lorem ipsum
<li>lorem
<li>ipsum
<li>>> lorem ipsum
<li>lorem ipsum
</ol>
However, ::marker styling seems limited (list-style-type). E.g. removing the period or vertical-align: super seems to needs other workarounds (back to li:before and counter).
Bonus: <li> also does not need the closing tag </li> (https://html.spec.whatwg.org/multipage/syntax.html#optional-tags), which saves typing.
Also as far as I understand, the <textarea> in codemirror just works in the background (Pseudo contenteditable: how does codemirror works?).
Line Numbers
Code:
const textarea = document.querySelector("textarea");
const numbers = document.querySelector(".numbers");
textarea.addEventListener("keyup", (e) => {
const num = e.target.value.split("\n").length;
numbers.innerHTML = Array(num).fill("<span></span>").join("");
});
textarea.addEventListener("keydown", (event) => {
if (event.key === "Tab") {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
textarea.value =
textarea.value.substring(0, start) +
"\t" +
textarea.value.substring(end);
event.preventDefault();
}
});
body {
font-family: Consolas, "Courier New", Courier, monospace;
}
.editor {
display: inline-flex;
gap: 10px;
font-family: Consolas, "Courier New", Courier, monospace;
line-height: 21px;
background-color: #282a3a;
border-radius: 2px;
padding: 20px 10px;
}
textarea {
line-height: 21px;
overflow-y: hidden;
padding: 0;
border: 0;
background: #282a3a;
color: #fff;
min-width: 500px;
outline: none;
resize: none;
font-family: Consolas, "Courier New", Courier, monospace;
}
.numbers {
width: 20px;
text-align: right;
}
.numbers span {
counter-increment: linenumber;
}
.numbers span::before {
content: counter(linenumber);
display: block;
color: #506882;
}
<div class="editor">
<div class="numbers">
<span></span>
</div>
<textarea cols="30" rows="10"></textarea>
</div>
From: https://www.webtips.dev/add-line-numbers-to-html-textarea
It actually works quite well.
The line numbers do not occur instantly but it workds quite fast.
Related
Basically it would would be super great if someone can provide a pointer on how to achieve this.
I use a 3rd SAS and when logged in to it, it returns the username to class="SFnam" which can be displayed on any page that has the associated JS embedded in the bottom of the page.
At the moment I use the following html to display the Users Name in the top right of the screen when logged in: i.e. "Logged in as: BORIS SMITH", however when a users NOT not logged in it displays "Logged in as:". Not ideal.
How can I display "LOGIN" if the class="SFnam" is empty?
Here's what I'm using (After Rafaels input):
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function(event) {
var spanElm = document.getElementById('myspan');
if(spanElm.classList.contains('SFnam'))
{
console.log('here');
}
else
{
console.log('here instead');
document.getElementsByTagName('user')[0].innerHTML = "LOGIN";
}
});
</script>
<style>
#loginwrapper {
margin: 0px 0px 0px Opx;
border: none;
cursor: pointer;
}
.logincontainer { text-align: right;}
user {
display: inline-flex;
background-color: #1f7665; color: #fff;
padding:2px 3px 1px 3px;
font-size:8px;
margin-right: 10px;
border-radius: 3px;
font-family: Raleway, Arial, Helvetica, 'Liberation Sans', FreeSans, sans-serif;
}
</style>
<div id="loginwrapper" title ="Click to Log in/out" onclick="window.open('/member-login.html','_self')">
<div class="logincontainer">
<user>Logged in as: <b><span style="text-transform:uppercase;" class="SFnam" id='myspan'></span></b>
</div>
</div>
When logged in the span result is:
< span class="SFnam">Boris Smith< /span >
When logged out the span result is:
< span class="SFnam">< /span>
I am reasonably new to this however have some skills with basic coding etc so apologies if the above has not been constructed poorly :(.
Any guidance / assistance will be gratefully appreciated.
Cheers
Boris
EDITED:
Also of note is the Listener script at the bottom of each page (not sure if that helps?:
<script>(function(){var i,j,a,x;try{x=localStorage.getItem("SF_nam");}catch(e){x="";}
try{for(a=document.querySelectorAll(".SFnam"),i=a.length-1;i>=0;i--)a[i].innerHTML=x?x:"";}catch(e){}
try{for(a=document.querySelectorAll(".SF_li"),i=a.length-1;i>=0;i--)a[i].style.display=x?"":"none";}catch(e){}
try{for(a=document.querySelectorAll(".SF_lo"),i=a.length-1;i>=0;i--)a[i].style.display=x?"none":"";}catch(e){}})();
</script>
This will change the element's text accordingly to that span class containing text or not.
function updateSpan()
{
var spanElm = document.getElementById('myspan');
if(spanElm.innerHTML)
{
document.getElementsByTagName('user')[0].innerHTML = "Logged in as " + spanElm.innerHTML;
}
else
{
document.getElementsByTagName('user')[0].innerHTML = "LOGIN";
}
}
window.addEventListener("DOMContentLoaded", function(event) {
updateSpan();
});
add an id to your span so we can locate it
<span style="text-transform:uppercase;"class="SFnam" id='myspan'></span>
update your bottom script with this
<script>(function(){var i,j,a,x;try{x=localStorage.getItem("SF_nam");}catch(e){x="";}
try{for(a=document.querySelectorAll(".SFnam"),i=a.length-1;i>=0;i--)a[i].innerHTML=x?x:"";}catch(e){}
try{for(a=document.querySelectorAll(".SF_li"),i=a.length-1;i>=0;i--)a[i].style.display=x?"":"none";}catch(e){}
try{for(a=document.querySelectorAll(".SF_lo"),i=a.length-1;i>=0;i--)a[i].style.display=x?"none":"";}catch(e){}
updateSpan()})();
</script>
This will make sure the function is also updated if changes happen during execution time.
Here's a JSFiddle
Following is my HTML
Branding
Is it possible to access using CSS to access anchor tag's text?
Something like this is what I want? The html is dynamically generated, so please don't mention to have id's or to have any classes.
a[text='Branding']
{
}
People already told you that you CAN'T select text in CSS. But there's some workaround in my opinion.
I don't know what you want to do, possibly a bad thing, but if I were you I'd take this bad practice:
/*First you hide the text*/
a {
font-size: 0; /* hide text */
text-decoration: none !important; /* get rid of that awful underline */
}
/* then you insert a new element using :before */
a:before {
content: 'Branding'; /* This is the text you want for the new element */
color: #333;
font-size: 15px; /* Bring back the text inside the anchor for this new element */
font: 24px sans-serif;
}
fiddle: http://jsfiddle.net/tsu7z546/
In case you want to try out jQuery:
$(document).ready(function(){
var brandingAnchor = $('a:contains("Branding")');
brandingAnchor.hide();
});
Remember! Every time you write jQuery code, you must have already called jQuery library on your page, just like this:
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
//Your jQuery code goes HERE, just below the library
$(document).ready(function(){
var brandingAnchor = $('a:contains("Branding")');
brandingAnchor.hide();
});
</script>
I've read a lot of web-sites about printing page numbers, but still I couldn't make it display for my html page when I try to print it.
So the CSS code is next:
#page {
margin: 10%;
#top-center {
font-family: sans-serif;
font-weight: bold;
font-size: 2em;
content: counter(page);
}
}
I've tried to put this page rule inside
#media all {
*CSS code*
}
And outside of it, tried to put it in #media print, but nothing helped me to display the page numbers on my page. I've tried to use FireFox and Chrome(based on WebKit as you know). I think the problem is in my html or css code. Could somebody show me an example of implementing this #page rule in the big html page with several pages? I just need the code of html page and the code of css file, that works.
P.S. I have the latest supported versions of browsers.
As #page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using #page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:
#content {
display: table;
}
#pageFooter {
display: table-footer-group;
}
#pageFooter:after {
counter-increment: page;
content: counter(page);
}
And the HTML code is:
<div id="content">
<div id="pageFooter">Page </div>
multi-page content here...
</div>
This way you can customize your page number by editing parametrs to #pageFooter. My example:
#pageFooter:after {
counter-increment: page;
content:"Page " counter(page);
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
-moz-border-radius: 5px;
-moz-box-shadow: 0px 0px 4px #222;
background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
}
This trick worked for me fine. Hope it will help you.
Try to use https://www.pagedjs.org/. It polyfills page counter, header-/footer-functionality for all major browsers.
#page {
#bottom-left {
content: counter(page) ' of ' counter(pages);
}
}
It's so much more comfortable compared to alternatives like PrinceXML, Antennahouse, WeasyPrince, PDFReactor, etc ...
And it is totally free! No pricing or whatever. It really saved my life!
This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.
A4 height = 297mm = 1123px(96dpi)
<html>
<head>
<style type="text/css">
#page {
size: A4;
margin: 0;
}
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = addPageNumbers;
function addPageNumbers() {
var totalPages = Math.ceil(document.body.scrollHeight / 1123); //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi,
for (var i = 1; i <= totalPages; i++) {
var pageNumberDiv = document.createElement("div");
var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
pageNumberDiv.style.position = "absolute";
pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
pageNumberDiv.style.height = "16px";
pageNumberDiv.appendChild(pageNumber);
document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
}
}
</script>
<div id="content">
Lorem ipsum....
</div>
</body>
</html>
Can you try this, you can use content: counter(page);
#page {
#bottom-left {
content: counter(page) "/" counter(pages);
}
}
Ref: http://www.w3.org/TR/CSS21/generate.html#counters
http://www.princexml.com/doc/9.0/page-numbers/
If you are looking to add page numbers when printing under Chrome/Chromium, one easy solution is to use Paged.js.
This JS library takes your HTML/CSS and cuts it into pages, ready to print as a book, that you will preview in your browser. It makes the #page and most the CSS3 specifications work for Chrome.
Solution 1 (easy) if you are OK with cutting your view into pages, ready to print
Just add their CDN in the head tag of your page :
<link href="path/to/file/interface.css" rel="stylesheet" type="text/css">
You can then add page numbers by using the automated counter page. Example :
HTML to put anywhere you want to display the current page number:
<div class="page-number"></div>
CSS to make the number appear in the div :
.page-number{
content: counter(page)
}
The library also allows to easily manage page margins, footers, headers, etc.
Solution 2 (trickier) if you want to show numbers (and page breaks) only when printing
In this case, you need to apply the Paged.js CDN only when printing the document.
One way I can think of would be to add a print me button that fires Javascript to :
add the CDN to the page
and then execute window.print(); to launch the printing prompt of the navigator
I don't know if someone still out there needs the answer, try this, it might work for you
in your html file put a div element your html like this
<div class="page-number"></div>
and do your css like this
.page-number:before {
content: "Page: " counter(page);}
hope it works for you
I know this is not a coding answer but it is what the OP wanted and what I have spent half the day trying to achieve - print from a web page with page numbers.
Print to pdf without the numbers
Run it through ilovepdf here https://www.ilovepdf.com/add_pdf_page_number which adds the page numbers
Yes, it is two steps instead of one but I haven't been able to find any CSS option despite several hours of searching. Real shame all the browsers removed the functionality that used to allow it.
This is what you want:
#page {
#bottom-right {
content: counter(page) " of " counter(pages);
}
}
I use page numbers styled in CSS to generated PDF documents, and it works:
#page {
size: A4 portrait;
margin-top: 1.2cm;
margin-bottom: 1.2cm;
margin-left: 1.2cm;
margin-right: 1.2cm;
background-image: url('../../images/logo_small.png');
background-repeat: no-repeat;
background-position: 40px 10px;
#bottom-center {
content: counter(page);
}
}
**#page {
margin-top:21% !important;
#top-left{
content: element(header);
}
#bottom-left {
content: element(footer
}
div.header {
position: running(header);
}
div.footer {
position: running(footer);
border-bottom: 2px solid black;
}
.pagenumber:before {
content: counter(page);
}
.pagecount:before {
content: counter(pages);
}
<div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
<span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
</div >**
I'm using contenteditable divs instead of input elements, because they are more flexible when it comes to styling within the input box. I'm just wondering if there's a way to make the input look like an input element with its type set to password, like so:
<input type='password'>
I hope that is clear enough. Thanks.
you will have to find out the browser specific CSS settings for mozilla and co.. but in webkit it looks like this. also you need to add the keypress handler via javascript for it.
<style>
#password {
-webkit-text-security: disc;
height:20px; width:100px;
-webkit-appearance: textfield;
padding: 1px;
background-color: white;
border: 2px inset;
-webkit-user-select: text;
cursor: auto;
}
</style>
<div id="password" contenteditable="true">yourpassword</div>
<script>
//you could use javascript to do nice stuff
var fakepassw=document.getElementById('password');
//fakepassw.contentEditable="true";
fakepassw.addEventListener('focus',function(e){ /*yourcode*/ },false);
fakepassw.addEventListener('keyup',function(e){ console.log(e.keyCode) },false);
</script>
but anyway, password fields are just combined elements with element.innerHTML="yourpassword" and element.innerText="•••••••"
you could do this with javascript too and fill innerText with "•"
I came across this question as I was trying to imitate a password input as well, but overlaying another div with •s wasn't an option for me, since I wanted it to work without JavaScript, too.
Then there's text-security: disc, but there isn't enough support for that as of this moment.
So what I've done is create a font on FontStruct in which all Latin characters (including the diacritic ones) look like a •.
Here is a link to the file on my Dropbox.
When using this, just add this in your CSS file
#font-face {
font-family: 'password';
src: url('../font/password.woff2') format('woff2'),
url('../font/password.woff') format('woff'),
url('../font/password.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Then to use it, simply apply font-family: 'password' to your element.
P.S. If the Dropbox link is down and you happen to have it downloaded, feel free to replace the link. Otherwise just give this answer a comment
To get rid of password remember, I treated the password as input field, and "blur" the text typed.
It is less "safe" than a native password field since selecting the typed text would show it as clear text, but password is not remembered. It also depends on having Javascript activated.
<input style="background-color: rgb(239, 179, 196); color: black; text-shadow: none;" name="password" size="10" maxlength="30" onfocus="this.value='';this.style.color='black'; this.style.textShadow='none';" onkeypress="this.style.color='transparent'; this.style.textShadow='1px 1px 6px green';" autocomplete="off" type="text">
The edit queue for #Ol Sen's answer was full. Here's the runnable code snippet.
Note the JavaScript is completely optional. This is really a CSS-only solution for browsers that support -webkit-text-security.
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-text-security
//you could use javascript to do nice stuff
var fakepassw = document.getElementById('password');
//fakepassw.contentEditable="true";
fakepassw.addEventListener('focus', function(e) { /*yourcode*/ }, false);
fakepassw.addEventListener('keyup', function(e) {
console.log(e.keyCode)
}, false);
#password {
-webkit-text-security: disc;
/* all styles below this line are optional */
height: 20px;
width: 100px;
-webkit-appearance: textfield;
padding: 1px;
background-color: white;
border: 2px inset;
-webkit-user-select: text;
cursor: auto;
}
<div id="password" contenteditable="true">yourpassword</div>
Here's my solution. It's not perfect (it only handles additional/deleted characters at end), but it's pretty short:
html:
<input
id="my_id"
type="text"
oninput="inputToBullets(this)"
onfocus="this.value='';this.inputPw='';"
autocomplete="off"
/>
JavaScript:
function inputToBullets (el) {
if (!el.inputPw) {
el.inputPw = '';
}
var val = el.value;
var len = val.length;
var chr = val.substr(len - 1);
if (chr !== "•") {
el.inputPw += chr;
} else {
el.inputPw = el.inputPw.substr(0, len);
}
el.value = el.value.replace(/./g, "•");
}
JavaScript to retrieve password:
var password = document.getElementById('my_id').inputPw;
First, I have been here How to make HTML Text unselectable
But that doesn't solve my issue, (the JavaScript version works well, but I need to make it using HTML and CSS, I cannot use JavaScript) I used the recommended CSS, but look at my DEMO drag the mouse from [drag from here] to [to here] you will see that the text is still selectable.
any way to make it really unselectable?
Thanks
You can use CSS like this:
CSS
.unselectable {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
/* No support for these yet, use at own risk */
-o-user-select: none;
user-select: none;
}
For older IE versions, the issue usually is harder to deal with, but you can use a behavior:
CSS
.unselectable {
behavior: url(ieUserSelectFix.htc);
}
and the behavior file "ieUserSelectFix.htc":
<public:component lightweight="true">
<public:attach event="ondocumentready" onevent="stopSelection()" />
<script type="text/javascript">
<!--
function stopSelection() {
element.onselectstart = function() { return(false); };
element.setAttribute('unselectable', 'on', 0);
}
//-->
</script>
</public:component>
With Javascript you can:
yourElement.onselectstart = function() { return(false); };
After reviewing this problem, Came to mind another method to prevent the user from selecting text while viewing the page, basically, setting up a mask over the target text:
Your Fiddle updated here!
Example:
CSS
.wrapTxt {
position: relative;
}
.wrapTxt .mask {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
HTML
<p class="wrapTxt">
This is my text! My text is mine and no one Else's!
<span class="mask"></span>
</p>
The principle here is simple (Fiddle), have a block element over the text, occupying all of it's wrapper space.
The downfall is a hard implementation if you need one line to be selectable and the next one not. Also, links on the "not selectable" text will not me available.
Final note:
The user can always go around this, either by looking at the source code, or by dragging the mouse from top to bottom of the webpage.
try something like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Disable /Prevent Text Selection jQuery-JavaScript</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Begin:
// Jquery Function to Disable Text Selection
(function($){if($.browser.mozilla){$.fn.disableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":"none"})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).css({"MozUserSelect":""})})}}else{if($.browser.msie){$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("selectstart.disableTextSelect")})}}else{$.fn.disableTextSelect=function(){return this.each(function(){$(this).bind("mousedown.disableTextSelect",function(){return false})})};$.fn.enableTextSelect=function(){return this.each(function(){$(this).unbind("mousedown.disableTextSelect")})}}}})(jQuery)
// EO Jquery Function
// Usage
// Load Jquery min .js ignore if already done so
// $("element to disable text").disableTextSelect();
// $("element to Enable text").enableTextSelect();
//
jQuery(function($) {
$("body").disableTextSelect();
$("#code").mouseover(function(){
$("body").enableTextSelect();
});
$("#code").mouseout(function(){
// Code for Deselect Text When Mouseout the Code Area
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
$("body").disableTextSelect();
});
});
</script>
<style type="text/css">
<!--
body {
margin-left: 10px;
margin-top: 10px;
}
#code
{
padding:20px;
border:2px dashed #CCC;
font-family:"Courier New", Courier, monospace;
font-size:15px;
background-color:#EEE;
}
-->
</style>
</head>
<body>
<h2>Disable /Prevent Text Selection jQuery-JavaScript</h2>
<p>Below this Code Area User can Allow to Select a Text in other Area text selection was disabled</p>
<p id="code">
$(".elementsToDisableSelectFor").disableTextSelect();</p>
<p>When you are leaving above code box selection was deselected! If selected !</p>
</body>
</html>
check jsfiddle output:
http://jsfiddle.net/bHafB/
EDIT:
This is a cross-browser method for preventing text selection using an unselectable="on" element attribute.
<!DOCTYPE html>
<html>
<head>
<title>Unselectable Text</title>
<style type="text/css">
[unselectable=on] { -moz-user-select: none; -khtml-user-select: none; user-select: none; }
</style>
</head>
<body id="doc">
<p unselectable="on">For example, the text in this paragraph
cannot be selected.
For example, the text in this paragraph
cannot be selected
For example, the text in this paragraph
cannot be selected</p>
</body>
</html>
Overlay full transparent text:
<div style="position:absolute;left: 1;top:1;z-index:1;font-size: 10pt;color: rgb(0, 0, 0);">highline me</div><br/><div style="position:absolute;left: 0;top:0;;z-index:2;font-size: 20pt;color: rgba(0, 0, 0, 0);">*********</div>