I have some old code that I am trying to convert to divs. It contains frames that have no target src, just JavaScript to generate a page.
Below is the code...
var editboxHTML =
'<html class="expand close">' +
'<head>' +
'<style type="text/css">' +
'.expand { width: 100%; height: 100%; }' +
'.close { border: none; margin: 0px; padding: 0px; }' +
'html,body { overflow: hidden; }' +
'<\/style>' +
'<\/head>' +
'<body class="expand close" onload="document.f.ta.focus(); document.f.ta.select();">' +
'<form class="expand close" name="f">' +
'<textarea class="expand close" name="ta" wrap="hard" spellcheck="false">' +
'<\/textarea>' +
'<\/form>' +
'<\/body>' +
'<\/html>';
var defaultStuff = 'This top frame is where you put your code.';
var extraStuff = '';
var old = '';
function init() {
window.editbox.document.write(editboxHTML);
window.editbox.document.close();
window.editbox.document.f.ta.value = defaultStuff;
update();
}
function update() {
var textarea = window.editbox.document.f.ta;
var d = dynamicframe.document;
if (old != textarea.value) {
old = textarea.value;
d.open();
d.write(old);
if (old.replace(/[\r\n]/g, '') == defaultStuff.replace(/[\r\n]/g, ''))
d.write(extraStuff);
d.close();
}
window.setTimeout(update, 150);
}
<frameset onload="init();" rows="50%,50%" resizable="no">
<frame name="editbox" src="javascript:'';">
<frame name="dynamicframe" src="javascript:'';">
</frameset>
This code has a user input box at the top to input HTML code into, and the bottom displays what that code would look like in a browser.
How would I manipulate this code to work with divs instead of frames, so I can include extra styling, and so that it is not fully depreciated in HTML5.
If your answer includes AJAX, please can you explain it as I am not familiar with that coding.
EDIT: If there is no div alternative, is there an iframe alternative?
Answer Updated
CSS Fixed
Error fixed
Jquery way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var editboxHTML =
'<html class="expand close">' +
'<head>' +
'<style type="text/css">' +
'.expand { width: 100%; height: 50%; }' +
'.close { border: none; margin: 0px; padding: 0px; }' +
'html,body { overflow: hidden; }' +
'<\/style>' +
'<\/head>' +
'<body class="expand close">' +
'<form class="expand close" name="f">' +
'<textarea class="expand close" name="ta" wrap="hard" spellcheck="false">qweqwe' +
'<\/textarea>' +
'<\/form>' +
'<\/body>' +
'<\/html>';
var defaultStuff = 'This top frame is where you put your code.';
var extraStuff = '';
var old = '';
function init() {
$("#editbox").html(editboxHTML);
$("#editbox form[name='f'] [name='ta']").focus();
$("#editbox form[name='f'] [name='ta']").val(defaultStuff);
update();
}
function update() {
var textarea = $("#editbox form[name='f'] [name='ta']");
var d = $("#dynamicframe");
if (old != textarea.val()) {
old = textarea.val();
if (old != undefined){
d.html(old);
if (old.replace(/[\r\n]/g, '') == defaultStuff.replace(/[\r\n]/g, '')){
d.append(extraStuff);
}
}
else{
d.html("old undefined");
}
}
setTimeout("update()", 150);
}
</script>
<button onclick="init()">EDIT</button>
<div id="editbox"></div>
<div id="dynamicframe"></div>
you can just create one div tag with id say <div id='editbox' /> and add one line code in your update function document.getElementById("editbox").innerHTML=editboxHTML;
Related
I have an image in HTML and i want the user to write an input in HTML and then if he click on the image it will create a colored div which is written inside the input, the position of this div is based of the coordinates where the user clicked (not centered, a little on top and to the left), for now I can create the rectangular div, but i don't know how to put a text in it.
let listaAre = [];
let quantiClic = 0;
document.getElementById('blah').addEventListener('click', event => {
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;"></div>';
document.getElementById('squar' + quantiClic).style.top = (event.pageY - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.left = (event.pageX - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.width = Number(document.getElementById('dimensione').value)/4 + 'px';
document.getElementById('squar' + quantiClic).style.height = Number(document.getElementById('dimensione').value)/10 + 'px';
document.getElementById('squar' + quantiClic).style.background =(document.getElementById('colorebordo').value);
listaAre.push({
x: (event.offsetX - Number(document.getElementById('dimensione').value) / 2),
y: (event.offsetY - Number(document.getElementById('dimensione').value) / 2),
width: Number(document.getElementById('dimensione').value),
height: Number(document.getElementById('dimensione').value),
background:(document.getElementById('colorebordo').value)
});
document.getElementById('squar' + quantiClic).addEventListener('click', function (e) {
this.style.display = 'none';
});
quantiClic = quantiClic + 1;
});
article, aside, figure, footer, header,
hgroup, menu, nav, section { display: block; }
.fasciaalta {
position: fixed;
background-color: white;
}
<div class="fasciaalta">
<input type="color" id="colorebordo">
<input type="text" id="nome">
<input type="number" id="dimensione" value="200">
<hr size="2px" color="blue" width="100">
</div>
<img id="blah" src="montagna.jpg" alt="your image" />
<div id="squareContaine"></div>
<div id="previewImage"></div>
You can get the coordinates of the mouse on the event click by accessing the clientX and clientY properties of the event object. Then you simply tell the new element to use them as top and left styles to position it.
Snippet
document.getElementById('blah').addEventListener('click', function(event) {
var div = document.createElement("DIV"); // Create a <div> element
var t = document.createTextNode("HELLO");// Create a text node
div.appendChild(t); // Append the text to <div>
document.body.appendChild(div); //Add <div> to document
div.style.position = 'absolute'; //Make its position absolute
//Set the coordinates
div.style.left = event.clientX + "px";
div.style.top = event.clientY + "px";
})
<div>
<img id="blah" src="http://img1.wikia.nocookie.net/__cb6/nyancat/images/5/50/Wiki-background" alt="your image" />
</div>
Extra
If instead of creating a new div, you want to use one simply access that element with getElementById and change its properties instead. I've made the example as simple as possible so that it can apply to not only your case but anyone else's trying to solve their issue.
If you need the text value then all you need is to change the first 2 statements of your click function. - Check this Codepen
1) Onclick, get the value of the textbox like so
var val = document.getElementById('nome').value;
2) Next insert this val into your innerHTML statement
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
Scroll the very end of the above statement to see the val inserted.
Also do not forget to change the color of the text if the background of the box is black.
document.getElementById('blah').addEventListener('click', event => {
var val = document.getElementById('nome').value; //added
//below statement changed
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
.. rest of the code remain the same ..
});
I have dynamic table on my JSP page, where I have added the rows to the table which depends on a dropdown field.
This is my table code:
function createDynamicTable(data){
currentbatchitemData = eval(data);
for(var i = 0; i < currentbatchitemData.length; i++){
var code = currentbatchitemData[i].empCode;
var name = currentbatchitemData[i].empName;
var salary = 0 ;
var income = currentbatchitemData[i].incomeYear;
var month = currentbatchitemData[i].month ;
var des = currentbatchitemData[i].batchDesc;
var tableInfo = "<tr>";
tableInfo +=
'<td class="table-td-text-color">' + code + '</td>' +
'<td class="table-td-text-color">' + name + '</td>' +
'<td class="table-td-text-color">'+ salary + '</td>' +
'<td class="table-td-text-color">' +
'<button type="button" class="btn-edit btn btn-xs"><span class="fa fa-edit"></span></button>'+
'<button type="button" onclick="delRow(this);" class="btn-del btn btn-xs"><span class="fa fa-trash"></span></button>' +'</td>';
$("#currentbatchitem tbody").append(tableInfo);
}
$(document).ready(function(){
$('#currentbatchitem').DataTable();
});
$("#income_year").val(income);
$("#pay_month").val(month);
$("#batch_description").val(des);
}
I want when I have changed the dropdown , the page will be disabled and a gif image will be shown as a reloading image and when the for loop is terminated / after the adding rows on the table; the gif image will be hide and the jsp page will be shown again.
How can I do this?
It seems you're using jQuery DataTables, there's a default option to show the processing indicator:
$('#currentbatchitem').dataTable( {
"processing": true
} );
More details here
PS: You can customize the message like so:
$('#currentbatchitem').dataTable( {
"oLanguage": {
"sProcessing": "DataTables is currently busy"
}
});
If you want to instead show a loading GIF, you can override the CSS class like so:
.dataTables_wrapper .dataTables_processing{
background-image:url('url/to/your/image.gif');
}
This is a plain javascript solution
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function createDynamicTable(){
document.getElementById('loadingDiv').style.display = "block";
//your for loop
setTimeout(function(){
document.getElementById('loadingDiv').style.display = "none";
}, 2000);
}
</script>
</head>
<body onload="createDynamicTable();">
Some page content
<div id="loadingDiv" style="background-color: black; opacity: 0.50; width: 100%; height: 100%;
position: absolute; top: 0px; left: 0px; display: none; z-index: 100;">
<img src="http://gifyo.com/public/img/loading.gif" alt="Loading..."/>
</div>
</body>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Just to let you know I am not a programmer. I try to understand some code and change it where I can using trial and error.
I have the following piece of code from a Joomla module where I need to change in the function: function pausescroller the document.write function that is used to document.getElementById('ElementID').innerHTML and I don't know how. I am posting the code of the function function pausescroller where I tried implementing the above w/o luck. Nothing displays on front end:
function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.getElementById('divId').innerHTML = "<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";
//document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}
HERE IS THE CODE OF THE WHOLE JavaScript part:
<script type="text/javascript">
<!--
var pausecontent=new Array();
var cnti = 0;
<?php
for($im=0; $im<count($testi_RSMSC); $im++) {
$dateExp_RSMSC = explode('-', $testi_RSMSC[$im]['date']);
$timestamp_RSMSC = mktime(12,0,0,$dateExp_RSMSC[1],$dateExp_RSMSC[2],$dateExp_RSMSC[0]);
$dateConfig_RSMSC = JFactory::getConfig();
$siteLang_RSMSC = $dateConfig_RSMSC->get('config.language');
setlocale(LC_ALL, $siteLang_RSMSC);
$dateView_RSMSC = strftime("%d %B %Y", $timestamp_RSMSC);
$testi_RSMSC[$im]['comment'] = preg_replace('/\s\s+/', ' ', trim($testi_RSMSC[$im]['comment']));
$testi_text = '';
if($char_RSMSC > 0) {
$testi_text .= substr($testi_RSMSC[$im]['comment'], 0, ($char_RSMSC-3)).'...';
} else {
$testi_text .= $testi_RSMSC[$im]['comment'];
}
####
$RStesti_pic_file = '';
if($imgDispRSMSC == '1') {
if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.gif')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.gif" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.png')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.png" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.jpg')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.jpg" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else if(file_exists(JPATH_ROOT.DS.'images'.DS.'com_rsmonials'.DS.$testi_RSMSC[$im]['id'].'.jpeg')) {
$RStesti_pic_file = '<img src="'.JURI::root().'images/com_rsmonials/'.$testi_RSMSC[$im]['id'].'.jpeg" style="max-width:'.$imgMwRSMSC.'px; max-height:'.$imgMhRSMSC.'px; border:'.$imgBorderRSMSC.';" />';
} else {
$RStesti_pic_file = $RS_noimg;
}
if($imgAlignRSMSC == '1') {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:left;">'.$RStesti_pic_file.'</div>';
} else if($imgAlignRSMSC == '2') {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:right;">'.$RStesti_pic_file.'</div>';
} else if($imgAlignRSMSC == '3') {
$RStesti_pic_file = '<span style="float:left; margin-right:5px;">'.$RStesti_pic_file.'</span>';
} else if($imgAlignRSMSC == '4') {
$RStesti_pic_file = '<span style="float:right; margin-left:5px;">'.$RStesti_pic_file.'</span>';
} else {
$RStesti_pic_file = '<div style="margin-bottom:5px; text-align:center;">'.$RStesti_pic_file.'</div>';
}
}
####
$RSMSC_disp_context = '<div style="text-align:'.$alignRSMSC.';">'.$RStesti_pic_file.addslashes($testi_text).'</div><br /><em><strong>'.addslashes($testi_RSMSC[$im]['fname']).' '.addslashes($testi_RSMSC[$im]['lname']).'</strong>';
if($displayaboutRSMSC == '1') {
if(($testi_RSMSC[$im]['about'] != '') || ($testi_RSMSC[$im]['location'] != '')) {
$RSMSC_disp_context .= ', Ηλικία: <small>';
$RS_isa = 0;
if($testi_RSMSC[$im]['about'] != '') {
$RSMSC_disp_context .= addslashes($testi_RSMSC[$im]['about']);
$RS_isa = 1;
}
if($testi_RSMSC[$im]['location'] != '') {
if($RS_isa == '1') {
$RSMSC_disp_context .= ', ';
}
$RSMSC_disp_context .= addslashes($testi_RSMSC[$im]['location']);
}
$RSMSC_disp_context .= '</small>';
}
}
if(($displayurlRSMSC == '1') && ($testi_RSMSC[$im]['website'] != '')) {
$RSMSC_disp_context .= '<br /><small>'.$testi_RSMSC[$im]['website'].'</small>';
}
if($displaydateRSMSC == '1') {
$RSMSC_disp_context .= '<br /><small>'.$dateView_RSMSC.'</small>';
}
$RSMSC_disp_context .= '</em>';
?>
pausecontent[cnti++]='<?php echo $RSMSC_disp_context; ?>';
<?php
}
?>
function pausescroller(content, divId, divClass, delay){
this.content=content //message array content
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in miliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
this.hiddendivpointer=1 //index of message array for hidden div
document.getElementById(divId).innerHTML = '<div class="innerDiv" style="position: absolute; width: 100%" id="' + divId + '1">' + content[0] + '</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="' + divId + '2">' + content[1] + '</div>';
//document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>')
var scrollerinstance=this
if (window.addEventListener) //run onload in DOM2 browsers
window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
else if (window.attachEvent) //run onload in IE5.5+
window.attachEvent("onload", function(){scrollerinstance.initialize()})
else if (document.getElementById) //if legacy DOM browsers, just start scroller after 0.5 sec
setTimeout(function(){scrollerinstance.initialize()}, 500)
}
/* initialize()- Initialize scroller method. -Get div objects, set initial positions, start up down animation */
pausescroller.prototype.initialize=function(){
this.tickerdiv=document.getElementById(this.tickerid)
this.visiblediv=document.getElementById(this.tickerid+"1")
this.hiddendiv=document.getElementById(this.tickerid+"2")
this.visibledivtop=parseInt(pausescroller.getCSSpadding(this.tickerdiv))
//set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
this.getinline(this.visiblediv, this.hiddendiv)
this.hiddendiv.style.visibility="visible"
var scrollerinstance=this
document.getElementById(this.tickerid).onmouseover=function(){scrollerinstance.mouseoverBol=1}
document.getElementById(this.tickerid).onmouseout=function(){scrollerinstance.mouseoverBol=0}
if (window.attachEvent) //Clean up loose references in IE
window.attachEvent("onunload", function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
setTimeout(function(){scrollerinstance.animateup()}, this.delay)
}
/* animateup()- Move the two inner divs of the scroller up and in sync */
pausescroller.prototype.animateup=function(){
var scrollerinstance=this
if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5)){
this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
setTimeout(function(){scrollerinstance.animateup()}, 50)
}
else{
this.getinline(this.hiddendiv, this.visiblediv)
this.swapdivs()
setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
}
}
/* swapdivs()- Swap between which is the visible and which is the hidden div */
pausescroller.prototype.swapdivs=function(){
var tempcontainer=this.visiblediv
this.visiblediv=this.hiddendiv
this.hiddendiv=tempcontainer
}
pausescroller.prototype.getinline=function(div1, div2){
div1.style.top=this.visibledivtop+"px"
div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}
/* setmessage()- Populate the hidden div with the next message before it's visible */
pausescroller.prototype.setmessage=function(){
var scrollerinstance=this
if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
setTimeout(function(){scrollerinstance.setmessage()}, 100)
else{
var i=this.hiddendivpointer
var ceiling=this.content.length
this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
this.animateup()
}
}
pausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
if (tickerobj.currentStyle)
return tickerobj.currentStyle["paddingTop"]
else if (window.getComputedStyle) //if DOM2
return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
else
return 0
}
//new pausescroller(name_of_message_array, CSS_ID, CSS_classname, pause_in_miliseconds)
new pausescroller(pausecontent, "rsmsc_scroller", "rsmsc_scroller_class", <?php echo $delay_RSMSC; ?>);
//-->
</script>
Change this line:
document.getElementById('divId').innerHTML = "<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";
to this:
document.getElementById(divId).innerHTML = '<div class="innerDiv" style="position: absolute; width: 100%" id="' + divId + '1">' + content[0] + '</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="' + divId + '2">' + content[1] + '</div>';
(The very first, and very last double quote, should be single quotes, and do not put quotes around the var name divid when calling document.getElementById(divId).innerHTML)
-EDIT- But actually the element you are looking for is not there yet, place the parent div into the html first '<div id="myDiv" class="divClass" style="position: relative; overflow: hidden"></div> then if var divId = 'myDiv'; call the function with:
pausescroller(content, divId, divClass, delay);
The value you set innerHTML to needs to be a complete string - adding ' to each side will fix it:
document.getElementById('divId').innerHTML = '"<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1">'+content[0]+'</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+content[1]+'</div></div>";'
I wrote a code for a 5 image slideshow and the NEXT and PREVIOUS buttons are supposed to take you to the next and previous slide but nothing happens when i press them. Can anyone help me out? some more detail some more detail some more detail some more detail
var slideShow = [];
function newImage(source, caption) {
var pic = new Object();
pic.src = source;
pic.cap = caption;
return pic;
}
slideshow[0] = newImage("slideshow1.jpg", "The Happy Cat");
slideshow[1] = newImage("slideshow2.jpg", "The Tube Cat");
slideshow[2] = newImage("slideshow3.jpg", "The Chubby Cat");
slideshow[3] = newImage("slideshow4.jpg", "if I fits I sits ");
slideshow[4] = newImage("slideshow5.jpg", "The classic Nicolas Cage");
var i = 0;
function nextPic() {
i = (i + 1);
if (i == 5)
i = 0;
document.getElementById("picture").innerHTML = '<img src= ' +
slideshow[i].src + ' id="images" height="100%"' +
' alt="my picture"> <p>' + slideshow[i].cap + '</p>';
}
function prevPic() {
if (i == -1)
i = 4;
else
i = (i - 1);
document.getElementById("picture").innerHTML = '<img src= ' +
slideshow[i].src + ' id="images" height="100%"' +
' alt="my picture"> <p>' + slideshow[i].cap + '</p>';
}
#picture {
width: 200px;
margin-left: 50;
margin-right: auto;
}
div.buttons {
width: 200px;
margin-left: auto;
margin-right: auto;
}
div.info {
width: 500px;
text-align: center;
margin-left: auto;
margin-right: auto;
border: 3px solid purple;
}
button {
font-size: 12px;
}
button.left {
auto;
margin-right: 418px;
}
p {
text-align: center;
}
<h3>Project 2: Slide Show</h3>
<h4>I do not own any of the following pictures</h6>
<h4>All pictures acquired online, unknown owners</h4>
<br />
<div id="picture">
<img src="slideshow1.jpg" id="images" alt="my picture" height="200 px">
<p>The Happy Cat</p>
</div>
<div class="buttons">
<button class="left" onClick="prevPic()">PREVIOUS</button>
<button onClick="nextPic()">NEXT</button>
</div>
1) Typo in slideShow
2)Not related but you cannot have duplicate id instead use class
var slideshow = [];
function newImage(source, caption) {
var pic = new Object();
pic.src = source;
pic.cap = caption;
return pic;
}
slideshow[0] = newImage("slideshow1.jpg", "The Happy Cat");
slideshow[1] = newImage("slideshow2.jpg", "The Tube Cat");
slideshow[2] = newImage("slideshow3.jpg", "The Chubby Cat");
slideshow[3] = newImage("slideshow4.jpg", "if I fits I sits ");
slideshow[4] = newImage("slideshow5.jpg", "The classic Nicolas Cage");
var i = 0;
function nextPic() {
i = (i + 1);
if (i == 5)
i = 0;
document.getElementById("picture").innerHTML = '<img src= ' +
slideshow[i].src + ' class="images" height="100%"' +
' alt="my picture"> <p>' + slideshow[i].cap + '</p>';
}
function prevPic() {
if (i == -1)
i = 4;
else
i = (i - 1);
document.getElementById("picture").innerHTML = '<img src= ' +
slideshow[i].src + ' class="images" height="100%"' +
' alt="my picture"> <p>' + slideshow[i].cap + '</p>';
}
<h3> Project 2: Slide Show </h3>
<h4> I do not own any of the following pictures </h6>
<h4> All pictures acquired online, unknown owners </h4>
<br />
<div id="picture">
<img src="slideshow1.jpg" class="images" alt="my picture" height="200 px">
<p>The Happy Cat</p>
</div>
<div class="buttons">
<button class="left" onClick="prevPic()">PREVIOUS</button>
<button onClick="nextPic()">NEXT</button>
</div>
You declaring var slideShow = []; array, however later you are populating slideshow with the code:
slideshow[0] = newImage("slideshow1.jpg","The Happy Cat");
which throws ReferenceError because you can't set property of the undefined.
Use var slideshow = [] instead of var slideShow = []
I have two divs: div1 and div2.
Maintaining the original css styles applied to the div2 element being printed.
I don't want to print content inside div1 but only the inside of div2.
How to print?
Try this
<style type="text/css">
#media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>
Using my following solution you can print the specific div content from your web page if you don't want to print your full page.
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">
function PrintElem(elem)
{
Popup($(elem).html());
}
function Popup(data)
{
var mywindow = window.open('', 'new div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}
</script>
</head>
<body>
<div id="yourdiv">
Div you want to print. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante.
</div>
<div>
This will not be printed.
</div>
<div id="anotherdiv">
Nor will this.
</div>
<input type="button" value="Print" onclick="PrintElem('#yourdiv')" />
</body>
</html>
Live Demo
You can only print a whole page, not part ofg a page. So, there is two options, you can either copy the content of one element into a new page and print that, or prevent the other element from being printed.
You can use a media css to hide one element from printing. Example:
#media print {
.div1 { display: none; }
}
<script type="text/javascript">
function printDiv() {
var printContents = document.getElementById('Your printable div').innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
Have a look at the jqPrint plugin for jQuery: http://plugins.jquery.com/project/jqPrint
You can also do it using jQuery:
<script>
function printArea(){
$('body').css('visibility', 'hidden');
$('.div2').css('visibility', 'visible');
window.print();
}
</script>
I faced lots of issues while printing a div (part of HTML) using window.print(). Used below method and it works seamlessly in edge, chrome and Mozilla. How this below function helps mitigate the issue that I face is by the use of iframe. When using window.print() without the below code it was printing most of the page's design and all, which we didn't want. There are many CSS based options too but eventually this one below worked for me. From the below code "frameDoc.document.write........ frameDoc.document.close();" is controlling the format that can be seen in print preview as well.
function printDiv(id) {
var contents = document.getElementById(id).innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write("<html><head>\n\n " +
"<style type=\"text/css\" media=\"print\">\n " +
"##page\n {\n " +
"size: auto; /* auto is the initial value */\n " +
"margin: 10mm; /* this affects the margin in the printer settings */\n " +
" }\n\n html\n {\n " +
" background-color: #FFFFFF;\n " +
" }\n\n body\n " +
" { font-family:\"Times New Roman\", Times, serif;\n " +
" border: none ;\n " +
" margin: 0; /* margin you want for the content */\n " +
" }\n .table {\n width: 100%;\n " +
" max-width: 100%;\n margin-bottom: 20px;\n " +
" border-collapse: collapse;\n " +
" background-color: transparent;\n display: table;\n " +
" }\n .table-bordered {\n " +
" border: 1px solid #ccc;\n }\n tr {\n " +
" display: table-row;\n vertical-align: inherit;\n " +
" border-color: inherit;\n padding:15px;\n }\n " +
" .table-bordered tr td {border: 1px solid #ccc!important; padding:15px!important;}\n " +
" </style><title></title></head><body>".concat(contents, "</body>"));
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}
Call this like
Print
Easy way
#media print {
body > div { display:none; }
body .div { display:block; }
}
.class-toggle { display: inline-block; }
#div1, #div2 { display: none; }
function classToggle() {
$('#div1').addClass('class-toggle');
}
classToggle();
Then you can play with event handler to handle how and when you want to
print the output.
Use PrintArea jQuery Plugin to print specific div content. I have found the easy integration guide from here - How to print a specific area of the web page using jQuery
You need only the following code to use PrintArea jQuery Plugin.
<script>
$(document).ready(function(){
$("#printButton").click(function(){
var mode = 'iframe';
var close = mode == "popup";
var options = { mode : mode, popClose : close};
$("div.printableArea").printArea( options );
});
});
</script>
<script type="text/javascript">
function printDiv() {
var printContents = document.getElementById('Your printable div').innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>