javascript dynamic textarea and nicedit - javascript

with the great help of a few guys on here I have managed to create a page that creates dynamic resizable/draggable textareas on the fly. I am now trying to intregrate nicedit into these textareas. Its working to a point. On double click the textarea becomes a nicedit area but unfortunately the draggable event is overriding the nicedit even and so am unable to edit the textarea.
my javascript is limited so I was hoping someone could point out the error of my ways
thanks in advance.
here is the jsfiddle link http://jsfiddle.net/JVhpJ/9/
heres the code
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<script src = "http://js.nicedit.com/nicEdit-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
window.onload = function () {
var body = document.body;
// The magic
body.addEventListener ("dblclick", function (event) {
var target = event.target;
if (target.nodeName === "TEXTAREA") {
var area = new nicEditor ({fullPanel : true}).panelInstance (target);
area.addEvent ("blur", function () {
this.removeInstance (target);
});
}
}, false);
}
var i=0;
var p=25;
function creatediv1(id)
{
id=id+i;
var xp=xp+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('iterate',i);
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.left = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id="+i +" name='textarea["+i +"]' class='textarea1' width='300' style='position:absolute; top:0px;left:0px;overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='300' name='width["+i+"]' id='width"+i+"'><br><input type='hidden' value='300' name='height["+i+"]' id='height"+i+"'>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='0' name='left["+i+"]' id='left"+i+"'><br><input type='hidden' value='0' name='top["+i+"]' id='top"+i+"'>";
document.getElementById("frmMain").appendChild(newdiv);
$(function()
{
$("#"+i).resizable(
{
stop: function(event, ui)
{
var width = ui.size.width;
var height = ui.size.height;
// alert("width="+width+"height="+height);
ValProportions(width,height,ui.element.context.id);
}
});
$( "#"+id ).draggable(
{
stop: function(event, ui)
{
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
// alert("left="+Stoppos.left+"top="+Stoppos.top);
ValPostion(Stoppos.left,Stoppos.top,$(this).attr('iterate'));
}
});
$("#"+i).draggable({handle:"#handle"});
});
function ValProportions(defaultwidth, defaultheight,id) {
$('#width'+id).val(defaultwidth);
$('#height'+id).val(defaultheight);
}
function ValPostion(defaultleft,defaulttop,id) {
$('#left'+id).val(defaultleft);
$('#top'+id).val(defaulttop);
}
i++;
p=p+25;
}
</script>
<style>
textarea {
height: 100px;
margin-bottom: 20px;
width: 1000px;
}
</style>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="test.php" method="post">
<input id="btn1" type="button" value="Add New textbox" onclick="creatediv1('draggable');" />
<input type="submit" value="Submit" >
</form>
</body>

I managed to fix this issue by use stoppropagation() on the mousedown event of the div, this allowed me to then edit the text without the draggable overriding the edit functions

Related

How to add image quantity functions in printing in javascript?

