I'm a bit of a JavaScript newbie, but I do know SOME basics, so I thought I could handle this. I'm trying to show specific DIVS when a page loads, but have them easily hideable when another DIV is clicked on.
I found something similar to this code somewhere and started with it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
function show( id ) {
document.getElementById(id).style.display = 'block';
}
function hide( id ) {
document.getElementById(id).style.display = 'none';
}
</script>
</head>
<body>
box 1</p>
<div id="box1">
<p>Text of box 1</p>
</div>
box 2</p>
<div id="box2" style="display:none;">
<p>Text of box 2</p>
</div>
box 3</p>
<div id="box3" style="display:none;">
<p>Text of box 3</p>
</div>
box 4</p>
<div id="box4" style="display:none;">
<p>Text of box 4 </p>
</div>
</body>
</html>
Great. This already does MOST of what I want it to do, except that I want it to re-show the hidden box titles when you click on a new box title, and hide the content of any box that is open.
So I tried this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
function show( id ) {
document.getElementById(id).style.display = 'block';
}
function hide( id ) {
document.getElementById(id).style.display = 'none';
}
</script>
</head>
<body>
box 1</p>
<div id="box1">
<p>Text of box 1</p>
</div>
box 2</p>
<div id="box2" style="display:none;">
<p>Text of box 2</p>
</div>
box 3</p>
<div id="box3" style="display:none;">
<p>Text of box 3</p>
</div>
box 4</p>
<div id="box4" style="display:none;">
<p>Text of box 4 </p>
</div>
</body>
</html>
Which causes NOTHING to work. I'm guessing I have some syntax wrong or something, but I'm not sure what it is. I tried it a few different ways. I've seen multiple things called that way before.
If anyone can help me, I'm guessing it's a pretty simple solution. Thanks in advance.
Your show and hide functions are not designed to handle arrays of variables. You will need to cycle through an array that you feed to the function and hide/show each element in it.
So your show function will look something like this:
function show(ids) {
for(var i=0, l=ids.length; i < l; i++ } {
document.getElementById(ids[i]).style.display = 'block';
}
}
You are passing arrays to your functions and they are being processed as strings. I just changed that, and leveraged jQuery language instead of the lengthy JavaScript language. See a working Sample.
JS
function show( id ) {
for (var x=0; x<id.length; x++)
$('#' + id[x]).show();
}
function hide( id ) {
for (var x=0; x<id.length; x++)
$('#' + id[x]).hide();
}
UPDATE
my bad. Could have sworn I saw a jQuery tag.
function show( ids ) {
foreach (id in ids){
document.getElementById(id).style.display = 'block';
}
}
function hide( ids ) {
foreach (id in ids){
document.getElementById(id).style.display = 'none';
}
}
Related
I am learning to create an element dynamically in an html page using javascript. In this code I am trying to create a simple "h6" inside "div-1".
<!DOCTYPE html>
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1"></div>
<script>
function constructElement(){
var elem = document.createElement("h6");
elem.innerText("Dynamically added text.")
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
</html>
there are two mistakes in your code
the first is that you used wrong "id" name div-1 instead of div1
also, innerText isn't a function
this is the code after the fix :)
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1">
</div>
<script>
function constructElement() {
var elem = document.createElement("h6");
elem.innerText = "Dynamically added text."
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1">
</div>
<script>
function constructElement(){
var elem = document.createElement("h6");
elem.innerText= "Dynamically added text.";
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
Set the text content of a node: node.innerText = text
function constructElement(){
var elem = document.createElement("h6");
elem.innerText ="Dynamically added text."
document.getElementById("div-1").appendChild(elem);
}
This is directly not your answer but the algorithm is very similar
https://stackoverflow.com/a/56489422/10941112
(For the part of modals please put your own elements)
In case you need further clarification feel free to ask as this is not your direct answer
Also sorry to say but the question is a duplicate of -
Dynamically creating HTML elements using Javascript?
This question already has answers here:
How to insert an element after another element in JavaScript without using a library?
(20 answers)
Closed 6 years ago.
I want to create a new element (a div) but instead of creating it as the last element, I want to create it between two elements. I created this simplified code of what I want to do:
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function createDiv() {
var newDiv = document.createElement("div");
var txt = document.createTextNode("I'm the second div");
newDiv.appendChild(txt);
document.body.appendChild(newDiv);
}
</script>
</head>
<body>
<div class="first">
<p>I'm the first div</p>
</div>
<div class="third">
<p>I'm the third div</p>
</div>
<button type="button" name="button" onclick="createDiv()">Create the second Div</button>
</body>
</html>
Keep in mind that I want to use DOM only, not jQuery.
You can do the following by inserting before the third div
function createDiv() {
var newDiv = document.createElement("div");
var txt = document.createTextNode("I'm the second div");
newDiv.appendChild(txt);
var thirdDiv = document.getElementById("thrid");
thirdDiv.parentNode.insertBefore(newDiv, thirdDiv);
}
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="first">
<p>I'm the first div</p>
</div>
<div id="thrid" class="third">
<p>I'm the third div</p>
</div>
<button type="button" name="button" onclick="createDiv()">Create the second Div</button>
</body>
</html>
How do you assign a class dynamically to a paragraph (via javascript/CSS) IF the paragraph contains the wording "Time Recorded:"?
You'll notice that I have manually assigned the paragraph with class class="dyncontent".
However, I'd like to dynamically assign this class to any paragraph tag which contain the words "Time Recorded:".
<!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=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">')
document.write('.dyncontent{display:none;}')
document.write('</style>')
}
</script>
<div class="right">
<ul>
<li class="say agent public">
<p>Description line 1</p>
<p class="dyncontent">Time Recorded: 5MIN(S)</p>
<p>Another description line</p>
</li>
</ul>
</div>
</body>
</html>
You could use jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(function(){
$("p:contains('Time Recorded:')").addClass('dyncontents');
});
</script>
$("p").each(function(ele) {if (this.html().indexOf('TimeRecorded') > 1) {$(this).addClass('dyncontent'))}});
I'd do indexOf because it will match easier than innerText
var allP = document.getElementsByTagName('p'),
pLength = allP.length;
while(pLength--){
if(allP[pLength].innerHTML.indexOf('Time Recorded') != -1){
allP[pLength].addClass('dycontents');
}
}
To explain: first you get all the <p> in the document. Then you loop through them. If any of them contain text of Time Recorded you add your class to it.
The following is solution without Jquery
o = document.getElementsByTagName('p');
for (i = 0; i < o.length; i++) {
if (o[i].innerText.indexOf('Time Recorded:') != -1) {
o[i].className = 'theClassYouWant';
}
}
I know this is a really simple question, but I need to replace this bit of text in a paragraph with a variable every time an even fires.
The markup looks like this
"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>Untitled Document</title>
<style>
#container {width:100%; text-align:center; }
#heading {width:100%; text-align:center; }
</style>
</head>
<div id="heading">
<h1>hello</h1>
</div>
<body>
<div id="container">
<textarea name="mytextarea" cols="60" rows="40"></textarea>
</div>
</body>
</html>
What I need is where it says "hello" in the tags, is for that to be a variable that van be replaced by a string that I will generate.
You could create a function that looks something like this.
function replaceTitle (replaceText) {
document.getElementById("heading").getElementsByTagName("h1")[0].innerHTML = replaceText;
}
If you are using jQuery it could look more like this.
function replaceTitle (replaceText) {
$("#heading h1").html(replaceText);
}
Then you call the function like this
replaceText(yourVariable);
It would probably be better to give your <h1> tag an id or a class so you can reference it directly, but I am going to assume that you have good reason for not doing so.
One example on how can be simple things made complicated :)
javascript:
// simple way:
function replace_text(text) {
var heading = document.getElementById('heading');
heading.innerHTML = '<h1>' + text + '</h1>';
}
// complicated way:
function replace_text2(text) {
var heading = document.getElementById('heading');
var node = heading.childNodes[0];
while ( node && node.nodeType!=1 && node.tagName!='H1' ){
//console.log(node.nodeType,node);
node = node.nextSibling;
}
if (node) {
node.replaceChild(document.createTextNode(text),node.childNodes[0]);
}
}
html:
<input type="button" onclick="replace_text('HELLO 1!');" value="Replace 1st text" />
<input type="button" onclick="replace_text2('HELLO 2!');" value="Replace 2nd text" />
The script is here.
The JavaScript code window.print() can print the current HTML page.
If I have a div in an HTML page (for example, a page rendered from an ASP.NET MVC view), then I want to print the div only.
Is there any jQuery unobtrusive JavaScript or normal JavaScript code to implement this request?
Making it more clear, suppose the rendered HTML page is like:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head" runat="server">
<title>
<asp:ContentPlaceHolder runat="server" ID="TitleContent" />
</title>
</head>
<body>
<div id="div1" class="div1">....</div>
<div id="div2" class="div2">....</div>
<div id="div3" class="div3">....</div>
<div id="div4" class="div4">....</div>
<div id="div4" class="div4">....</div>
<p>
<input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
</p>
</body>
</html>
Then I want to click on the Print button, only printing div3.
I would go about it somewhat like this:
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> Print<br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> Print<br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> Print<br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
Along the same lines as some of the suggestions you would need to do at least the following:
Load some CSS dynamically through JavaScript
Craft some print-specific CSS rules
Apply your fancy CSS rules through JavaScript
An example CSS could be as simple as this:
#media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.
<!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>Print Portion Example</title>
<style type="text/css">
#media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
Try this JavaScript code:
function printout() {
var newWindow = window.open();
newWindow.document.write(document.getElementById("output").innerHTML);
newWindow.print();
}
<div id="invocieContainer">
<div class="row">
...Your html Page content here....
</div>
</div>
<script src="/Scripts/printThis.js"></script>
<script>
$(document).on("click", "#btnPrint", function(e) {
e.preventDefault();
e.stopPropagation();
$("#invocieContainer").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import page CSS
importStyle: true, // import style tags
printContainer: true, // grab outer container as well as the contents of the selector
loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles from print elements
printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
header: null, // prefix to html
formValues: true // preserve input/form values
});
});
</script>
For printThis.js souce code, copy and pase below URL in new tab
https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js
You could use a print stylesheet, but this will affect all print functions.
You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.