How to save custom style rule to LocalStorage? - javascript
Button works, but after refreshing the page, the rule is gone.
My code:
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
};
You can do it like this:
localStorage.setItem("your item name or id goes here", "value goes here");
So for what you want it could be like this:
localStorage.setItem("size", "15px");
Then you have to get it when the window loads:
window.onload = function(){
var nav = document.getElementById(navbar);
var finalSize = localStorage.getItem('size');
nav.style.letterSpacing = finalSize;
}
Also, give your navbar or element and ID of "navbar".
Also, there is no need to create a style tag. You can do that with style
in javascript.
Shouldn't that be the normal behavior, refreshing the page should reset it to the initial state?
If you want to use LocalStorage for saving the style rules, you can
// Button
let spaces = document.getElementById("spaces");
spaces.onclick = () => {
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
localStorage.setItem("addNavbarRule", true)
};
// on page load
window.onload = function(){
if (localStorage.getItem("addNavbarRule")){
sheet.insertRule(".navbar {letter-spacing: 3px !important;}", 0);
}
}
Related
assistance regarding fetching and displaying a display:none back to my page
this is my code: const clcBtn = document.getElementById("calcButton"); let clcInput = document.getElementById("calcInput"); const result = document.getElementById('paragraph'); const loader = document.getElementById('spinner'); clcBtn.addEventListener("click", calcFunc); function calcFunc() { loader.classList.add("display") fetch(`http://localhost:5050/fibonacci/`).then(function (response) { return response.json().then(function (data) { result.innerHTML = data.clcInput.value; // i want to get the input value from the input field and the server to calculate it and present it to the user. }); }); } basically what i want to do, is to add the value the user types in to the innerHTML paragraph id name. and then i want to make the button react to the click and re-display the "loader" (which i gave it display:none in the CSS file) and then, i need to make the button to display an error message if the input is higher than 50. what i have tried to do: inside the clcBtn.addEventListener("click", calcFunc); function calcFunc() { i have tried to add: loader.classlist.add("display") and inside return response.json().then(function (data) { result.innerHTML = data.clcInput.value; i have tried to add and change it to: clcInput.value = innerHTML.result; what am i doing wrong? what is wrong with my syntax and what is the order i need to write everything? thank you!!!
If i understand correctly what is you need, you should look at the small snippets I did below. It show a loader during the API Call and hide it when you get the result as well as updating the info paragraph depending on the value you typed. The main thing I recommend you changing in order for your code to work properly is not adding or removing a class to your spinner element to hide it and show it, but simply changing directly it's style by using loader.style.display = "value" Hope it helps. const clcBtn = document.getElementById("calcButton"); let clcInput = document.getElementById("calcInput"); const result = document.getElementById('paragraph'); const loader = document.getElementById('spinner'); clcBtn.addEventListener("click", calcFunc); function calcFunc() { paragraph.innerText= ""; loader.style.display = "block"; // TimeOut to simulate API Call setTimeout(function() { loader.style.display = "none"; if (clcInput.value > 50) { paragraph.innerText = clcInput.value + " - Error, value too high"; } else { paragraph.innerText = clcInput.value + " - Value correct"; } }, 2000); } #spinner { width: 50px; height: 50px; border-radius: 50%; background-color: white; border: 5px solid black; display: none; } <input type="number" id="calcInput" /> <button id="calcButton">calcButton</button> <div id="spinner"></div> <p id="paragraph"></p>
Mouse over the <a> tag
There is a prompt in the lower left corner When I put the mouse over the tag, and can u tell me how to forbid this phenomenon.enter image description here
As commented, the behaviour that you wish to stop is a browser's feature. To avoid this, you will have to simulate anchor's behaviour on your own but as you said you have many anchors and you cannot manually convert them to buttons, you can try following code: function maskAnchors() { var els = document.querySelectorAll('a[href]'); console.log("Anchors Found: ", els.length) for (var i = 0; i < els.length; i++) { els[i].setAttribute("data-url", els[i].getAttribute('href')); els[i].removeAttribute("href"); els[i].addEventListener("click", handleClick) } } function handleClick() { var url = this.getAttribute('data-url'); window.open(url) } document.getElementById('btnAdd').addEventListener("click", function() { var container = document.querySelector('.content'); var link = document.createElement('a') link.href = "www.google.com"; link.textContent = "This is a newly added link"; container.append(link) }) document.getElementById('btnMask').addEventListener("click", maskAnchors) window.addEventListener('load', maskAnchors) .maskedAnchor { color: -webkit-link; text-decoration: underline; cursor: auto; } <div class="content"> Google Facebook StackOverflow YouTube Example <a>blabla</a> </div> <button id="btnAdd">Add Anchor</button> <button id="btnMask">Run masking</button> Note: Removing href will change styling. You will also have to do that manually. This will not handle any anchors added dynamically after execution of this function. You will have to call this function again. I have optimised function to only fetch anchors that has href Hope it helps!
How can I prevent pop up box when hovering over link?
I am trying to fix my webpage. I have a small problem. When I hover over my link this pop up box covers the text. What would be the best method to fix this? Thanks for any tips I have added an img below for better understanding. http://imgur.com/a/Nwqv4 <html> <head> <title>010101010101010110101010010101010101010110101010</title> <link rel="shortcut icon" type="image/png" href="red.png"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <style type="text/css"> body { background-color: black } #console { font-family: courier, monospace; color: white; width:750px; margin-left:auto; margin-right:auto; margin-top:100px; font-size:14px; } #x { color: red; } #d { color: #0f0; } a { color: white; text-decoration: none; } #a { color: #0f0; } #c { color: #0bc; } #b { color: #ff0096; } #green { color: green; } #red { color: red; } </style> </head> <body> <script type="text/javascript"> var Typer={ text: null, accessCountimer:null, index:0, // current cursor position speed:1, // speed of the Typer file:"", //file, must be setted accessCount:0, //times alt is pressed for Access Granted deniedCount:0, //times caps is pressed for Access Denied init: function(){// inizialize Hacker Typer accessCountimer=setInterval(function(){Typer.updLstChr();},600); // inizialize timer for blinking cursor $.get(Typer.file,function(data){// get the text file Typer.text=data;// save the textfile in Typer.text Typer.text = Typer.text.slice(0, Typer.text.length-1); }); }, content:function(){ return $("#console").html();// get console content }, write:function(str){// append to console content $("#console").append(str); return false; }, makeAccess:function(){//create Access Granted popUp FIXME: popup is on top of the page and doesn't show is the page is scrolled Typer.hidepop(); // hide all popups Typer.accessCount=0; //reset count var ddiv=$("<div id='gran'>").html(""); // create new blank div and id "gran" ddiv.addClass("accessGranted"); // add class to the div ddiv.html("<h1>ACCESS GRANTED</h1>"); // set content of div $(document.body).prepend(ddiv); // prepend div to body return false; }, makeDenied:function(){//create Access Denied popUp FIXME: popup is on top of the page and doesn't show is the page is scrolled Typer.hidepop(); // hide all popups Typer.deniedCount=0; //reset count var ddiv=$("<div id='deni'>").html(""); // create new blank div and id "deni" ddiv.addClass("accessDenied");// add class to the div ddiv.html("<h1>ACCESS DENIED</h1>");// set content of div $(document.body).prepend(ddiv);// prepend div to body return false; }, hidepop:function(){// remove all existing popups $("#deni").remove(); $("#gran").remove(); }, addText:function(key){//Main function to add the code if(key.keyCode==18){// key 18 = alt key Typer.accessCount++; //increase counter if(Typer.accessCount>=3){// if it's presed 3 times Typer.makeAccess(); // make access popup } }else if(key.keyCode==20){// key 20 = caps lock Typer.deniedCount++; // increase counter if(Typer.deniedCount>=3){ // if it's pressed 3 times Typer.makeDenied(); // make denied popup } }else if(key.keyCode==27){ // key 27 = esc key Typer.hidepop(); // hide all popups }else if(Typer.text){ // otherway if text is loaded var cont=Typer.content(); // get the console content if(cont.substring(cont.length-1,cont.length)=="|") // if the last char is the blinking cursor $("#console").html($("#console").html().substring(0,cont.length-1)); // remove it before adding the text if(key.keyCode!=8){ // if key is not backspace Typer.index+=Typer.speed; // add to the index the speed }else{ if(Typer.index>0) // else if index is not less than 0 Typer.index-=Typer.speed;// remove speed for deleting text } var text=Typer.text.substring(0,Typer.index)// parse the text for stripping html enities var rtn= new RegExp("\n", "g"); // newline regex $("#console").html(text.replace(rtn,"<br/>"));// replace newline chars with br, tabs with 4 space and blanks with an html blank window.scrollBy(0,0); // scroll to make sure bottom is always visible } if ( key.preventDefault && key.keyCode != 122 ) { // prevent F11(fullscreen) from being blocked key.preventDefault() }; if(key.keyCode != 122){ // otherway prevent keys default behavior key.returnValue = false; } }, updLstChr:function(){ // blinking cursor var cont=this.content(); // get console if(cont.substring(cont.length-1,cont.length)=="|") // if last char is the cursor $("#console").html($("#console").html().substring(0,cont.length-1)); // remove it else this.write("|"); // else write it } } function replaceUrls(text) { var http = text.indexOf("http://"); var space = text.indexOf(".me ", http); if (space != -1) { var url = text.slice(http, space-1); return text.replace(url, "" + url + ""); } else { return text } } Typer.speed=20; Typer.file="index.txt"; Typer.init(); var timer = setInterval("t();", 30); function t() { Typer.addText({"keyCode": 123748}); if (Typer.index > Typer.text.length) { clearInterval(timer); } } </script> <div id="console"></div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-610661-7']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html> .txt <span id="green"> iIYVVVVXVVVVVVVVVYVYVYYVYYYYIIIIYYYIYVVVYYYYYYYYYVVYVVVVXVVVVVYI+. tYVXXXXXXVXXXXVVVYVVVVVVVVVVVVYVVVVVVVVVVVVVVVVVXXXXXVXXXXXXXVVYi. iYXRXRRRXXXXXXXXXXXVVXVXVVVVVVVVXXXVXVVXXXXXXXXXXXXXXRRRRRRRRRXVi. tVRRRRRRRRRRRRRRRXRXXXXXXXXXXXXXXRRXXXXRRRRXXXXXXXRRRRRRRRRRRRXV+. tVRRBBBRMBRRRRRRRRRXXRRRRRXt=+;;;;;==iVXRRRRXXXXRRRRRRRRMMBRRRRXi, tVRRBMBBMMBBBBBMBBRBBBRBX++=++;;;;;;:;;;IRRRRXXRRRBBBBBBMMBBBRRXi, iVRMMMMMMMMMMMMMMBRBBMMV==iIVYIi=;;;;:::;;XRRRRRRBBMMMMMMMMBBRRXi. iVRMMMMMMMMMMMMMMMMMMMY;IBWWWWMMXYi=;:::::;RBBBMMMMMMMMMMMMMMBBXi, +VRMMRBMMMMMMMMMMMMMMY+;VMMMMMMMRXIi=;:::::=VVXXXRRRMMMMMMMMBBMXi; =tYYVVVXRRRXXRBMMMMMV+;=RBBMMMXVXXVYt;::::::ttYYVYVVRMMMMMMBXXVI+= ;=tIYYVYYYYYYVVVMMMBt=;;+i=IBi+t==;;i;::::::+iitIIttYRMMMMMRXVVI=; ;=IIIIYYYIIIIttIYItIt;;=VVYXBIVRXVVXI;::::::;+iitttttVMMBRRRVVVI+, ;+++tttIttttiiii+i++==;;RMMMBXXMMMXI+;::::::;+ittttitYVXVYYIYVIi;; ;===iiittiiIitiii++;;;;:IVRVi=iBXVIi;::::::::;==+++++iiittii+++=;; ;;==+iiiiiiiiii+++=;;;;;;VYVIiiiVVt+;::::::::;++++++++++iti++++=;; ;;=++iiii+i+++++iii==;;;::tXYIIYIi+=;:::::,::;+++++++++++++++++=;; ;;;+==+ii+++++iiiiit=;;:::::=====;;;::::::::::+++i+++++++++i+++;;; ;;;==+=+iiiiitttIIII+;;;:,::,;;;;:;=;;;::,::::=++++++++==++++++;;; :;====+tittiiittttti+;;::::,:=Ytiiiiti=;:::::,:;;==ii+ittItii+==;; ;;+iiittIti+ii;;===;;:;::::;+IVXVVVVVVt;;;;;::::;;===;+IIiiti=;;;; ;=++++iIti+ii+=;;;=;:::;;+VXBMMBBBBBBXY=;=;;:::::;=iYVIIttii++;;;; ;;++iiiItttIi+++=;;:::;=iBMMMMMMMMMMMXI==;;,::;;:;;=+itIttIIti+;;; ;=+++++i+tYIIiii;:,::;itXMMMMMMMMMMMBXti==;:;++=;:::::;=+iittti+;; ;;+ii+ii+iitiIi;::::;iXBMMMMMWWWWWMMBXti+ii=;::::,,,,:::=;==+tI+;; ;;iiiitItttti;:::;::=+itYXXMWWWWWWMBYt+;;::,,,,,,,,,,,,,:==;==;;;; :;=iIIIttIt+:;:::;;;==;+=+iiittttti+;;:,:,,,,::,,,,,,,,:::;=;==::; ;::=+ittiii=;:::::;;;:;:;=++==;;==;:,,,,,,:;::::,,,,,,,,::;==;;::; :::;+iiiii=;::::,:;:::::;;:;;::;:::,,,,,,,:::;=;;;:,,,,,:::;;::::; :;;iIIIIII=;:::,:::::::,::::,:::,,,,,,,,,,,:;;=;:,,,,,,::::;=;:::; :;==++ii+;;;:::::::::::,,,,,,::,,,,,,,,,,,::::,,,,,,,,,,:,:::::::; ::;;=+=;;;:::;;::,,,,,,,,,,,,,,,,,,,,,,,,,:,,,,,,,,,,,,,,,,,:::::; ::;=;;;:;:::;;;;::,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,::,,::::; :;;:;::::::,::,,:,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,:::; :::::::::::;;;:,,,,,,,,,,,,,...,...,,,.,,,,,,,,,,,,.,,,,,,,,,,,,:; ::::::::;=;;;;;::,,,,,,,,,,,.......,...,,,,,,,,,,,,.,,,,,,,,,,,,,; :::::,,:;=;;;;;;;iVXXXVt+:,,....,,,,....,.,,,,,,,.,.....,,,,,,,,:; :,,::,,:::;;;;;;=IVVVXXXXVXVt:,,,,,..,..,,,,.,,,,,..,.,,,,,,,,,,,; ::,::,,,:,:::::,::;=iIYVXVVVVIYIi;,,.,.,,,::,,,,,,,,,,,,,,,,,,,,,. :,,,,,,,,,,,,,,,,::;+itIIIIIIi:;;i++=;;;;;;;;;::,,,...,,..,,,,,,,. :,,,,,,,,,,,,,,=iitVYi++iitt==it;;:;;;;::;;::::,,,......,,,,,,,::. ::,,,,,,,,,,,,,++iiIVIi=;;=;+i;:;+:::,,,,,,,,,,,,,.....,,,,,,,,::, ,,,,,,,,,,,,,,,;=+it=:::,,,,,,,,,,.,......,,.,..........,,,,,,,,:: :,,,,,,,,,,,,,,,,:=:,,,,,,,,,,,,,,......................,.,,.,.,,: :,,,,,,,,,,,,,,,,,:,,,,,,,,,,..,........................,..,...,,: ,,,,,,,,,,,,,,,,,,,.....................................,.......,, ,,,,,,,,,.,,,,,,,...............................................,, itittiiiii+=++=;;=iiiiiiittiiiiii+iii===;++iiitiiiiiii+=====+ii=+i </span> Let us go for a journey....
It's browser's status bar and you can't turn that off. In most cases you won't see it and it only shows up when it needs to. Even if you didn't want it to appear every time you hover over a link, it's one feature that you just can't turn off. I'd suggest you to move its position to the right. <a style="float:right;" href="journey.html">Let us go for a journey....</a>
Chrome reads the HREF attribute from your link to display the link in the status bar. So if you remove the HREF from your A tags, the status bar will not be displayed. However the link won't work either, :). That's why you can create an event handler on MouseOver to address that and keep your links working. $("body").on('mouseover', 'a', function (e) { var $link = $(this), href = $link.attr('href') || $link.data("href"); $link.off('click.chrome'); $link.on('click.chrome', function () { window.location.href = href; }) .attr('data-href', href) //keeps track of the href value .css({ cursor: 'pointer' }) .removeAttr('href'); // <- this is what stops Chrome to display status bar }); You might run in extra issues, like disabled links or links that have other event handlers. In this case, you can tweak your selector to 'a:not(.disabled)' or perhaps just add this delegation to known elements with the css class ".disable-status", therefore your selector would be: "a.disable-status".
I used a onclick to fix this, So right now my code is <div id='link'> <a id='pro1' onclick="location.href='./pages/langs.html';"></a> </div> tht creates another way to use a link without the bar at the bottom, Youd have to use CSS to remove Text Deco ect, or just config links but it works great overall. For you, <a onclick="location.href='journey.html';">Let us go for a journey....</a> CREATES: Let us go for a journey....
keep link style when changing page Javascript
im using Smarty and php4(cant upgrade =( ).On my site on the left, i have a navigation-column with all my links. I want the link which i click to change color to RED and STAY RED until i click another link. I already found something when googling but i cant get it to work tough everyone says it runs perfectly :/..... the script changes the color to red when i click on a link but fails to keep the color RED after my url changes. {literal} <script type="text/javascript"> // first component: non-active link-color // second component: active link-color var arrColor = new Array("#404040","#e40624"); var lnkOldID = ""; var lnkOldColor; // get object-type IE = document.all&&!window.opera; DOM = document.getElementById&&!IE; function activeLink(lnkID){ // declare object myObj = (IE)?document.all[lnkID]:document.getElementById(lnkID); // if no link is chosen if(lnkOldID == ""){ lnkOldID = lnkID; // remember cur. ID lnkOldColor = arrColor[0]; // remember cur. color myObj.style.color = arrColor[1]; // change color }else{ // if current link is not active link if(lnkOldID != lnkID){ // declare object var myOldObj = (IE)?document.all[lnkOldID]:document.getElementById(lnkOldID); myOldObj.style.color = lnkOldColor; // set color to non-activelink color myObj.style.color = arrColor[1]; // setcolor to activelinkcolor lnkOldID = lnkID; // remember cur. ID lnkOldColor = arrColor[0]; // remember cur. color } } } </script> {/literal} <a onClick="activeLink('verteilung_prios')" id="verteilung_prios" href="?n=navigation_pm&a=verteilung_prios">Verteilung Prios</a> <a onClick="activeLink('histogramm_reaktionszeiten')" id="histogramm_reaktionszeiten" href="?n=navigation_pm&a=histogramm_reaktionszeiten">Histogramm Reaktionszeiten</a>
How about changing class? sample script : function toggleColor(obj) { var redObjs = document.getElementsByClassName('red'); for ( var i = 0; i < redObjs.length; i++ ) { redObjs[i].className = ''; } obj.className = 'red'; } add class function when page refresh execute in document.onload function initClass() { // get now url //var nowUrl = document.location.href; // dummy url var nowUrl = 'http://fiddle.jshell.net/now/'; // get elements that have 'navi' class var naviObjs = document.getElementsByClassName('navi'); for ( var i = 0; i < naviObjs.length; i++ ) { if ( naviObjs[i].href == nowUrl ) { // check url //alert(naviObjs[i].className); // add 'red' class naviObjs[i].className += ' red'; } } } css : a:visited { color: #404040; } a.red { color: #e40624; }
How to print only a selected HTML element?
I am trying to implement a print feature in HTML. I know I can print the whole page with window.print(), but how do I print only a specific page element? For example a particular <DIV>Some text to print</DIV>.
You could use a print specific CSS stylesheet and hide everything but what you want printed. <div class="no-print">I won't print</div><div class="something-else">I will!</div> Just the no-print class will be hidden, but anything with a print class will show. <style type="text/css" media="print"> .no-print { display: none; } </style>
If you are familiar to jQuery, you can use jQuery Print Element plugin like this: $('SelectorToPrint').printElement();
Created something generic to use on any HTML element HTMLElement.prototype.printMe = printMe; function printMe(query){ var myframe = document.createElement('IFRAME'); myframe.domain = document.domain; myframe.style.position = "absolute"; myframe.style.top = "-10000px"; document.body.appendChild(myframe); myframe.contentDocument.write(this.innerHTML) ; setTimeout(function(){ myframe.focus(); myframe.contentWindow.print(); myframe.parentNode.removeChild(myframe) ;// remove frame },3000); // wait for images to load inside iframe window.focus(); } Usage: document.getElementById('xyz').printMe(); document.getElementsByClassName('xyz')[0].printMe(); Hope this help Regards Gaurav Khurana
Simple html and pure javascript works best. Parameter "this" refers to current id, so that function is universal for all ids. By using "ref.textContent" instead of "ref.innerHTML" you can extract only textual content for printing. html body: <div id="monitor" onclick="idElementPrint(this)">element to print <img src="example.jpg" width="200"> </div> pure javascript: /*or: monitor.textContent = "click me to print content"; const imga = new Image(200); //width imga.src = "./example.jpg"; monitor.appendChild(imga); */ const idElementPrint = ref => { const iframe = document.createElement("iframe"); iframe.style.display = "none"; document.body.appendChild(iframe); const pri = iframe.contentWindow; pri.document.open(); pri.document.write(ref.innerHTML); pri.document.close(); pri.focus(); pri.print(); pri.onafterprint = () => { document.body.removeChild(iframe); } }
If you are using JQuery, you can use clone to do the following: function printElement(e) { var ifr = document.createElement('iframe'); ifr.style='height: 0px; width: 0px; position: absolute' document.body.appendChild(ifr); $(e).clone().appendTo(ifr.contentDocument.body); ifr.contentWindow.print(); ifr.parentElement.removeChild(ifr); } and use like so: printElement(document.getElementById('myElementToPrint'))
If I understood you well you can use CSS3 to print your selected HTML element. #media print { body.print-element *:not(.print) { display: none; } } Notice, that you just need a selector. This allows you to easily print an element or the entire page using CSS classes. Here you can check a working example: https://jsfiddle.net/gengns/d50m8ztu/
If you're using bootstrap, just add classname d-print-none to the elements you don't want to display in print
I found a solution that doesn't have the problems other solutions have. It copies the printed element to the body, and is fairly elegant and general: CSS: #media print { body *:not(.printable, .printable *) { // hide everything but printable elements and their children display: none; } } JS: function printElement(e) { let cloned = e.cloneNode(true); document.body.appendChild(cloned); cloned.classList.add("printable"); window.print(); document.body.removeChild(cloned); } The only limitation is that the element loses styles it inherited from its previous parents. But it works on arbitrary elements in the document structure
If you need to print the HTML element with pure JS, you can open a window that contains only the element you want to print (without any HTML-markup). For instance, you can print the image itself without wrapping it in any HTML by opening this image in a new window as a file. Note: 'visible=none' doesn't actually make the window invisible, but it allows to open it as a separate window (not a tab). afterprint event allows us to close the window when the printing dialog is closed. event.target points to the opened window instance. Note: afterprint MUST be assigned before calling .print(), otherwise it would not be called. let win = window.open('/absolute/image/path.jpg', '__blank', 'visible=none'); win.addEventListener('afterprint', event => event.target.close() ); win.print();
Printing an Html or a Selected Html is easy using Print.Js Add Print.Js Library http://printjs.crabbly.com/ <form method="post" action="#" id="printJS-form"> ... </form> <button type="button" onclick="printJS('printJS-form', 'html')"> Print Form </button>
Add this method function printDiv(divName) { let specific_element = document.getElementById(divName).innerHTML; let original_elements = document.body.innerHTML; document.body.innerHTML = specific_element; window.print(); document.body.innerHTML = original_elements; }
This implementation will create and apply an ad-hoc temporary style that hides all the elements on print media except the one that we want to print. After the printing the temporary style is removed, so your document will get back to its initial state. Feel free to adjust the ad-hoc style (like papar size, margins, etc) to fit your needs. /** * #description Print the given element using browser built-in function * #param {HTMLElement} element */ function printElement(element) { if (!element) { throw new Error(`Invalid print target element`); } const printWrapper = "print-wrapper"; const printElement = "print-element"; const css = ` body.${printWrapper} *:not(.${printElement}) { visibility:hidden; } body.${printWrapper} .${printElement} { width: 210mm; height: 297mm; left:0; top:0; position:fixed; } body.${printWrapper} .${printElement} * { visibility:initial; margin: 0; } `; const head = document.getElementsByTagName("head")[0]; const style = document.createElement("style"); style.setAttribute("type", "text/css"); style.setAttribute("media", "print"); if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); document.body.classList.add(printWrapper); element.classList.add(printElement); window.print(); document.body.classList.remove(printWrapper); element.classList.remove(printElement); head.removeChild(style); }
The simplest way to do it is: elem = document.getElementById('elem').outerHTML orig = document.documentElement.outerHTML document.documentElement.outerHTML=elem print() document.documentElement.outerHTML = orig
function printDomElement(element) { element.classList.add("printCss"); let printId = "printSvgId"; let name = ".printCss"; let rules = "-webkit-print-color-adjust:exact;height:100%;width:100%;position:fixed;top:0;left:0;margin:0;"; var style = document.createElement('style'); style.id = printId; style.media = "print"; document.getElementsByTagName('head')[0].appendChild(style); if (!(style.sheet || {}).insertRule)(style.styleSheet || style.sheet).addRule(name, rules); else style.sheet.insertRule(name + "{" + rules + "}", 0); window.print(); setTimeout(() => { element.classList.remove("printCss"); let elem = document.getElementById(printId); if (elem) elem.remove(); }, 500); }
Set the style of the element you want to print to position:fixed,then make it cover the whole page.
Here is another (perhaps a more modern?) solution: <link rel="stylesheet" media="print" href="print.css">