JavaScript - Loop Function - javascript

I have this code which uses a typewriter animation to replace the placeholder text in a search bar:
https://codepen.io/anon/pen/vQmRjM
////////////////////////////
// Twitter: #mikedevelops
////////////////////////////
// your custome placeholder goes here!
var typetext = ["Text 1", "Text 2", "Text 3"];
var typetext = typetext[Math.floor(Math.random() * typetext.length)];
var searchBar = $('#search');
// placeholder loop counter
var phCount = 0;
// function to return random number between
// with min/max range
function randDelay(min, max) {
return Math.floor(Math.random() * (max-min+1)+min);
}
// function to print placeholder text in a
// 'typing' effect
function printLetter(string, el) {
// split string into character separated array
var arr = string.split(''),
input = el,
// store full placeholder
origString = string,
// get current placeholder value
curPlace = $(input).attr("placeholder"),
// append next letter to current placeholder
placeholder = curPlace + arr[phCount];
setTimeout(function(){
// print placeholder text
$(input).attr("placeholder", placeholder);
// increase loop count
phCount++;
// run loop until placeholder is fully printed
if (phCount < arr.length) {
printLetter(origString, input);
}
// use random speed to simulate
// 'human' typing
}, randDelay(50, 90));
}
// function to init animation
function placeholder() {
$(searchBar).attr("placeholder", "");
printLetter(typetext, searchBar);
}
window.setInterval(function(){
placeholder();
}, 3000);
I added a setInterval to loop through the different placeholder text every few seconds, however after the first iteration it just starts showing undefined.
Any ideas where I have went wrong?

