Select and copy table to clipboard - javascript

I want to select table without headers, and it works, but I cannot get it so, that it would copy to clipboard.
Here's the page: http://tuudik.lohv.eu/Asjad/EURXML/
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ECB kursid seisuga: 2011-04-01 </title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<style type="text/css">
table
{
border-collapse:collapse;
}
table, td, th
{
border:1px solid black;
}
</style>
<script type="text/javascript">
function selectElementContents(el) {
var body = document.body, range, sel;
if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand('Copy');
} else if (document.createRange && window.getSelection) {
range = document.createRange();
range.selectNodeContents(el);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
sel.execCommand('Copy');
}
}
</script>
</head>
<body>
<table cellpadding="2">
<thead>
<tr>
<th>Valuuta</th>
<th>Kurss</th>
</tr>
</thead>
<tbody id="currencies">
<tr><td>USD</td><td>1,4141</td></tr><tr><td>JPY</td><td>118,56</td></tr><tr><td>DKK</td><td>7,4564</td></tr><tr><td>GBP</td><td>0,88150</td></tr><tr><td>NOK</td><td>7,8055</td></tr><tr><td>RUB</td><td>40,1500</td></tr><tr><td>CAD</td><td>1,3686</td></tr></tbody>
</table>
<input type="button" value="select table"
onclick="selectElementContents( document.getElementById('currencies') );">
</body>
</html>

This works for me on IE8:
var table = document.getElementById('copyHtmlToClipboard');
// Below line is essential !!!
table.contentEditable = 'true';
var controlRange = document.body.createControlRange();
controlRange.addElement(table);
controlRange.execCommand("Copy");

In most browsers it isn't possible to copy to the system clipboard. To do this you need to use a hack. The most common way is to use Flash. ZeroClipboard does this and appears to work quite well.
By the way, execCommand() is a method of document and TextRange objects, not Selection objects, so sel.execCommand("Copy") couldn't possibly work.
UPDATE
I've never actually used ZeroClipboard. Having looked at the docs, it doesn't look like it does what I had hoped (there seems to be no way to copy rich text) and is even more of a gruesome hack than I thought. You could copy the table's content as text via innerHTML using ZeroClipboard, but whether this is acceptable or not depends on what you're hoping the user can do with the copied content.

Related

Change CSS background-color using Javascript

As the title suggest, I'm trying to change my css background-color using javascript function. To simplify the problem, I write a new code here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Potato</title>
<style>
#item {
background-color:blue;
color:red;
}
</style>
<script type="text/javascript">
function changeBG(id,color) {
var id = id;
var color = color;
document.getElementById(id).style.background-color = color;
}
</script>
</head>
<body>
<script type="text/javascript">changeBG(item,green)</script>
<div id="item">I am a potato</div>
</body>
</html>
The default background-color is red (as suggested by CSS), then I want to change it to green before I print it. But the code doesn't work. I don't know where the mistake is.
First item needs to be made first:
<div id="item">I am a potato</div>
<script>
//...stuff....
</script>
Then we need to use strings:
changeBG("item","green")
And finally in JavaScript we say backgroundColor other than background-color.
#media print {
#item {
background-color:green;
}
}
Include this in your css. This will solves your problem while printing.
All css properties in javascript are camelCased rather than spinal-cased
document.getElementById('youElement').style.backgroundColor = 'color';
Use jQuery
$("#item").css("background-color", "green");
Documentation
Or pure JavaScript
document.getElementById("item").style.backgroundColor = "green";
Documentation

Displaying a part of DIV in iframe