This is an example of what I want to achieve first the user will select the image and then they will input number of image pieces they want to show on the print page, I already created the functions of adding the image and printing it but it is only one I want to create like this one that can print multiple images depends on what user input.
This is my code:
var myApp = new function() {
this.geltint = function() {
var tab = document.getElementById('geltint');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
var myApp2 = new function() {
this.powdery = function() {
var tab = document.getElementById('powdery');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
var myApp3 = new function() {
this.powdery5ml = function() {
var tab = document.getElementById('powdery5ml');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#geltint')
.attr('src', e.target.result)
.width(244.8)
.height(187.2);
};
reader.readAsDataURL(input.files[0]);
}
}
function readURL2(input) {
if (input.files && input.files[0]) {
var reader2 = new FileReader();
reader2.onload = function(e) {
$('#powdery')
.attr('src', e.target.result)
.width(172.8)
.height(230.4);
};
reader2.readAsDataURL(input.files[0]);
}
}
function readURL3(input) {
if (input.files && input.files[0]) {
var reader2 = new FileReader();
reader2.onload = function(e) {
$('#powdery5ml')
.attr('src', e.target.result)
.width(244.8)
.height(105.6);
};
reader2.readAsDataURL(input.files[0]);
}
}
This is my HTML code:
<HTML>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js">
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article,
aside,
figure,
footer,
header,
group,
menu,
nav,
section {
display: block;
}
</style>
</head>
<body>
<div id="1stimage">
<input type='file' onchange="readURL(this);" />
<img id="geltint" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp.geltint()" />
</p>
</div>
<div id="2ndimage">
<input type='file' onchange="readURL2(this);" />
<img id="powdery" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp2.powdery()" />
</p>
</div>
<div id="3rdimage">
<input type='file' onchange="readURL3(this);" />
<img id="powdery5ml" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp3.powdery5ml()" />
</p>
</div>
</body>
</html>
This is EXAMPLE what I want my output to look plain and simple any suggestions or ideas you can share with me guys thank you so much.
Users will choose an image and then input quantity on how many copies of an image they want then press print And It will show the print preview like this with total numbers of images what the user input
You can use for-loop and iterate until <= quantity where quantity is enter by user and inside this for-loop append tab.outerHTML in some variable using += .So , you can change your code like below :
HTML :
<div id="1stimage">
<input type='file' onchange="readURL(this);" />
<!--added qty -->
<input type="number" value="1" class="qty">
<img id="geltint" src="#" alt="your image" />
<p>
<!--pass this as well-->
<input type="button" value="Print Table" onclick="myApp.geltint(this)" />
</p>
</div>
<!--do same for others ...->
Js Code :
var myApp = new function() {
this.geltint = function(el) {
var tab = document.getElementById('geltint');
var qty = $(el).closest("div").find(".qty").val(); //get qty value
console.log(qty)
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var html = "";
//loop
for (var i = 1; i <= qty; i++) {
html += tab.outerHTML //append
}
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(html); //pass same
win.document.close();
win.print();
}
}

Elements within dynamically created of <div> on each button click is not properly overridden

I am trying to create a comment box where on each submit a new is dynamically created. The inner elements of the <div> being 3 buttons Edit, Post, Cancel and a close icon(image). These are also dynamically created. I finally append them all together. The below code would generate something like the below image on two submits. The error I'm facing is that, whatever <div>'s close icon/button is clicked, always the last <div> is being affected. Here I tried to close 'Hi' but 'hello' is being affected.Also there is a duplication of the <div> on even comments.
Kindly help me correct these issues.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<textarea id="ta" rows="30" cols="30" readonly></textarea>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var newDiv="",i=1,ta="";
function add() {
i++;
ta=document.getElementById('ta');
newDiv = document.createElement("div");
newDiv.id = "d"+i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
newP=document.createElement("BUTTON");
newP.id="p"+i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
newImg=document.createElement("IMG");
newImg.id="i"+i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
newBut1=document.createElement("button");
newBut1.id="b"+i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
newButt1=document.createElement("button");
newButt1.id="bt"+i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
}
</script>
</body>
</html>
Try this code. I have changed textarea to div.
Initial i to 0 instead of 1. You can also set it to 1. It won't affect the functionality.
Some variables were global, I have changed them to local variable now like newDiv,newP, newImg etc.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<!--<textarea id="ta" rows="30" cols="30" readonly></textarea>-->
<div id="ta"></div>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var i=0,ta="";
function add() {
(function(){
i++;
var temp_i = i;
ta=document.getElementById('ta');
var newDiv = document.createElement("div");
newDiv.id = "d"+temp_i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+temp_i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
console.log(temp_i);
console.log(i);
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
var newP=document.createElement("BUTTON");
newP.id="p"+temp_i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
var newImg=document.createElement("IMG");
newImg.id="i"+temp_i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
var newBut1=document.createElement("button");
newBut1.id="b"+temp_i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
var newButt1=document.createElement("button");
newButt1.id="bt"+temp_i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+temp_i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
})();
}
</script>
</body>
</html>
Why not you use jquery to minimize your code campaign. Below is the code which will fix your problem.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<br>
<div class="container">
<input type="textbox" id="tb"><br>
<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br />
</div>
<button class="submit">Submit</button><br>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.submit').click(function() {
var element = '<div class="container">'+'<input type="textbox" id="tb"><br>'+
'<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br /></div>';
$('.submit').before(element);
});
$('body').delegate('.cancel', 'click', function() {
$(this).parent().remove();
});
});
</script>
</body>
</html>
Thanks