The issue is you are trying to access the array item from an index which does not really exist. You have to reset the variable phCount in each call of setInterval():
window.setInterval(function(){
phCount = 0; // reset here
placeholder();
}, 3000);
Code Example:
////////////////////////////
// Twitter: #mikedevelops
////////////////////////////
// your custome placeholder goes here!
var typetext = ["Text 1", "Text 2", "Text 3"];
var typetext = typetext[Math.floor(Math.random() * typetext.length)];
var searchBar = $('#search');
// placeholder loop counter
var phCount = 0;
// function to return random number between
// with min/max range
function randDelay(min, max) {
return Math.floor(Math.random() * (max-min+1)+min);
}
// function to print placeholder text in a
// 'typing' effect
function printLetter(string, el) {
// split string into character seperated array
var arr = string.split(''),
input = el,
// store full placeholder
origString = string,
// get current placeholder value
curPlace = $(input).attr("placeholder"),
// append next letter to current placeholder
placeholder = curPlace + arr[phCount];
//console.log(curPlace + '::' + arr[phCount] + '::' + phCount)
setTimeout(function(){
// print placeholder text
$(input).attr("placeholder", placeholder);
// increase loop count
phCount++;
// run loop until placeholder is fully printed
if (phCount < arr.length) {
printLetter(origString, input);
}
// use random speed to simulate
// 'human' typing
}, randDelay(50, 90));
}
// function to init animation
function placeholder() {
$(searchBar).attr("placeholder", "");
printLetter(typetext, searchBar);
}
window.setInterval(function(){
phCount = 0;
placeholder();
}, 3000);
#import url(https://fonts.googleapis.com/css?family=PT+Sans:400,700);
html {
background: linear-gradient(90deg, #00c6ff 10%, #0072ff 90%);
font-family: 'PT Sans', Helvetica, Arial, sans-serif;
padding-top: 50px;
}
h1 {
text-shadow: 1px 1px 10px rgba(black, .5);
}
h1, h2 {
text-align: center;
color: white;
font-size: 2.5em;
line-height: 1.3em;
font-weight: 300;
}
h2 {
margin-top: 100px;
font-size: 1.3em;
font-style: italic;
font-weight: 100;
}
.body {
width: 100%;
height: 250px;
box-sizing: border-box;
}
input {
box-sizing: border-box;
font-size: 13px;
vertical-align: top;
}
.wrapper {
text-align: center;
position: relative;
height: 80px;
font-size: 0;
top: 50%;
transform: translateY(-50%);
}
.search {
padding: 0 30px;
font-size: 18px;
width: 60%;
max-width: 400px;
height: 80px;
border: 1px solid darken(white, 30%);
border-radius: 20px 0 0 20px;
}
.submit {
cursor: pointer;
border: none;
background: url('http://thesuiteworld.com/wp-admin/maint/search-icon-white-png-540.png') no-repeat center center, #1E1E20;
background-size: 35px 35px;
border-radius: 0 20px 20px 0;
padding: 15px 25px;
display: inline-block;
width: 150px;
height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<h1>Placeholder text with<br/> typing effect</h1>
<div class="wrapper">
<input class="search" type="text" id="search" />
<input class="submit" type="submit" value=" " />
</div>
</div>
<h2>Click search to reset</h2>

to remove undefined, You need to reset the char length loop setting
update following code to reset the string length to 0
if (phCount arr.length) {
printLetter(origString, input);
}
else {
phCount = 0;
}
and to display next string use following code
var wordcount =0;
window.setInterval(function(){
if (wordcount >= typetext.length) {
wordcount = 0;
}
placeholder(wordcount);
wordcount++;
}, 3000);
This will loop the array of string. This should work.

I think you have to reset the phCount to 0 when you reset the placeholder ($(searchBar).attr("placeholder", "")).

Related

I'm having trouble coming up with the winning logic for Tic Tac Toe

I'm going through The Odin Project and I'm working on completing Tic Tac Toe. I have almost everything completed but I'm stuck with coming up with the logic that checks what symbol (X or O) is being stored in each board and how to check for a winner. The directions say to store everything inside an array so I was doing that but I can't figure out how to update the array to store whichever symbol and check for a winner.
You’re going to store the gameboard as an array inside of a Gameboard object, so start there! Your players are also going to be stored in objects… and you’re probably going to want an object to control the flow of the game itself.
This is what I have completed so far.
I have a player function that stores each players name and the symbol that represents them.
const player = (name, symbol) => {
return { name, symbol };
};
const Player1 = player("Player X", "X");
const Player2 = player("Player O", "O");
I have a for loop that loops through my main div and creates 9 divs that represent the 9 squares for the game.
const createGameBoard = function () {
for (i = 0; i < 9; i++) {
gameBoardElements(); // Function that appends div to main board class
}
};
createGameBoard();
This is the function I'm using when I click on one of the divs. At the top I have the variable turn = 0 and after every click, it goes up by one. Using the modulus operator and my player function I'm making the text inside the board div either X or O and I'm changing the class so the div has a different background color. I know I could use the style feature but I don't like changing my html too much.
const board = document.querySelectorAll(".game-board");
board.forEach((el) => el.addEventListener("click", selectBoard));
// Decides which symbol to add to board: X or O
function selectBoard(e) {
e.target.appendChild(
createPElement(`${turn % 2 === 0 ? Player1.symbol : Player2.symbol}`)
);
turn++;
e.target.className = "complete-board";
e.target.removeEventListener("click", selectBoard); // prevent additional clicks
}
What I've tried
I've tried creating the array myGameBoard and appending each div to it inside the createGameBoard function
let myGameBoard = [
{board: 1, value: ""}
{board: 2, value: ""}
etc...
];
But I couldn't find a way to update the value of each div after I click to make it either an X or an O.
const currentTurn = document.getElementById("current-turn");
const getGameBoard = document.getElementById("board");
const btn = document.getElementById("btn");
let turn = 0;
// Main Player function. Gives default name and symbol
const player = (name, symbol) => {
return { name, symbol };
};
const Player1 = player("Player X", "X");
const Player2 = player("Player O", "O");
console.log(Player1);
// Creates a div and appends to board div
const gameBoardElements = function () {
const getBoard = document.getElementById("board");
const createBoard = document.createElement("div");
getBoard.appendChild(createBoard);
createBoard.className = "game-board";
};
// For loop that creates 9 divs and adds to board div
const createGameBoard = function () {
for (i = 0; i < 9; i++) {
gameBoardElements(); // Function that appends div to main board class
}
};
createGameBoard();
// Creates the [p] element that displays either X or O inside the gameboard div
function createPElement(symbol) {
let p = document.createElement("p");
p.textContent = symbol;
p.className = "text";
return p;
}
// Selects all game boards and assigns two event listener functions
const board = document.querySelectorAll(".game-board");
board.forEach((el) => el.addEventListener("click", selectBoard));
board.forEach((el) => el.addEventListener("click", updateBoard));
// Decides which symbol to add to board: X or O
function selectBoard(e) {
e.target.appendChild(
createPElement(`${turn % 2 === 0 ? Player1.symbol : Player2.symbol}`)
);
turn++;
e.target.className = "complete-board";
e.target.removeEventListener("click", selectBoard); // prevent additional clicks
}
// Updates the [p] tag that shows whose turn it is at the top
function updateBoard() {
currentTurn.textContent = `${
turn % 2 === 0 ? `${Player1.name} turn` : `${Player2.name} turn`
}`;
}
// Reset button text display
btn.addEventListener("mouseover", function () {
this.textContent = "Reset >>";
});
btn.addEventListener("mouseout", function () {
this.textContent = "Reset >";
});
body {
background-color: #fffdfa;
}
.title {
font-size: 42px;
font-family: "Dancing Script", cursive;
}
.current-turn {
font-size: 24px;
}
.content {
background-color: #fffdfa;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 700px;
width: 800px;
margin: 0 auto;
border-radius: 8px;
}
.board {
display: flex;
flex-flow: row wrap;
align-content: center;
justify-content: space-evenly;
gap: 10px;
background-color: #fff;
height: 500px;
width: 600px;
}
.board div,
.complete-board {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid #000;
background-color: #3c4048;
width: 175px;
height: 150px;
}
.board div:hover {
background-color: #f4e06d;
transform: scale(1.1);
transition: 0.8s;
box-shadow: 5px 5px 0 rgba(0, 0, 0, 0.5);
}
.complete-board {
background-color: #f4e06d !important;
}
.text {
font-size: 64px;
}
.btn {
display: inline-block;
background-color: #4649ff;
padding: 0.5em 2em;
margin-top: 20px;
cursor: pointer;
font-family: "Poor Story", cursive;
font-size: 2rem;
letter-spacing: 0.4rem;
transition: all 0.3s;
text-decoration: none;
}
.btn:hover {
box-shadow: 10px 10px 0 rgba(0, 0, 0, 0.5);
}
.parallelogram {
transform: skew(-20deg);
}
.skew-fix {
display: inline-block;
transform: skew(20deg);
}
<div class="content">
<p class="title">Tic Tac Toe</p>
<p class="current-turn" id="current-turn">Player X Turn</p>
<div id="board" class="board"></div>
<a id="btn" class="btn parallelogram" onclick="reset()">
<span class="skew-fix">Reset ></span>
</a>
</div>
The winning logic will include checking the element if
it is any one of the corner elements or if it is the element at the center.
it is any of the other elements.
If it is case 1, you will check all horizontal/vertical/diagonal elements if they are the same.
If it is case 2, you will check for all horizontal/vertical elements if they are the same.
If any of the above two statements are true, then you have won the game.
I hope I gave you some hint or logic.

Update element with ajax don't affect until for loop end

I want to print a lot of numbers ONE-BY-ONE with AJAX.
something like this: (each new line is update of previous line!)
output is:
1
12
123
1234
12345
123456
...
I tried a lot and read a lot of this same problem, but i couldn't find my right Answer.
The real problem is every FOR LOOP in javascript will NO affect the DOM after it will END the loop. I just want update the DOM inside the FOR LOOP while working on a long running job.
Please look at my code.
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var counter = 100; // i want assign counter = 2000000000
for (var i = 0; i < counter; i++) {
document.getElementById("print_here").innerHTML += i;
}
document.getElementById("foo").innerHTML = "done!";
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Thanks for any answer and help to solve this problem.
Your DOM is "locked" while it is being updated and redrawn ones the loop is done. You can free up the resource to let the DOM update each time wrapping your DOM change in a setTimeout, similar to:
setTimeout(function(){
document.getElementById("print_here").innerHTML += i;
},1);
To ensure setTimeout uses the correct value for i use let i instead of var i
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
}, 1);
}
document.getElementById("foo").innerHTML = "done!";
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
I want change the #foo into "done!" after the FOR statement is END
You could check if you are at your last item you process within the setTimeout, similar to:
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
var counter = 3000; // i want assign counter = 2000000000
for (let i = 0; i < counter; i++) {
setTimeout(function() {
document.getElementById("print_here").innerHTML += i;
if (i == counter - 1){
document.getElementById("foo").innerHTML = "done!";
}
}, 1);
}
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
You need to let the call stack complete so the browser can do its work on the page. If you bog down the one main thread, page updates aren't going to occur.
One way to do this is use setImmediate or nextTick. This is non-standard, so check this polyfill: https://www.npmjs.com/package/browser-next-tick
Basically, you do an iteration, then tell the browser to do the next iteration as soon as possible... and this occurs on a fresh call stack.
Here is the working code for you:
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var i, j, row = 5;
var html = "";
for (i = 1; i <= row; i++) {
for (j = 1; j <= i; j++) {
html += "<span>" + j + "</span>";
}
html += "</br>";
}
console.log(html);
document.getElementById("print_here").innerHTML = html;
}, 50);
}
#btn {
background: #1f1f1f;
padding: 10px;
font-weight: bolder;
color: #fff;
width: 50%;
margin: auto;
margin-top: 10px;
text-align: center;
cursor: pointer;
}
#print_here {
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">CLICK TO DO WORK</div>
<div id="foo"></div>
<div id="print_here"></div>
Rows is the number of rows you want to print.