I am using HTML object in below manner
<object id="foo" name="foo" type="text/html" data="mypage.aspx">
</object>
Now, I don't want to display complete data in mypage.aspx in HTML object/iframe. I just want to display a DIV layer from mypage.aspx in current page (default.aspx). I tried using data="mypage.aspx#div1" but didn't work.
For testing purpose mypage.aspx consists of
<body>
<div id="div1">This has to be displayed</div>
<div id="div2">This should not be displayed</div>
This portion also should not be displayed
</body>
How can I display only DIV1 part of mypage.aspx in HTML object?
If you can get rid of using object or iframe you can use jQuery load method to just get the required mark up from mypage.aspx. Keep a container in your parent page which will hold the required content from mypage.aspx and try this.
$(function(){
//Here container is a div in which #div1 from mypage.aspx will be loaded.
$('#container').load('mypage.aspx #div1');
});
If you want to read about Loading Page Fragments using jQuery take a look at this link
I don't have an aspx capable server. So I tested using plain html, but the principle is the same really.
I recreated test.html:
<body>
<div id="div1">This has to be displayed</div>
<div id="div2">This should not be displayed</div>
This portion also should not be displayed
</body>
Then I made test2.html and for simplicity I embedded the JavaScript in test2.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Test</title>
<script language="javascript"type="text/javascript">
function init() {
var obj = document.getElementById("foo"); // Grab the frame element
var kids = obj.contentDocument.body.childNodes; // Grab all child nodes of the body node of fram element
for( var i = 0; i < kids.length; i++ ) { // iterate through all child nodes
if( kids[i].id == "div1" ) { // if child node's id is "div1"
alert(kids[i].firstChild.nodeValue); // alert the first child of the div, e.g. text node, value
}
}
}
window.onload = init;
</script>
</head>
<body>
<object id="foo" name="foo" type="text/html" data="test.html"> </object>
</body>
</html>
This approach seemed the most cross-browser compatible naked javascript I could create. I'm not claiming that it's the best possible solution, though.
Here's some additional things you can do, I wrote comments for each. I commented one of the lines out because it makes a dramatic change I'm not sure you'd like. You can try it, though.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Test</title>
<script language="javascript"type="text/javascript">
function init() {
var myDiv = document.createElement("div"); //create a new div
myDiv.innerHTML = "<strong>Testing!</strong>"; // add some HTML to myDiv
var obj = document.getElementById("foo"); // Grab the frame element
var kids = obj.contentDocument.body.childNodes; // Grab all child nodes of the body node of fram element
for( var i = 0; i < kids.length; i++ ) { // iterate through all child nodes
if( kids[i].id == "div1" ) { // if child node's id is "div1"
kids[i].firstChild.nodeValue = "sts"; // change first text node to sts
kids[i].appendChild( myDiv ); //append myDiv to Div1
document.getElementById("container").innerHTML = kids[i].firstChild.nodeValue; // add text to container
//document.getElementById("container").appendChild(kids[i]); // actually append, or insert div1 into container2, this should move the div1 out of the frame and into the document
}
}
}
window.onload = init;
</script>
</head>
<body>
<object id="foo" name="foo" type="text/html" data="test.html"> </object>
<div id="container"></div>
<div id="container2"></div>
</body>
</html>

jQuery ajax doesn't seem to be reading HTML data in Chromium

I have an HTML (App) file that reads another HTML (data) file via jQuery.ajax(). It then finds specific tags in the data HTML file and uses text within the tags to display sort-of tool tips.
Here's the App HTML file:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>Test</title>
<style type="text/css">
<!--/* <![CDATA[ */
body {
font-family : sans-serif;
font-size : medium;
margin-bottom : 5em;
}
a, a:hover, a:visited {
text-decoration : none;
color : #2222aa;
}
a:hover {
background-color : #eeeeee;
}
#stat_preview {
position : absolute;
background : #ccc;
border : thin solid #aaa;
padding : 3px;
font-family : monospace;
height : 2.5em;
}
/* ]]> */-->
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("#stat_preview").hide();
$(".cfg_lnk").mouseover(function () {
lnk = $(this);
$.ajax({
url: lnk.attr("href"),
success: function (data) {
console.log (data);
$("#stat_preview").html("A heading<br>")
.append($(".tool_tip_text", $(data)).slice(0,3).text())
.css('left', (lnk.offset().left + lnk.width() + 30))
.css('top', (lnk.offset().top + (lnk.height()/2)))
.show();
}
});
}).mouseout (function () {
$("#stat_preview").hide();
});
});
//]]>
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Test</h1>
<ul>
<li><a class="cfg_lnk" href="data.html">Sample data</a></li>
</ul>
<div id="stat_preview"></div>
</body>
</html>
And here is the data HTML
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Test</h1>
<table>
<tr>
<td class="tool_tip_text"> Some random value 1</td>
<td class="tool_tip_text"> Some random value 2</td>
<td class="tool_tip_text"> Some random value 3</td>
<td class="tool_tip_text"> Some random value 4</td>
<td class="tool_tip_text"> Some random value 5</td>
</tr>
<tr>
<td class="tool_top_text"> Some random value 11</td>
<td class="tool_top_text"> Some random value 21</td>
<td class="tool_top_text"> Some random value 31</td>
<td class="tool_top_text"> Some random value 41</td>
<td class="tool_top_text"> Some random value 51</td>
</tr>
</table>
</body>
</html>
This is working as intended in Firefox, but not in Chrome (Chromium 5.0.356.0).
The console.log (data) displays empty string in Chromium's JavaScript console. Firebug in Firefox, however, displays the entire data HTML.
Am I missing something? Any pointers?
Not sure of the answer, but a few avenues of investigation that I could think of:
Is data an object (rather than a string?) Maybe the Chromium console doesn't know how to display it. You could try an alternative output method to test it, or see if supplying the 'dataType' setting makes any difference.
Is the success callback being called at all in Chromium? It could be a bug, or some browser security feature (like cross-site-scripting protection, or having javascript disabled) that's blocking it.
Experiment with a static version of the HTML/CSS your code is supposed to produce, and make sure it displays properly in both browsers.