jQuery button requiring two clicks for functionality

I'm really new to working with jQuery and JSON, but I'm doing a simple weather retrieving practice project. I have got it to work except that I have to hit the Get Weather button twice in order for the Fahrenheit/Celsius button to work. I'm sure it is something small that I'm missing.
Here is all the code:
<!DOCTYPE html>
<html>
<head>
<title>Weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function gettingJSON(data){
var temp = data.main.temp;
var tempC = (temp - 32) * .5556;
var far = $(".temp").html("The temperature is " + Math.floor(temp) + "F");
var cel = $(".tempC").html("The temperature in C is " + Math.floor(tempC));
cel.hide();
far.show();
$(document).on("click", "#change", function(){
far.toggle();
cel.toggle();
});
}
$(document).ready(function(){
$(document).on("click", "#getIt", function(){
var location = $(".loc").val();
var state = $(".state").val();
var apiKey = "a6253b99c39a496597483fbf2ff308ff";
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+","+state+"&units=imperial&appid=" + apiKey;
$.getJSON(url, gettingJSON);
});
});
</script>
<style>
body,html{
width: 100%;
height: 100%;
background: honeydew;
}
.temp, .tempC{
font-size: 30px;
}
</style>
</head>
<body>
<div class="toggleMe">
<p class="temp"></p>
<p class="tempC"></p>
</div>
<input type="text" class="loc" placeholder="City">
<input type="text" class="state" placeholder="State">
<button id ="getIt"> Get Weather</button>
<button id="change">C/F</button>
</body>
</html>
I'd appreciate any help available!
Thanks!
You should move the $(document).on("click", "#change", out of the gettingJSON function, otherwise - every time you call the gettingJSON function - you attache a new event listener for the click event on the #change element.
Here is your updated code:
var far = $(".temp");
var cel = $(".tempC")
function gettingJSON(data){
var temp = data.main.temp;
var tempC = (temp - 32) * .5556;
far.html("The temperature is " + Math.floor(temp) + "F");
cel.html("The temperature in C is " + Math.floor(tempC));
cel.hide();
far.show();
}
$(document).ready(function(){
$(document).on("click", "#change", function(){
far.toggle();
cel.toggle();
});
$(document).on("click", "#getIt", function(){
var location = $(".loc").val();
var state = $(".state").val();
var apiKey = "a6253b99c39a496597483fbf2ff308ff";
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+","+state+"&units=imperial&appid=" + apiKey;
$.getJSON(url, gettingJSON);
});
});
body,html{
width: 100%;
height: 100%;
background: honeydew;
}
.temp, .tempC{
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="toggleMe">
<p class="temp"></p>
<p class="tempC"></p>
</div>
<input type="text" class="loc" placeholder="City">
<input type="text" class="state" placeholder="State">
<button id ="getIt"> Get Weather</button>
<button id="change">C/F</button>
Dekel's answer is the way to go! Additionally if you want to make it a little bit nicer you could hide the change button until the values are actually available.
To reach that set the button to be hidden by the loading of the page via CSS:
#change {
display:none;
}
and in your gettingJSON() you can then call
$('#change').show();
for displaying the button.

Overlap Issue with div in HTML and JS

I am trying to rotate an image within a div using html and js. I have it working for the most part except for an overlapping issue: the image either covers up everything or overlaps during rotation. I thought I had resolved it with my js formula which sets the div size based on the image size, however it's not working and I'm not sure why. Any ideas?
<html>
<head>
<style>
#photoimg {
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#photo {
position: relative;
}
</style>
</head>
<body>
<form action="#" method="post">
<input type="url" name="imglink" id="imglink" placeholder="Insert image URL here" /><br>
<input type="button" value="Show Image" id="btn1"/>
</form>
<div id="photo"></div>
<script>
document.getElementById('btn1').addEventListener('click', function(){
document.getElementById('photo').innerHTML = '<img id="photoimg" src="'+ document.getElementById('imglink').value +'" alt="Image"/>';
//Get larger edge
var largerPhotoDimension = Math.sqrt(Math.pow(document.getElementById('photoimg').offsetWidth , 2) + Math.pow(document.getElementById('photoimg').offsetHeight ,2) );
//Adjust container to fix image roted 90deg
document.getElementById('photo').offsetWidth(largerPhotoDimension);
document.getElementById('photo').offsetHeight(largerPhotoDimension);
});
</script>
<button id="button">rotate</button>
<script>
document.getElementById('button').onclick = function(){
var curr_value = document.getElementById('photoimg').style.transform;
var new_value = "rotate(90deg)";
if(curr_value !== ""){
var new_rotate = parseInt(curr_value.replace("rotate(","").replace(")","")) + 90;
new_value = "rotate(" + new_rotate + "deg)";
}
document.getElementById('photoimg').style.transform = new_value;
};
</script>
</body>
</html>
Just add these two lines
document.getElementById('photoimg').style.height = document.getElementById("photo").offsetWidth;
document.getElementById('photoimg').style.width = document.getElementById('photo').offsetHeight;
below
document.getElementById('photoimg').style.transform = new_value;
Thanks Guys. I fixed the issue using the following code.
<html>
<head>
<style>
#photoimg {
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#photo {
position: relative;
}
</style>
</head>
<form action="#" method="post">
<input type="url" name="imglink" id="imglink" placeholder="Insert image URL here" /><br>
<input type="button" value="Show Image" id="btn1"/>
</form>
<div id="photo"></div>
<script>
document.getElementById('btn1').addEventListener('click', function(){
document.getElementById('photo').innerHTML = '<img id="photoimg" src="'+ document.getElementById('imglink').value +'" alt="Image"/>';
//Get larger edge
var largerPhotoDimension = Math.sqrt(Math.pow(document.getElementById('photoimg').offsetWidth , 2) + Math.pow(document.getElementById('photoimg').offsetHeight ,2) );
var marginVert = (largerPhotoDimension - document.getElementById('photoimg').offsetHeight)/2;
var marginHorz = (largerPhotoDimension - document.getElementById('photoimg').offsetWidth)/2;
//Adjust container to fix image rotated 90deg
document.getElementById('photo').style.marginRight = marginHorz;
document.getElementById('photo').style.marginLeft = marginHorz;
document.getElementById('photo').style.marginBottom = marginVert;
document.getElementById('photo').style.marginTop = marginVert;
});
</script>
<button id="button">rotate</button>
<script>
document.getElementById('button').onclick = function(){
var curr_value = document.getElementById('photoimg').style.transform;
var new_value = "rotate(45deg)";
if(curr_value !== ""){
var new_rotate = parseInt(curr_value.replace("rotate(","").replace(")","")) + 45;
new_value = "rotate(" + new_rotate + "deg)";
}
document.getElementById('photoimg').style.transform = new_value;
};
</script>
</body>
</html>