How to do automoving from one page to another page and back to first page where pagination is there in table in html

I am trying to add automoving with pagination for table in HTML.
For eg i have table with 100 rows and then i am doing pagination for it with 10 records on one page.So there will be 10 pages with 10 records each.
I nedd to do it automatically so that user dont have to specifically click on the page and see.
I used paging.js
with below code
<style type="text/css">
.paging-nav {
text-align: right;
padding-top: 2px;
}
.paging-nav a {
margin: auto 1px;
text-decoration: none;
display: inline-block;
padding: 1px 7px;
background: #91b9e6;
color: white;
border-radius: 3px;
}
.paging-nav .selected-page {
background: #187ed5;
font-weight: bold;
}
.paging-nav,
#tableData {
'width: 400px;
margin: 0 auto;
font-family: Arial, sans-serif;
}
</style>
$(document).ready(function() {
$('#file').paging({limit:10});
});
Here file is id of table which is to be paginated. How can i go about changing page of table automatically? All answers are welcome.
Here is an example for how to start with it..
beware this is just an example, do not copy! for your own protection
//create
el = $("<table></table>");
for (var i = 1; i !== 100; i++) {
el.append("<tr><td>" + i + "</td><td>buuurp</td></tr>");
}
el.data("intStart", 1);
el.appendTo("body");
//fuction
function showRow(j = 10) { //default var j = 10; you can call showRow(50) for 50 as example
var i = $("table").data().intStart; //grabs data that hold the number of currect first element to view
$("tr").hide();
// hides all
$("tr").filter(function(index) {
return index >= i - 1 && index < i + j - 1; //jquery has 0-9 we count in 1-10 so -1
}).show(); //shows the one needed
$("table").data().intStart += j; //addes 'j' to the counter
if ($("table").data().intStart > $("table").children("tr").lenght) {
clearInterval(timer); //if we reach the end we can kill this
}
}
showRow();
var timer = setInterval(function() {
showRow();
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

resize the font size of the text box

I am using the below code to shrink the font size, but it will reduce only once, I want it to reduce every time when i enter a new character.
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()">
<style>
#allocatedVisionBudget {
width: 10%;
height: 93.3px;
background-color: rgba(255,255,255,0);
border: none;
font-size: 60px;
color: #7e8081;
padding: 0px;
}
</style>
<script>
function resizetext(){
var xy = document.getElementById('allocatedVisionBudget').value;
var x = document.getElementById("allocatedVisionBudget").style.fontSize=60;
//x;
xy;
var i=0;
var y=xy.length;
if(xy.length > 4) {
document.getElementById("allocatedVisionBudget").style.fontSize=x-20;
}
}
</script>
You only have one condition:
if(xy.length > 4) {
so it only resizes when you change the lenght from 4 to 5 or from 5 to 4.
Either add more conditions, or better make the fontSize calculated as a function of the text length:
document.getElementById("allocatedVisionBudget").style.fontSize=f(xy);
function resizetext(e){
var xy = document.getElementById('allocatedVisionBudget').value;
var l=xy.length;
var f = Math.ceil(80/xy.length) || 60;
console.log(e, xy, l, f);
document.getElementById("allocatedVisionBudget").style.fontSize=f + "px";
}
#allocatedVisionBudget {
width: 10%;
height: 93.3px;
background-color: rgba(255,255,255,0);
border: #f00 solid 1px;
font-size: 60px;
color: #7e8081;
padding: 0px;
}
Input: <input type="text" value="" id="allocatedVisionBudget" onkeypress="resizetext(event)" onkeydown="resizetext(event)" onkeyup="resizetext(event)">
a few things you need to do
when you set to input element font size it should wrap as string with px or % etc...
this is example:
var x = document.getElementById("allocatedVisionBudget").style.fontSize
= "60px";
when you use x-20 the x is string so you need to use the parseInt(x) function
here is a demo for your code
HTML:
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()">
javascript:
window.resizetext = function() {
var xy = document.getElementById('allocatedVisionBudget').value;
var x = document.getElementById("allocatedVisionBudget").style.fontSize = "60px";
var i = 0;
var y = xy.length;
if (xy.length > 4) {
document.getElementById("allocatedVisionBudget").style.fontSize = (parseInt(x) - 20) + "px";
}
};
CSS:
#allocatedVisionBudget {
width: 100%;
height: 93.3px;
background-color: rgba(255, 255, 255, 0);
font-size: 60px;
color: #7e8081;
padding: 0px;
}