Execcommand for iframe don't work

I am making my own WYSIWYG editor. But i can't make any text bold with the execcommand function. I am using the next code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
function loadWysiwyg() {
if(window.navigator.appName == "Microsoft Internet Explorer") {
reactioneditor.document.designMode = "on";
} else {
document.getElementById('reactioneditor').contentDocument.designMode = "on";
}
}
function make_bold() {
document.getElementById("reactioneditor").contentWindow.document.execCommand("bold", false, null);
}
</script>
</head>
<body onload="loadWysiwyg();">
<iframe id="reactioneditor" style="border: 1px solid #CCC;width: 100%; height: 200px;"></iframe>
<button id="makebold" onclick="make_bold();">Maak bold</button>
</body>
</html>
I readed multiple tutorials but with no effect, i don't now how i can fix it.
Is there anyone who can?
Your exact code works for me in IE, Firefox, and Chrome. I wrote some text into the iFrame, selected it, and clicked the button. Are those the steps you are taking? Are you getting any errors?

Select Cells On A Table By Dragging

I was looking at this question and saw the reference to the iPhone game where you drag across the screen selecting letters as you go.
I was curious to see an implimentation of this in Javascript using tables. So you'd drag the mouse over each cell they would then become highlighted.
I'm not sure what the best method would be but I hope someone has a go. Someone attempted it here, but it doesn't really work.
Thank Cacoo for the sexy diagrams. It's like an online visio, really nice. Check it out ;)
Here's a working prototype: http://jsfiddle.net/few5E/ Using jQuery for DOM hooking, but could easily be implemented with another framework.
Update: http://jsfiddle.net/Brv6J/ a slightly different version - the highlighted state will only change when you release and click again.
Update 2: http://jsfiddle.net/Brv6J/3/ - binding onselectstart so that text is not selected in IE.
A few relevant facts:
The mousedown event of the table cells is hooked to track the actual click. This event is stopped, so that text selection is hindered. Also binding ontextselect for the same effect in IE.
The mouseover event will toggle the highlighted class for the cell
The mouseout event is hooked on document. This is to ensure that it always runs. If the mouseup event was hooked on the table cell, it would not trigger if you released the mouse key with the mouse outside of the table. This state is tracked in isMouseDown.
Full source code for reference:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css" media="screen">
table td {
width:100px;
height:100px;
text-align:center;
vertical-align:middle;
background-color:#ccc;
}
table td.highlighted {
background-color:#999;
}
</style>
</head>
<body>
<table cellpadding="0" cellspacing="1" id="our_table">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
<tr>
<td>g</td>
<td>h</td>
<td>i</td>
</tr>
</table>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var isMouseDown = false;
$("#our_table td")
.mousedown(function () {
isMouseDown = true;
$(this).toggleClass("highlighted");
return false; // prevent text selection
})
.mouseover(function () {
if (isMouseDown) {
$(this).toggleClass("highlighted");
}
})
.bind("selectstart", function () {
return false; // prevent text selection in IE
});
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
</script>
</body>
</html>
If you're after spreadsheet-like cell selection (in column/row blocks), you need to highlight every cell in every row that is between your start & end index (both row and cell) in your mouseover event:
for (var i = rowStart; i <= rowEnd; i++) {
var rowCells = table.find("tr").eq(i).find("td");
for (var j = cellStart; j <= cellEnd; j++) {
rowCells.eq(j).addClass("selected");
}
}
As the user might start selecting cells from all directions (up-bottom, bottom-up, right-left, left-right) you need to assign the correct indexes for start & end.
Here is a jsFiddle.
http://www.jaanuskase.com/stuff/dragSelect.html
Not sure if you wanted pure-Javascript implementation, I used jQuery for convenience.

Categories

Resources