How to print selected portion of HTML page? - javascript

I was trying to print selected <div> tags in HTML. I tried using CSS like this:
<style media="print">
.onlyscreen {
display: none;
}
</style>
<html>
<body>
<div class="onlyscreen">
<p>Hello</p>
<div>
<p> Inner tag</p>
</div>
</div>
<input type="submit" value="Print Report" onclick="window.print()">
</body>
</html>
"Inner tag" is not printed. This is a useful technique, but it fails when there are layered <div> tags.
I also tried this JavaScript:
function printContent(id) {
str = document.getElementById(id).innerHTML;
newwin = window.open('', 'printwin', 'left=100,top=100,width=400,height=400');
newwin.document.write('<HTML>\n<HEAD>\n');
newwin.document.write('<TITLE>Report</TITLE>\n');
newwin.document.write('<script>\n');
newwin.document.write('function chkstate(){\n');
newwin.document.write('if(document.readyState=="complete"){\n');
newwin.document.write('window.close()\n');
newwin.document.write('}\n');
newwin.document.write('else{\n');
newwin.document.write('setTimeout("chkstate()",2000)\n');
newwin.document.write('}\n');
newwin.document.write('}\n');
newwin.document.write('function print_win(){\n');
newwin.document.write('window.print();\n');
newwin.document.write('chkstate();\n');
newwin.document.write('}\n');
newwin.document.write('<\/script>\n');
newwin.document.write('</HEAD>\n');
newwin.document.write('<BODY onload="print_win()">\n');
newwin.document.write(str);
newwin.document.write('</BODY>\n');
newwin.document.write('</HTML>\n');
newwin.document.close();
}
And then calling this function by onclick. This script works fine with one <div> tag but not with mulitple tags. For example
<html>
<body>
<div id="print_thistag">
<p>Hello</p>
</div>
<div id="print_thistag">
<p>User</p>
</div>
<input type="submit" value="Print Report" onclick="printContent('print_thistag')">
</body>
</html>
Only "Hello" gets printed. What should I do in such cases?

Basically the problem is that your printContent function is designed in such way that it works only with a single element.
You can alter your function, so it will accept not the id of the element but the css class name as in the following sample
function printContent(className) {
var matchedElements = document.getElementsByClassName(className);
var str = '';
for (var i = 0; i < matchedElements.length; i++) {
var str = str + matchedElements[i].innerHTML;
}
var newwin = window.open('', 'printwin', 'left=100,top=100,width=400,height=400');
newwin.document.write('<HTML>\n<HEAD>\n');
newwin.document.write('<TITLE>Report</TITLE>\n');
newwin.document.write('<script>\n');
newwin.document.write('function chkstate(){\n');
newwin.document.write('if(document.readyState=="complete"){\n');
newwin.document.write('window.close()\n');
newwin.document.write('}\n');
newwin.document.write('else{\n');
newwin.document.write('setTimeout("chkstate()",2000)\n');
newwin.document.write('}\n');
newwin.document.write('}\n');
newwin.document.write('function print_win(){\n');
newwin.document.write('window.print();\n');
newwin.document.write('chkstate();\n');
newwin.document.write('}\n');
newwin.document.write('<\/script>\n');
newwin.document.write('</HEAD>\n');
newwin.document.write('<BODY onload="print_win()">\n');
newwin.document.write(str);
newwin.document.write('</BODY>\n');
newwin.document.write('</HTML>\n');
newwin.document.close();
}
You'll also need to alter html a bit
<html>
<body>
<div class="print_thistag">
<p>Hello</p>
</div>
<div class="print_thistag">
<p>User</p>
</div>
<input type="submit" value="Print Report" onclick="printContent('print_thistag');">
</body>
</html>
It will work as you expected - aggregate every div content into a single html string which will be printed.
By the way assigning the same id for the multiple elements is not a good practice - the id should be unique and if you want to group elements somehow - you can just add the same class for those elements as in the sample above.

Related

How to create a button that will change background color