Event Handlers On Newly Created Elements

I have a web app with a number of textareas and the ability to add more if you wish.
When you shift focus from one textarea to another, the one in focus animates to a larger size, and the rest shrink down.
When the page loads it handles the animation perfectly for the initial four boxes in the html file, but when you click on the button to add more textareas the animation fails to accomodate these new elements... that is, unless you place the initial queries in a function, and call that function from the addelement function tied to the button.
But!, when you do this it queries as many times as you add a new element. So, if you quickly add, say 10, new textareas, the next time you lay focus on any textarea the query runs 10 times.
Is the issue in my design, or jQueries implementation? If the former, how better can I design it, if it is the latter, how can I work around it?
I've tried to chop the code down to the relevant bits... I've tried everything from focus and blur, to keypresses, the latest is on click.
html::
<html>
<head>
<link rel="stylesheet" type="text/css" href="./sty/sty.css" />
<script src="./jquery.js"></script>
<script>
$().ready(function() {
var $scrollingDiv = $("#scrollingDiv");
$(window).scroll(function(){
$scrollingDiv
.stop()
//.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "fast" );
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>boxdforstacks</title>
</head>
<body>
<div class="grid">
<div class="col-left" id="left">
<div class="module" id="scrollingDiv">
<input type="button" value="add" onclick="addele()" />
<input type="button" value="rem" onclick="remele()" />
<p class="display">The value of the text input is: </p>
</div>
</div> <!--div class="col-left"-->
<div class="col-midd">
<div class="module" id="top">
<p>boxa</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxa" ></textarea>
<p>boxb</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxb"></textarea>
<p>boxc</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxc"></textarea>
<p>boxd</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxd"></textarea>
</div>
</div> <!--div class="col-midd"-->
</div> <!--div class="grid"-->
</body>
</html>
<script type="text/javascript" src="boxd.js"></script>
js:
function onit(){
$('textarea').on('keyup change', function() {
$('p.display').text('The value of the text input is: ' + $(this).val());
});
}
$('textarea').on("click",function(){
//alert(this.id.substring(0,3));
if ( this.id.substring(0,3) == 'box' ){
$('textarea').animate({ height: "51" }, 1000);
$(this).animate({ height: "409" }, 1000);
} else {
$('textarea').animate({ height: "51" }, 1000);
}
}
);
var boxfoc="";
var olebox="";
var numb = 0;
onit();
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box'+num;
newbox.setAttribute('id',newboxid);
newbox.setAttribute('class','tecksd');
newbox.setAttribute('placeholder','('+romu+')');
tops.appendChild(newbox);
numb = num;
onit();
} //addele(), add element
function remele(){
var tops = document.getElementById('top');
var boxdone = document.getElementById(boxfoc);
tops.removeChild(boxdone);
} // remele(), remove element
function romanise (num) {
if (!+num)
return false;
var digits = String(+num).split(""),
key = ["","c","cc","ccc","cd","d","dc","dcc","dccc","cm",
"","x","xx","xxx","xl","l","lx","lxx","lxxx","xc",
"","i","ii","iii","iv","v","vi","vii","viii","ix"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
} // romanise(), turn numbers into roman numerals
css :
.tecksd {
width: 97%;
height: 51;
resize: none;
outline: none;
border: none;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px 1px #0044FF;*/
}
.tecksded {
width: 97%;
resize: none;
outline: none;
border: none;
overflow: auto;
position: relative;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px #FFDD00;*/
}
/*#postcomp {
width: 500px;
}*/
* {
#include box-sizing(border-box);
}
$pad: 20px;
.grid {
background: white;
margin: 0 0 $pad 0;
&:after {
/* Or #extend clearfix */
content: "";
display: table;
clear: both;
}
}
[class*='col-'] {
float: left;
padding-right: $pad;
.grid &:last-of-type {
padding-right: 0;
}
}
.col-left {
width: 13%;
}
.col-midd {
width: 43%;
}
.col-rght {
width: 43%;
}
.module {
padding: $pad;
}
/* Opt-in outside padding */
.grid-pad {
padding: $pad 0 $pad $pad;
[class*='col-']:last-of-type {
padding-right: $pad;
}
}
body {
padding: 10px 50px 200px;
background: #FFFFFF;
background-image: url('./backgrid.png');
}
h1 {
color: black;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
p {
color: white;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
You should use the following:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on("click", "textarea", function () {
event.preventDefault();
alert('testlink');
});
Since the textarea is added dynamically, you need to use event delegation to register the event handler.
Try
$(document).on('click', 'textarea', function() {
// do something
});
The issue is you are binding the textareas only on the page load. I made a JSFiddle with working code: http://jsfiddle.net/VpABC/
Here's what I changed:
I wrapped:
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
in a function so it looked like this:
function bindTextAreas() {
$('textarea').unbind("click");
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
}
bindTextAreas();
What this does is it allows you to call this function, bindTextAreas, whenever you create a new textarea. This will unbind all the current events than rebind them. This will make it so your new textarea is has the click handler setup.
An place where this function is called is in the addele function like this:
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box' + num;
newbox.setAttribute('id', newboxid);
newbox.setAttribute('class', 'tecksd');
newbox.setAttribute('placeholder', '(' + romu + ')');
tops.appendChild(newbox);
numb = num;
onit();
bindTextAreas();
} //addele(), add element
Notice the bindTextAreas(); line near the bottom. This reloads all the click handlers.

Categories

Resources