How do I add the same functions back into my code after detaching in Jquery?

I'm trying to recreate my .click functions, for loops, if statements after they are used the first time. I created a button on the page that asks the user if they want to start over when the user clicks this button it does indeed reload everything except my .click functions, for loops, if statements in jquery.
How can I make my button reload the functions,loops,if statements?
I tried using remove(). It didn't work either. As you can see in my code when the user clicks on the button that says Yes! then the divs they have created are detached() from the code a long with most of the other elements on the page. After that I am using before() & after() to recreate the removed questions, spaces under them & their submit buttons. The problem is that the submit buttons no longer function after they are created again.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<title>Razzakun's Etch A Sketch</title>
</head>
<body>
<center><h1>Welcome to Razzakun's Etch A Sketch</h1><center>
<center><div id="verticalSquaresQuestion">How many vertical squares of Etch A Sketch Space do you want?</div></center>
<br>
<center><input id="vsquareInput" type="text" value="" /></center>
<br>
<center><input id="vsubmit" type="button" value="Submit" /></center>
<br>
<center><div id="horizontalSquaresQuestion">How many horizontal squares of Etch A Sketch Space do you want?</div></center>
<br>
<center><input id="hsquareInput" type="text" value="" /></center>
<br>
<center><input id="hsubmit" type="button" value="Submit" /></center>
</body>
</html>
<script>
$(document).ready(function(){
var creatingVDivs = 0;
var creatingHDivs = 0;
var createContainer = "<div id=container></div>";
var createHorizontalDivs="<div class= hsquare><center>Etch A Sketch</center></div>";
var createVerticalDivs = "<div class= vsquare><center>Etch A Sketch</center></div>";
var trueNumberOfVerticalSquares = 0;
var trueNumberOfHorizontalSquares = 0;
var $numOfVerticalSquares = $("#vsquareInput");
var $numOfHorizontalSquares = $("#hsquareInput");
var createEtchASketchLogoDiv = "<div id = logo><center><h3>Thank you for trying Razzakun's Etch A Sketch! </h3></center></div>";
var clearQuestion = "<div id= clearQuestion><center><h2>Do you want to start over?</h2></center></div>";
var clearQuestionSpace= "<br>";
var clearQuestionSubmit ="<center><input id='clearSubmit' type='button' value='Yes!' /></center>";
var verticalSquaresQuestion = "<center><div id='verticalSquaresQuestion'>How many vertical squares of Etch A Sketch Space do you want?</div></center>";
var vSquareInput = "<center><input id='vsquareInput' type='text' value='' /></center>";
var vSubmit = "<center><input id='vsubmit' type='button' value='Submit' /></center>";
var horizontalSquaresQuestion ="<br><br><center><div id='horizontalSquaresQuestion'>How many horizontal squares of Etch A Sketch Space do you want?</div></center>";
var hSquareInput = "<center><input id='hsquareInput' type='text' value='' /></center>";
var hSubmit= "<center><input id='hsubmit' type='button' value='Submit' /></center>";
$("#vsubmit").off("click").on("click", function () {
trueNumberOfVerticalSquares = $numOfVerticalSquares.val();
alert(trueNumberOfVerticalSquares + " vertical squares will be created. Click OK if that's okay.");
for(creatingVDivs=0; creatingVDivs < trueNumberOfVerticalSquares; creatingVDivs++) {
$("body").append(createVerticalDivs);
$(".vsquare").height("200px");
$(".vsquare").width("200px");
$(".vsquare").css("margin", "0px");
$(".vsquare").css("background-color","#eef7ff");
}
if(creatingVDivs >= trueNumberOfVerticalSquares){
$("body").append(createContainer);
$("#logo").detach();
$("#container").prepend( $( ".vsquare"));
$("#vsubmit").detach();
$("#vsquareInput").detach();
$("#verticalSquaresQuestion").detach();
$("#clearQuestion").detach();
$("<br>").detach();
$("#clearSubmit").detach();
$("#container").before(createEtchASketchLogoDiv);
$("#logo").before(clearQuestion);
$("#logo").before(clearQuestionSpace);
$("#clearQuestion").after(clearQuestionSubmit);
$("#clearSubmit").off("click").on("click", function () {
alert("Are you sure you really want to erase your hard work? Click OK if you are.");
$(".vsquare, .hsquare").detach();
$("#clearSubmit").detach();
$("#clearQuestion").detach();
$("#horizontalSquaresQuestion").detach();
$("#hsquareInput").detach();
$("#hsubmit").detach();
$("h1").after(verticalSquaresQuestion);
$("#verticalSquaresQuestion").after(vSquareInput);
$("#vsquareInput").after(vSubmit);
$("#verticalSquaresQuestion").after($("<br>"));
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
$("#horizontalSquaresQuestion").after(hSquareInput);
$("#hsquareInput").after(hSubmit);
$("#horizontalSquaresQuestion").after($("<br>"));
$("#hsubmit").before($("<br>"));
});
}
});
$("#hsubmit").off("click").on("click", function () {
trueNumberOfHorizontalSquares = $numOfHorizontalSquares.val();
alert(trueNumberOfHorizontalSquares + " horizontal squares will be created. Click OK if that's okay.");
for(creatingHDivs=0; creatingHDivs < trueNumberOfHorizontalSquares; creatingHDivs++) {
$("body").append(createHorizontalDivs);
$(".hsquare").height("200px");
$(".hsquare").width("200px");
$(".hsquare").css("margin", "0px");
$(".hsquare").css("background-color","#eef7ff");
$(".hsquare").css("padding","0px");
$(".hsquare").css("float","left");
$(".hsquare").css("display","block");
}
if(creatingHDivs >= trueNumberOfHorizontalSquares){
$("body").append(createContainer);
$("#logo").detach();
$("#container").prepend( $( ".hsquare"));
$("#hsubmit").detach();
$("#hsquareInput").detach();
$("#horizontalSquaresQuestion").detach();
$("#clearQuestion").detach();
$("<br>").detach();
$("#clearSubmit").detach();
$("#container").before(createEtchASketchLogoDiv);
$("#logo").before(clearQuestion);
$("#logo").before(clearQuestionSpace);
$("#clearQuestion").after(clearQuestionSubmit);
$("#clearSubmit").off("click").on("click", function () {
alert("Are you sure you really want to erase your hard work? Click OK if you are.");
$(".vsquare, .hsquare").detach();
$("#clearSubmit").detach();
$("#clearQuestion").detach();
$("#verticalSquaresQuestion").detach();
$("#vsquareInput").detach();
$("#vsubmit").detach();
$("h1").after(verticalSquaresQuestion);
$("#verticalSquaresQuestion").after(vSquareInput);
$("#vsquareInput").after(vSubmit);
$("#verticalSquaresQuestion").after($("<br>"));
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
$("#horizontalSquaresQuestion").after(hSquareInput);
$("#hsquareInput").after(hSubmit);
$("#horizontalSquaresQuestion").after($("<br>"));
$("#hsubmit").before($("<br>"));
});
}
});
});
</script>
If you want to renew the event handler, then try calling them again once you have recreated the DOM elements:
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
$("#vsubmit").off("click").on("click", function () { ... });
Since function () { ... } is now being used multiple times and recursively, you must assign it to a variable.
var vsubmitListener = function () {
trueNumberOfVerticalSquares = $numOfVerticalSquares.val();
alert(trueNumberOfVerticalSquares + " vertical squares will be created. Click OK if that's okay.");
for (creatingVDivs = 0; creatingVDivs < trueNumberOfVerticalSquares; creatingVDivs++) {
$("body").append(createVerticalDivs);
$(".vsquare").height("200px");
$(".vsquare").width("200px");
$(".vsquare").css("margin", "0px");
$(".vsquare").css("background-color", "#eef7ff");
}
if (creatingVDivs >= trueNumberOfVerticalSquares) {
$("body").append(createContainer);
$("#logo").detach();
$("#container").prepend($(".vsquare"));
$("#vsubmit").detach();
$("#vsquareInput").detach();
$("#verticalSquaresQuestion").detach();
$("#clearQuestion").detach();
$("<br>").detach();
$("#clearSubmit").detach();
$("#container").before(createEtchASketchLogoDiv);
$("#logo").before(clearQuestion);
$("#logo").before(clearQuestionSpace);
$("#clearQuestion").after(clearQuestionSubmit);
$("#clearSubmit").off("click").on("click", function () {
alert("Are you sure you really want to erase your hard work? Click OK if you are.");
$(".vsquare, .hsquare").detach();
$("#clearSubmit").detach();
$("#clearQuestion").detach();
$("#horizontalSquaresQuestion").detach();
$("#hsquareInput").detach();
$("#hsubmit").detach();
$("h1").after(verticalSquaresQuestion);
$("#verticalSquaresQuestion").after(vSquareInput);
$("#vsquareInput").after(vSubmit);
$("#verticalSquaresQuestion").after($("<br>"));
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
/* Now that is has a name, we can recursively call it */
$("#vsubmit").off("click").on("click", vsubmitListener);
/* We couldn't do that when it was an anonymous function literal */
$("#horizontalSquaresQuestion").after(hSquareInput);
$("#hsquareInput").after(hSubmit);
$("#horizontalSquaresQuestion").after($("<br>"));
$("#hsubmit").before($("<br>"));
});
}
};
$("#vsubmit").off("click").on("click", vsubmitListener);
You'll have to do this for #hsubmit as well.
The following snippet works for me:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<title>Razzakun's Etch A Sketch</title>
</head>
<body>
<center>
<h1>Welcome to Razzakun's Etch A Sketch</h1>
<center>
<center>
<div id="verticalSquaresQuestion">How many vertical squares of Etch A Sketch Space do you want?</div>
</center>
<br>
<center>
<input id="vsquareInput" type="text" value="" />
</center>
<br>
<center>
<input id="vsubmit" type="button" value="Submit" />
</center>
<br>
<center>
<div id="horizontalSquaresQuestion">How many horizontal squares of Etch A Sketch Space do you want?</div>
</center>
<br>
<center>
<input id="hsquareInput" type="text" value="" />
</center>
<br>
<center>
<input id="hsubmit" type="button" value="Submit" />
</center>
</body>
</html>
<script>
$(document).ready(function() {
var creatingVDivs = 0;
var creatingHDivs = 0;
var createContainer = "<div id=container></div>";
var createHorizontalDivs = "<div class= hsquare><center>Etch A Sketch</center></div>";
var createVerticalDivs = "<div class= vsquare><center>Etch A Sketch</center></div>";
var trueNumberOfVerticalSquares = 0;
var trueNumberOfHorizontalSquares = 0;
var $numOfVerticalSquares = $("#vsquareInput");
var $numOfHorizontalSquares = $("#hsquareInput");
var createEtchASketchLogoDiv = "<div id = logo><center><h3>Thank you for trying Razzakun's Etch A Sketch! </h3></center></div>";
var clearQuestion = "<div id= clearQuestion><center><h2>Do you want to start over?</h2></center></div>";
var clearQuestionSpace = "<br>";
var clearQuestionSubmit = "<center><input id='clearSubmit' type='button' value='Yes!' /></center>";
var verticalSquaresQuestion = "<center><div id='verticalSquaresQuestion'>How many vertical squares of Etch A Sketch Space do you want?</div></center>";
var vSquareInput = "<center><input id='vsquareInput' type='text' value='' /></center>";
var vSubmit = "<center><input id='vsubmit' type='button' value='Submit' /></center>";
var horizontalSquaresQuestion = "<br><br><center><div id='horizontalSquaresQuestion'>How many horizontal squares of Etch A Sketch Space do you want?</div></center>";
var hSquareInput = "<center><input id='hsquareInput' type='text' value='' /></center>";
var hSubmit = "<center><input id='hsubmit' type='button' value='Submit' /></center>";
var vsubmitListener = function() {
trueNumberOfVerticalSquares = $numOfVerticalSquares.val();
alert(trueNumberOfVerticalSquares + " vertical squares will be created. Click OK if that's okay.");
for (creatingVDivs = 0; creatingVDivs < trueNumberOfVerticalSquares; creatingVDivs++) {
$("body").append(createVerticalDivs);
$(".vsquare").height("200px");
$(".vsquare").width("200px");
$(".vsquare").css("margin", "0px");
$(".vsquare").css("background-color", "#eef7ff");
}
if (creatingVDivs >= trueNumberOfVerticalSquares) {
$("body").append(createContainer);
$("#logo").detach();
$("#container").prepend($(".vsquare"));
$("#vsubmit").detach();
$("#vsquareInput").detach();
$("#verticalSquaresQuestion").detach();
$("#clearQuestion").detach();
$("<br>").detach();
$("#clearSubmit").detach();
$("#container").before(createEtchASketchLogoDiv);
$("#logo").before(clearQuestion);
$("#logo").before(clearQuestionSpace);
$("#clearQuestion").after(clearQuestionSubmit);
$("#clearSubmit").off("click").on("click", function() {
alert("Are you sure you really want to erase your hard work? Click OK if you are.");
$(".vsquare, .hsquare").detach();
$("#clearSubmit").detach();
$("#clearQuestion").detach();
$("#horizontalSquaresQuestion").detach();
$("#hsquareInput").detach();
$("#hsubmit").detach();
$("h1").after(verticalSquaresQuestion);
$("#verticalSquaresQuestion").after(vSquareInput);
$("#vsquareInput").after(vSubmit);
$("#verticalSquaresQuestion").after($("<br>"));
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
$("#horizontalSquaresQuestion").after(hSquareInput);
$("#hsquareInput").after(hSubmit);
$("#horizontalSquaresQuestion").after($("<br>"));
$("#hsubmit").before($("<br>"));
$("#vsubmit").off("click").on("click", vsubmitListener);
$("#hsubmit").off("click").on("click", hsubmitListener);
});
}
};
var hsubmitListener = function() {
trueNumberOfHorizontalSquares = $numOfHorizontalSquares.val();
alert(trueNumberOfHorizontalSquares + " horizontal squares will be created. Click OK if that's okay.");
for (creatingHDivs = 0; creatingHDivs < trueNumberOfHorizontalSquares; creatingHDivs++) {
$("body").append(createHorizontalDivs);
$(".hsquare").height("200px");
$(".hsquare").width("200px");
$(".hsquare").css("margin", "0px");
$(".hsquare").css("background-color", "#eef7ff");
$(".hsquare").css("padding", "0px");
$(".hsquare").css("float", "left");
$(".hsquare").css("display", "block");
}
if (creatingHDivs >= trueNumberOfHorizontalSquares) {
$("body").append(createContainer);
$("#logo").detach();
$("#container").prepend($(".hsquare"));
$("#hsubmit").detach();
$("#hsquareInput").detach();
$("#horizontalSquaresQuestion").detach();
$("#clearQuestion").detach();
$("<br>").detach();
$("#clearSubmit").detach();
$("#container").before(createEtchASketchLogoDiv);
$("#logo").before(clearQuestion);
$("#logo").before(clearQuestionSpace);
$("#clearQuestion").after(clearQuestionSubmit);
$("#clearSubmit").off("click").on("click", function() {
alert("Are you sure you really want to erase your hard work? Click OK if you are.");
$(".vsquare, .hsquare").detach();
$("#clearSubmit").detach();
$("#clearQuestion").detach();
$("#verticalSquaresQuestion").detach();
$("#vsquareInput").detach();
$("#vsubmit").detach();
$("h1").after(verticalSquaresQuestion);
$("#verticalSquaresQuestion").after(vSquareInput);
$("#vsquareInput").after(vSubmit);
$("#verticalSquaresQuestion").after($("<br>"));
$("#vsubmit").before($("<br>"));
$("#vsubmit").after(horizontalSquaresQuestion);
$("#horizontalSquaresQuestion").after(hSquareInput);
$("#hsquareInput").after(hSubmit);
$("#horizontalSquaresQuestion").after($("<br>"));
$("#hsubmit").before($("<br>"));
$("#vsubmit").off("click").on("click", vsubmitListener);
$("#hsubmit").off("click").on("click", hsubmitListener);
});
}
};
$("#vsubmit").off("click").on("click", vsubmitListener);
$("#hsubmit").off("click").on("click", hsubmitListener);
});
</script>
My recommendation though is to not delete any elements that you don't want to go away in the first place.
EDIT:
I have not used jQuery in a while, because I prefer to use native JavaScript. In native JavaScript, is it required that you reattach event listeners whenever an element is removed and reinserted into the DOM.
The jQuery .on() handler is supposed to result in persistent event handling, adding the event listener to any element inserted into the DOM which matches the selector. I think this problem could also be solved by figured how why your code is somehow having jQuery remove the .on() event listeners.

Categories