I need help coding in HTML. I have tried many different ways of coding this button. The button is on the webpage now but will not change the background color of the web page.
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.getElementByld("background").sytlecolor="blue";
</script>
</body>
</html>
I would recommend you to go through Javascript DOM and HTML
function myFunction(){
document.getElementsByTagName("body")[0].style.background="blue";
}
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
</body>
</html>
Try this:
var isBlue = false;
document.querySelector("button").addEventListener("click", function(){
if(isPurple){
document.body.style.background= "white";
}
else{
document.body.style.background= "blue";
}
isBlue = !isBlue
})
This will not only change the background colour but will create a button that toggles it.
Try this
<body>
<button type="button" onclick="myFunction()">Click to change color</button>
<script>
function myFunction(){
document.body.style.background = "aqua";
}
</script>
</body>
</html>```
background is not a document object. It is an html dom object.
Add this line in HTML Body
<a onclick="changecolor('navy')" id="navy">#0E2A36</a>
You can add customize color in CSS like
#navy{
background:#0E2A36;
}
Then add JavaScript
<script type="text/javascript">
function changecolor(id) {
document.body.style.background = document.getElementById(id).innerHTML;
}
</script>
There are few spelling mistakes but this should explain
1.make the element a variable.
2. set that variable with .style.background = "blue"
spelling mistakes:
sytle = style
getElementByld = getElementById
<html>
<body>
<div id="background">
<button type="button" onclick="myFunction()">Blue</button>
</div>
<script>
function myFunction() {
//get the element
const background = document.getElementById("background");
// set it to blue
background.style.background = "blue";
}
</script>
</body>
</html>
hope this helps.
You have two errors here:
You are selecting an element by id, but that element doesn't exists on your html.
Your javascript have a sintax error. (Missing closing brackets on your function.
You are using the property sytlecolor that doesn't exists (there's a typo on style, and even this way, stylecolor doesn't exists. Use style.backgroundColor instead.
Here's a working example:
<html>
<body id="background">
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.getElementByld("background").style.backgroundColor = "blue";
}
</script>
</body>
</html>
Also if you want to change the body background color, you don't need to put an id on it:
<html>
<body>
<button type="button" onclick="myFunction()"> Blue</button>
<script>
function myFunction(){
document.body.style.backgroundColor = "blue";
}
</script>
</body>
</html>
I'll go with
//On top goes the head
<button type="button">Blue</button>
And then I would create a JS file
var button=document.querySelector('button'),
body =document.querySelector('body');
button.addEventListener('click',function(){
body.style.backgroundColor="blue";
});
That should turn the background blue.
Add id of the specific element whose background you want to change
document.getElementsByTagName('body')[0].style.background='green'
<html>
<body>
<button type="button"
onclick="document.getElementsByTagName('body')[0].style.background='green'">
Click for green backgournd
</button>
<br />
<br /><br />
Another way to do from text box Just for your reference
<br />
<input style="width:100%" type="text" id="txtColorBox" placeholder="enter color name and click button"/>
<br/>
<button type="button"
onclick="document.getElementsByTagName('body')[0].style.background=document.getElementById('txtColorBox').value">
Click for green backgournd
</button>
</body>
</html>
Try this in your function
function myFunction(){
document.body.style.background = "blue";
}
There are two methods to this with vanilla javascript and the second is jQuery.
In your case, you are not using jQuery. So the solution is vanilla javascript.
function myFunction(element) {
element.style.backgroundColor="green";
}
<button type="button" onclick="myFunction()"> Blue</button> //Change web bg
if you need to change the button background. Pass the current pointer.
<button type="button" onclick="myFunction(this)"> Blue</button> //Change buttion bg
bg => background
Hi you could do something like so:
document.getElementById('buttonColor').addEventListener('click', () =>
document.body.style.backgroundColor = "blue"
);
<html>
<body>
<button id="buttonColor">Change Color</button>
</body>
</html>

Trying to Target a button

hi I'm trying to target a button to a div using iframe .. I tried so much but no result...
<html>
<body>
<div id="one">
<button type="submit" onclick="ShowResult()" formtarget="result"> Calculate </button>
</div>
<div id="two">
<iframe name="result"></iframe>
</div>
</body>
javascript:
function ShowResult()
{
document.write("someword");
}
it seems true but when I click the button it open a blank page showing what in the function.. help ??
You are missing alot,
First do not practice "onclick()" anymore.
Second do not practice "document.write" anymore.
I have rewrite your code, enjoy..
HTML
<div id="one">
<button type="submit" id="functionThis" formtarget="result"> Calculate </button>
</div>
<div id="two">
<iframe id="iframe1" name="result"></iframe>
</div>
JS
document.getElementById("functionThis").addEventListener("click", showResult, false);
function showResult() {
var htmlString = "<body>Some Words</body>";
var myIFrame = document.getElementById('iframe1');
myIFrame.src = "javascript:'" + htmlString + "'";
}
Fiddle
working fiddle

Jquery: Get Head and Body Tag Contents from string

I am having a string like below:
<head>
This is the Head
</head>
<body>
<div>
<div>
<p> Body Content <br /></p>
<p> Hello World <br /></p>
</div>
</div>
</body>
It is having both head and body tags. Now I want the contents of head tag and body tag using jquery. Can anyone help?
Well suppose your string variable is "s" so the code is:
var html = document.createElement('html');
html.innerHTML = s;
var head = $(html).find('head:first');
var body = $(html).find('body:first');
Here parse the string to html object and then you will be able to access the elements.
Here is code for the same
var str = "<head>This is the Head</head><body><div><div><p> Body Content <br /> </p><p> Hello World <br /></p> </div></div></body>";
//This will parse the string to HTML
var htmlString = $.parseHTML(str);
//To get the Body content
console.log(htmlString[1].innerHTML);
//To get the HTML Tag Content
console.log(htmlString[0].data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use the regular expression as well, with basic and simple and one more benefit of using that is you can get any other html as well. Please find the code below :
var html = '<head>\
This is the Head\
</head>\
<body>\
<div>\
<div>\
<p> Body Content <br /></p>\
<p> Hello World <br /></p>\
</div>\
</div>\
</body>';
var reg = /\<head[^>]*\>([^]*)\<\/head/m;
var head = html.match( reg )[1];
var reg2 = /\<body[^>]*\>([^]*)\<\/body/m;
var body = html.match( reg2 )[1];
document.getElementById("Head").innerHTML = head;
document.getElementById("body").innerHTML = body;
.head{
border:1px solid red;
}
.body{
border:1px solid red;
}
<div class="head">
<h1>
Heading
</h1><br />
<div id="Head">
</div>
</div> <br />
<div class="body">
<h1>
Body
</h1> <br />
<div id="body">
</div>
</div>
have you considered trying these jquery expressions.
$('head').html();
$('body').html();
for combined text the following jquery expressions.
$('head').text();
$('body').text();

is it possible to hide div when another button is click?

I am trying to hide the div's when different buttons are clicked but I don't know how to. (So when 'Test 1' is clicked it should hide 'Test 2' Div and vice versa) I checked here and on Google but couldn't find an answer for it.
Javascript :
function showHide(divId) {
var theDiv = document.getElementById(divId);
if (theDiv.style.display == "none") {
theDiv.style.display = "";
} else {
theDiv.style.display = "none";
}
}
HTML :
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JSFIDDLE: is not doing it here but works locallyhttp://jsfiddle.net/S5JzK/
<input type="button" onclick="showHide('hidethis')" value="Test It" />
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
function showHide(divId) {
$("#"+divId).toggle();
}
Check the Fiddle http://jsfiddle.net/S5JzK/7/
Please try this, it works well and so simple,
<html>
<head>
<style>
.manageDiv{
display:none;
}
</style>
</head>
<body>
<input type="button" class="testButton" value="Test It" />
<input type="button" class="testButton" value="Test It 2" />
<div id="hidethis2" class="manageDiv">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
</body>
</html>
$(function(){
$(".testButton").on("click", function(){
$("#hidethis2").toggleClass("manageDiv");
});
});
To it work in fiddle, in your example, you need to select (No wrap - in head) on the left.
Look the example below, using pure javascript:
HTML
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JAVASCRIPT
function showHide(divId) {
/* Hide all divs */
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
http://jsfiddle.net/S5JzK/9/
ANOTHER JAVASCRIPT EXAMPLE
function showHide(divId) {
/* Hide the divs that you want */
var div1 = document.getElementById('#hidethis');
var div2 = document.getElementById('#hidethis2');
div1.style.display = "none";
div2.style.display = "none";
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
Using JQuery:
function showHideDiv(divId, bShow) {
if (bShow) {
$("#" + divId).show();
} else {
$("#" + divId).hide();
}
}
your code seems fine. are you sure you enter the function upon click? try adding a breakpoint using developer tools or an alert.
Anyways, I see you tagged this post with jquery. you can you it to do the task more elegantly.
$("#" + theDiv).hide();
or for showing it:
$("#" + theDiv).show();
"JSFIDDLE: is not doing it here but works locally"
Yes, because by default jsfiddle wraps your JS in an onload handler, which means the function declaration is local to that handler. Inline html attribute event handlers like your onclick="showHide('hidethis')" can only call global functions.
Under jsfiddle's Frameworks & Extensions heading there's a drop-down where you can change the default "onload" to "No wrap - in head" (or "No wrap - in body"). That'll make your function declaration global as in your local implementation.
Demo: http://jsfiddle.net/S5JzK/8/

Prinitng issue in jQuery

<html>
<head>
<script type="text/javascript">
function PrintElem()
{
var mydiv1 = document.getElementById("div1");
var mydiv2= mydiv.getElementsByTagName("div2");
printTheDivs(mydiv1, mydiv2);
}
function printTheDivs (d1,d2)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><body>' + d1.innerHTML + '</body></html>');
//Here I want to show the Images in this window.
$(d2).print();
//but want to print the Div2 Images I’m using the jquery.print.js plugin but not working. It is printing complete page. How to accomplish the task with multiple Browsers.
}
</script>
</head>
<body>
<div id="div1">
<img src=”image1.jpg”/>
<img src=”image2.jpg”/>
<img src=”image3.jpg”/>
<img src=”image4.jpg”/>
<img src=”image5.jpg”/>
</div>
<div id="div2">
<img src=”image6.jpg”/>
<img src=”image7.jpg”/>
<img src=”image8.jpg”/>
<img src=”image9.jpg”/>
<img src=”image10.jpg”/>
</div>
<input type="button" value="Print Div" onclick="PrintElem()" />
</body>
</html>
I want to show one div using window.open() and print another div. I’m using the jquery.print.js plugin but not working. It is printing complete page. How to accomplish the task with multiple Browsers. Please help me. Thanks in advance.
You can print particular div
<div id="divid">test</div>
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
printDiv('divid')
check here http://jsfiddle.net/jrhp8/

Categories

Resources