setTimeOut for button cliks in javascript - javascript

I'm trying to make it so the user cannot press a number button until the start button is pressed. I've searched w3schools and other sites, but cannot find a solution. Any help would be appreciated, even if you can point me to a website. My instructor has informed use that we would need to find any solutions to our problems online. Even suggestions for a good javascript book would be helpful as there is no text book for the class and he doesn't teach it.
<body>
<h3 style="margin-left: 15px">This is Your TARGET:</h3>
<div id="randomNum" class="display" style="margin-top: -20px; margin-bottom: 30px">0</div>
<!-- Start button -->
<button onclick="setTimeout(myFunction, 5000);">Start</button>
<!-- Total value text -->
<div id="text_total">0</div>
<!-- Number buttons -->
<div class="number_button" onclick="change_total(1)">1</div>
<div class="number_button" onclick="change_total(2)">2</div>
<div class="number_button" onclick="change_total(3)">3</div>
<div class="number_button" onclick="change_total(4)" style="clear: left">4</div>
<div class="number_button" onclick="change_total(5)">5</div>
<div class="number_button" onclick="change_total(6)">6</div>
<div class="number_button" onclick="change_total(7)" style="clear: left; margin-bottom: 30px">7</div>
<div class="number_button" onclick="change_total(8)" style="margin-bottom: 30px">8</div>
<div class="number_button" onclick="change_total(9)" style="margin-bottom: 30px">9</div>
<h3 style="clear: left; margin-left: 58px">COUNTER!</h3>
<div id="counter" class="display" style="clear: left; margin-top: -20px">0</div>
<script>
// Variables
var total = 0;
var target;
var clicks = 0;
window.onload = randomNumber();
// Functions
function change_total(arg) { // This takes button input and changes the total value
total = total + arg;
clicks = clicks + 1;
update_total();
if (total == target) {
alert("You win!"); // popup window with message
total = 0; // reset for next round
clicks = 0; // resets the click counter
randomNumber(); //gets new number for next round
update_total();
}if (total > target) {
alert("BUSTED!!");
total = 0;
clicks = 0;
randomNumber();
update_total();
}
update_clicks();
}
function myFunction() {
alert("You failed to reach the target in time!");
}
function update_total() { // Updates the text on the screen to show the current total
document.getElementById("text_total").innerHTML = total;
}
function randomNumber() { // returns a random number between 25 and 75
target = Math.floor(Math.random() * (50) + 25);
document.getElementById("randomNum").innerHTML = target;
}
function update_clicks() { // lets user know how many clicks
document.getElementById("counter").innerHTML = "You clicked the mouse " + clicks + " times.";
}
</script>
</body>

You may try for this,
I have tested it on my end, see below,
i just use isStart boolean variable to check is game start or not.
<body>
<h3 style="margin-left: 15px">This is Your TARGET:</h3>
<div id="randomNum" class="display" style="margin-top: -20px; margin-bottom: 30px">0</div>
<!-- Start button -->
<button onclick="startGame()">Start</button>
<!-- Total value text -->
<div id="text_total">0</div>
<!-- Number buttons -->
<div class="number_button" onclick="change_total(1)">1</div>
<div class="number_button" onclick="change_total(2)">2</div>
<div class="number_button" onclick="change_total(3)">3</div>
<div class="number_button" onclick="change_total(4)" style="clear: left">4</div>
<div class="number_button" onclick="change_total(5)">5</div>
<div class="number_button" onclick="change_total(6)">6</div>
<div class="number_button" onclick="change_total(7)" style="clear: left; margin-bottom: 30px">7</div>
<div class="number_button" onclick="change_total(8)" style="margin-bottom: 30px">8</div>
<div class="number_button" onclick="change_total(9)" style="margin-bottom: 30px">9</div>
<h3 style="clear: left; margin-left: 58px">COUNTER!</h3>
<div id="counter" class="display" style="clear: left; margin-top: -20px">0</div>
<script>
// Variables
var total = 0;
var target;
var clicks = 0;
window.onload = randomNumber();
var isStart=false;
// Functions
function change_total(arg) { // This takes button input and changes the total value
if(isStart){
total = total + arg;
clicks = clicks + 1;
update_total();
if (total == target) {
alert("You win!"); // popup window with message
total = 0; // reset for next round
clicks = 0; // resets the click counter
randomNumber(); //gets new number for next round
update_total();
isStart=false;
}if (total > target) {
alert("BUSTED!!");
total = 0;
clicks = 0;
randomNumber();
update_total();
isStart=false;
}
update_clicks();
}
else{
alert('please start the game');
}
}
function myFunction() {
alert("You failed to reach the target in time!");
}
function update_total() { // Updates the text on the screen to show the current total
document.getElementById("text_total").innerHTML = total;
}
function randomNumber() { // returns a random number between 25 and 75
target = Math.floor(Math.random() * (50) + 25);
document.getElementById("randomNum").innerHTML = target;
}
function update_clicks() { // lets user know how many clicks
document.getElementById("counter").innerHTML = "You clicked the mouse " + clicks + " times.";
}
function startGame(){
isStart=true;
}
</script>
</body>

Related

Animation and transition property with setTimeout() function

I'm fairly new to JS, and I'm trying to make a simple text slide animation. However, when the animation event is activated the first time, the transition property doesn't apply. Every time after that it works fine.
So I'm struggling with the first execution of the slide animation.
Here is the code:
function slide_animation(direction){
// Init
let text = document.querySelector(".story .box .right-part .text");
let text_html = text.innerHTML;
let text_slide = [
"Text n°1",
'Text n°2',
'Text n°3'
];
let current_slide = 0;
// Looking for the current_slide
for(let i=0;i<text_slide.length;i++){
if (text_slide[i]==text_html){current_slide = i};
}
// Calculating the next slide position
if (direction=='right'){
if (current_slide >= text_slide.length-1){
current_slide = 0;
}
else {current_slide+=1;}
}
else {
if (current_slide <= 0){
current_slide = text_slide.length-1;
}
else {
current_slide = current_slide-=1;
}
}
// Animation
setTimeout(()=>{
text.style.transition = '0.5s';
text.style.opacity = 0;
text.style.left = '100px';
},250);
setTimeout(()=>{
text.innerHTML = text_slide[current_slide];
text.style.opacity = 1;
text.style.left = '0px';
},750)
}
.story .box .right-part .text-container .text {
line-height: 1.25;
position: relative;
}
<div class="box">
<div class="left-part">
<div class="text-container">
<p class="text">
<span class="text-padding fontsize-md">----</span>
</p>
</div>
<div class="buttons-container">
<button class="backward" onclick="slide_animation('left')"></button>
<button class="forward" onclick="slide_animation('right')"></button>
</div>
</div>
<div class="right-part">
<div class="text-container">
<p class="text fontsize-sm">Text n°1</p>
</div>
</div>
</div>
Anyway , it is fixed. I added another setTimeOut that did nothing really useful on the text , i placed it just before the others setTimeOut and it seems to work out properly.
Here is what is inserted :
setTimeout(()=>{
text.style.left=0;
},0)

Print after dragged items are placed

I need the final page (after going through and submitting everything) to print with the student names dragged into the team boxes, but whatever I try with the display/float/position properties, the student cards won't show when printing the page.
My code is using interact_min.js from Interact.io as well which is in the codepen project.
Codepen Project Link
Here is a screenshot of the final page when students are distributed into teams. I need the page to print out like this for teachers. (Class sizes vary so it has to work for >= 8 students which will be #ofTeams >= 2)
I have tried quite a few "fixes" from various sites, but none of them are working for me. Any help is appreciated. I am relatively new to coding, so please explain thoroughly.
This is what it looks like when I try to print.
Here I have changed the scale to 30% and you can see 7/8 of the student cards.
function isInputNumber(){
const inputNumber = parseInt($("#numberOfStudents").val());
if(isNaN(inputNumber)) {
alert('Must input a number');
return ;
} else {
return ;
}
}
function isNumberBigEnough() {
const numberS = parseInt($("#numberOfStudents").val());
if (numberS > 7 && isInputNumber) {
$('#submitTeams').removeAttr('disabled');
} else {
return ;
}
}
$('#numberOfStudents').keyup(isInputNumber).keyup(isNumberBigEnough);
//First submit function on the team form gives the user a response
$( "#submitTeams" ).click(function( event ) {
event.preventDefault();
const numberOfStudents = parseInt($("#numberOfStudents").val());
const divideByFour = numberOfStudents % 4;
let responseHTML = '<p id="numberOverall">'+numberOfStudents+'</p><p class="responseText">';
if (divideByFour === 0){
responseHTML += 'You will have ' + numberOfStudents / 4 + ' teams of 4 in your class.';
}
else if (divideByFour === 1) {
responseHTML += 'You will have ' + (numberOfStudents - 1) /4 + ' teams of 4 in your class and one team of 5.';
}
else if (divideByFour === 2) {
responseHTML += 'You will have ' + (numberOfStudents - 6) /4 + ' teams of 4 in your class and two teams of 3.';
}
else {
responseHTML += 'You will have ' + (numberOfStudents - 3) /4 + ' teams of 4 in your class and one team of 3.';
}
responseHTML += '</p>';
$('#studentNumberResponse').css('display', 'block').html(responseHTML);
//second submit function on the team form that makes the second form (studentsForm)
let responseHTMLSecond = '<div class="card-block"> <h4 class="card-title">Step 2: Enter Your Students</h4> <p class="card-text">Add your students to create each individual team.</p> <form id="studentsForm" onsubmit="return false;">';
let i = 0;
do {
i++;
responseHTMLSecond += '<h4 class="numberingStudents">Student ' + i + '</h4>';
responseHTMLSecond += '<div class="form-group"> <h4> <input type="text" class="form-control" id="studentFirstName'+i+'" aria-describedby="studentFirstName" placeholder="First Name"> </div> <div class="form-group"> <input type="text" class="form-control" id="studentLastName'+i+'" aria-describedby="studentLastName" placeholder="Last Name"> </div> <div class="form-group"> <label for="exampleSelect1">Select Student Level</label> <select class="form-control" id="exampleSelect'+i+'"> <option>High</option> <option>Mid-High</option> <option>Mid-Low</option> <option>Low</option> </select> </div>';
} while (i < numberOfStudents);
responseHTMLSecond += '<button type="submit" class="btn btn-primary" id="submitStudents" onclick="addStudentsClicked()">Submit</button> </form> <small class="text-muted">Click the Submit button when you have finished adding all students or after making any changes to student names.</small> </div>';
$('#secondsStep').show().html(responseHTMLSecond);
$('#numberOfStudents').val('');
});
//submit function on the studentsForm to show a response
function addStudentsClicked()
{
let responseHTMLThird = '<h4 class="card-title">Step 3: Review Class Roster</h4> <p class="card-text">Review your class roster before moving on to the next step. If you need to make any changes, scroll back up to Step 2 and hit submit again after changes have been made.</p>';
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
let Students = [];
for (i =1; i < numberOfStudentsTwo+1; i++) {
let $firstName = $('#studentFirstName'+i+'').val();
let $lastName = $('#studentLastName'+i+'').val();
let $studentLevel = $('#exampleSelect'+i+' :selected').text();
Students[i] = new Object({$firstName, $lastName, $studentLevel});
responseHTMLThird += '<p class="studentRosterList">'+Students[i].$firstName+' '+Students[i].$lastName+' : '+Students[i].$studentLevel+'</p>';
}
responseHTMLThird += '<button type="submit" class="btn btn-primary" id="submitOverall" onclick="finalSubmit()">Submit</button>';
alert('Scroll down to review your student roster.');
$('#studentListResponse').show().html(responseHTMLThird);
}
function finalSubmit () {
if(confirm("Are you sure everything is correct?") === true){
$('.hideMe').hide();
document.location.href = "#top";
makingCards();
} else {
alert('Please make your changes before submitting again.');
}
}
function makingCards () {
let makeTeams = '<div class="card-block clearfix" id="makeTeams"><h4 class="card-title">Step 4: Make Teams</h4><p class="card-text">Use your mouse to click and drag students into team groupings. Remember, you don\'t want to have 2 Highs or 2 Lows on a team together.</p></div>';
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
const numero = numberOfStudentsTwo % 4;
let fourthResponse = '';
let StudentsTwo = [];
for (i =1; i < numberOfStudentsTwo+1; i++) {
let $firstName = $('#studentFirstName'+i+'').val();
let $lastName = $('#studentLastName'+i+'').val();
let $studentLevel = $('#exampleSelect'+i+' :selected').text();
StudentsTwo[i] = new Object({$firstName, $lastName, $studentLevel});
fourthResponse += '<div class="card teamCard draggable" style="width: 10rem;"><div class="card-block teamCard-block">';
fourthResponse += '<h4 class="card-title teamCard-title">'+ StudentsTwo[i].$firstName;
fourthResponse += ' '+ StudentsTwo[i].$lastName;
fourthResponse += '</h4>';
fourthResponse += '<h6 class="card-subtitle mb-2 text-muted teamCard-subtitle">Student Level: '+ StudentsTwo[i].$studentLevel;
fourthResponse += '</h6>';
fourthResponse += '</div></div>';
}
$('#top').append(makeTeams);
teamNumber();
$('#teamDropBox').after(fourthResponse);
$('.teamCard').mousedown(handle_mousedown);
}
function teamNumber (numero) {
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
let $teamDrops = '<table id="teamDropBox"><tbody>';
if (numero === 0){
let $teams = numberOfStudentsTwo / 4;
for (j=1; j < $teams; j++){
$teamDrops += '<tr><th class="teamDrops">Team ' + j +':</th><td class="dropzone"></td></tr>';
}
} else if (numero === 1) {
let $teams = (numberOfStudentsTwo - 1) / 4 + 1;
for (j=1; j < $teams; j++){
$teamDrops += '<tr><th class="teamDrops">Team ' + j +':</th><td class="dropzone"></td></tr>';
}
} else if (numero === 2) {
let $teams = (numberOfStudentsTwo - 6) / 4 + 2;
for (j=1; j < $teams; j++){
$teamDrops += '<tr><th class="teamDrops">Team ' + j +':</th><td class="dropzone"></td></tr>';
}
} else {
let $teams = (numberOfStudentsTwo - 3) / 4 + 1;
for (j=1; j < $teams; j++){
$teamDrops += '<tr><th class="teamDrops">Team ' + j +':</th><td class="dropzone"></td></tr>';
}
$teamDrops += '</tbody></table>';
}
$('#makeTeams').append($teamDrops);
}
//dragging code from online site - changed to interact.js code below
/*
function handle_mousedown(e){
window.my_dragging = {};
my_dragging.pageX0 = e.pageX;
my_dragging.pageY0 = e.pageY;
my_dragging.elem = this;
my_dragging.offset0 = $(this).offset();
function handle_dragging(e){
var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
$(my_dragging.elem)
.offset({top: top, left: left});
}
function handle_mouseup(e){
$('body')
.off('mousemove', handle_dragging)
.off('mouseup', handle_mouseup);
}
$('body')
.on('mouseup', handle_mouseup)
.on('mousemove', handle_dragging);
}
*/
//interact.js code here:
// target elements with the "draggable" class
interact('.draggable')
.draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
restriction: ".dropzone",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
// enable autoScroll
autoScroll: true,
// call this function on every dragmove event
onmove: dragMoveListener,
});
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
// enable draggables to be dropped into this
interact('.dropzone').dropzone({
// only accept elements matching this CSS selector
accept: '.draggable',
// Require a 75% element overlap for a drop to be possible
overlap: 0.75,
// listen for drop related events:
ondropactivate: function (event) {
// add active dropzone feedback
event.target.classList.add('drop-active');
},
ondropdeactivate: function (event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active');
}
});
* {
box-sizing: border-box;
}
#studentNumberResponse, #secondsStep, #studentListResponse {
display: none;
}
#numberOverall {
color: #fff;
}
.responseText {
font-size: 2rem;
}
.teamCard {
float: right;
margin: 2rem;
}
table {
border-collapse: collapse;
border: 1px solid grey;
margin: 3rem 0 5rem 1rem;
float: left;
}
table th {
border: 1px solid grey;
vertical-align: center;
text-align: center;
width: 18rem;
padding: 0 5rem;
text-transform: uppercase;
font-size: 2rem;
}
table td {
height: 15rem;
border: 1px solid grey;
width: 50rem;
}
#media print {
body * {
visibility: hidden;
}
#top, #top * {
visibility: visible;
}
#top {
position: absolute;
left: 0;
top: 0;
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnPoint Team Generator</title>
<meta name="description" content="OnPoint Team Generator">
<meta name="author" content="MeganRoberts">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div class="card" id="top">
<h3 class="card-header" style="text-align: center;">OnPoint Team Generator</h3>
<div class="card-block hideMe">
<h4 class="card-title">Step 1: Number of Teams</h4>
<p class="card-text">How many students do you have in your class?</p>
<form id="teamForm">
<div class="form-group">
<input type="text" class="form-control" id="numberOfStudents" aria-describedby="numberStudents" placeholder="Enter Number of Students" data-toggle="tooltip" data-placement="top" title="Please enter a number larger than 7.">
</div>
<button type="submit" class="btn btn-primary" id="submitTeams" disabled>Submit</button>
</form>
</div>
</div>
<div class="card hideMe">
<div class="card-block" id="studentNumberResponse">
</div>
</div>
<div id="secondsStep" class="card hideMe">
</div>
<div id="listResponse" class="card hideMe">
<div class="card-block" id="studentListResponse">
</div>
</div>
<script src="interact_min.js"></script>
<script src="app.js"></script>
</body>
</html>
I had to overhaul my code a bit to get it to print. I changed the drag and drop to jquery UI sortable instead.
Codepen Project
Requires jquery UI to fully function so check out the codepen link -> below is the "final" code
$('#printbtn').hide();
$('#studentNumberResponse').hide();
$('#secondsStep').hide();
$('#listResponse').hide();
//Checking to make sure the input is a number for the rest of the program to work
function isInputNumber(){
//get user input
const inputNumber = parseInt($("#numberOfStudents").val());
//check if input is a number or not
if(isNaN(inputNumber)) {
alert('Must input a number');
return ;
} else {
return ;
}
}
//Checking to make sure that the input is larger than 7 in order to create teams and remove the disabled from the submit button
function isNumberBigEnough() {
//get user input
const numberS = parseInt($("#numberOfStudents").val());
//check to make sure that the number is large enough and then remove the disabled attribute
if (numberS > 7 && isInputNumber) {
$('#submitTeams').removeAttr('disabled');
} else {
return ;
}
}
//watching user input to determine if they can submit using the above functions
$('#numberOfStudents').keyup(isInputNumber).keyup(isNumberBigEnough);
//First submit function on the team form gives the user a response of how many teams and what kind of teams depending on their input
$( "#submitTeams" ).click(function( event ) {
//prevent the window from refeshing after submit event
event.preventDefault();
//get user input
const numberOfStudents = parseInt($("#numberOfStudents").val());
//DRY for repeated calc
const divideByFour = numberOfStudents % 4;
//response to user to tell them the number of teams there will be in their class
let responseHTML = '<p id="numberOverall">'+numberOfStudents+'</p><p class="responseText">';
if (divideByFour === 0){
responseHTML += 'You will have ' + numberOfStudents / 4 + ' teams of 4 in your class.';
}
else if (divideByFour === 1) {
responseHTML += 'You will have ' + (numberOfStudents - 5) /4 + ' teams of 4 in your class and one team of 5.';
}
else if (divideByFour === 2) {
responseHTML += 'You will have ' + (numberOfStudents - 6) /4 + ' teams of 4 in your class and two teams of 3.';
}
else {
responseHTML += 'You will have ' + (numberOfStudents - 3) /4 + ' teams of 4 in your class and one team of 3.';
}
responseHTML += '</p>';
//show and add the above html to the studentNumberResponse so the user can view the response
$('#studentNumberResponse').css('display', 'block').html(responseHTML);
//second submit function on the team form that makes the second form (studentsForm) to allow the user to enter student names for sorting later
//create form to match the student numbered entered
let responseHTMLSecond = '<div class="card-block"> <h4 class="card-title"><span>Step 2:</span> Enter Your Students</h4> <p class="card-text lightText">Add your students to create each individual team.</p> <form id="studentsForm" onsubmit="return false;">';
//needed for the do while loop
let i = 0;
do {
i++;
//firstname and lastname and level input for each student
responseHTMLSecond += '<h4 class="numberingStudents">Student ' + i + '</h4>';
responseHTMLSecond += '<div class="form-group"> <input type="text" class="form-control" id="studentFirstName'+i+'" aria-describedby="studentFirstName" placeholder="First Name"> </div> <div class="form-group"> <input type="text" class="form-control" id="studentLastName'+i+'" aria-describedby="studentLastName" placeholder="Last Name"> </div> <div class="form-group"> <label for="exampleSelect1">Select Student Level</label> <select class="form-control" id="exampleSelect'+i+'"> <option>High</option> <option>Mid-High</option> <option>Mid-Low</option> <option>Low</option> </select> </div>';
} while (i < numberOfStudents);
//add submit button to end of the student info form
responseHTMLSecond += '<button type="submit" class="btn btn-primary opbtn" id="submitStudents" onclick="addStudentsClicked()">Submit</button> </form> <small class="text-muted">Click the Submit button when you have finished adding all students or after making any changes to student names.</small> </div>';
//show and add the above html for the student info form
$('#secondsStep').show().html(responseHTMLSecond);
//clear the number of students input field
$('#numberOfStudents').val('');
});
//submit function on the studentsForm to show the class roster for a final check before moving on
function addStudentsClicked() {
//html for the third response
let responseHTMLThird = '<h4 class="card-title"><span>Step 3:</span> Review Class Roster</h4> <p class="card-text lightText">Review your class roster before moving on to the next step. If you need to make any changes, scroll back up to Step 2 and hit submit again after changes have been made.</p>';
//hidden numberOfStudents to use in future functions like this one = user input from first step
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
//create empty array to add students from student info form
let Students = [];
//for each student, create an object with the input information from the previous form
for (i =1; i < numberOfStudentsTwo+1; i++) {
let $firstName = $('#studentFirstName'+i+'').val();
let $lastName = $('#studentLastName'+i+'').val();
let $studentLevel = $('#exampleSelect'+i+' :selected').text();
Students[i] = new Object({$firstName, $lastName, $studentLevel});
//use the data in the array to print out a student roster for the user to review
responseHTMLThird += '<p class="studentRosterList">'+Students[i].$firstName+' '+Students[i].$lastName+' : '+Students[i].$studentLevel+'</p>';
}
//final submit button for the user to click on after reviewing the student roster
responseHTMLThird += '<button type="submit" class="btn btn-primary opbtn" id="submitOverall" onclick="finalSubmit()">Submit</button>';
//response appears below the viewport, so an alert to let them know to scroll down
alert('Scroll down to review your student roster.');
//show and add response to the page
$('#listResponse').show();
$('#studentListResponse').show().html(responseHTMLThird);
}
//asking the user if everything is correct before moving on (cant go back and change)
function finalSubmit () {
if(confirm("Are you sure everything is correct?") === true){
//hide forms that are no longer needed
$('.hideMe').hide();
//move the user back to the top of the screen
document.location.href = "#top";
//cal the function to make the team boxes
makingTeams();
} else {
alert('Please make your changes before submitting again.');
}
}
//making the teams dropzone containers
function makingTeams () {
//header for step 4
let makeTeams = '<div class="card-block clearfix printMe" id="makeTeams"><h4 class="card-title"><span>Step 4:</span> Make Teams</h4><p class="card-text lightText">Use your mouse to click and drag students into team groupings. Remember, you don\'t want to have 2 Highs or 2 Lows on a team together.</p><p id="reminderTeams" class="lightText"></p></div>';
//get the number of students for creating the correct amount of teams
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
//get the remainder to split the loops depending on the number of students
const numero = numberOfStudentsTwo % 4;
//start the response string
let $teamDrops = '';
//creating the team ul for sorting ui
if (numero === 0){
//if equally divisible, then the number divided by four = the number of teams
let $teams = numberOfStudentsTwo / 4;
for (let j=1; j < $teams +1; j++){
$teamDrops += '<ul class="teamDrops connected printMe"><h4>Team ' + j +':</h4></ul>';
}
} else if (numero === 1) {
//if remainder 1, then subtract the one team of five from the total, divide by four to get the number of teams and add back the 1 team of 5
let $teams = (numberOfStudentsTwo - 5) / 4 + 1;
for (let j=1; j < $teams +1; j++){
$teamDrops += '<ul class="teamDrops connected printMe"><h4>Team ' + j +':</h4></ul>';
}
} else if (numero === 2) {
//if remainder 2, then subtract 6 for the two teams of 3 then divide by four to get the number of teams and add back the 2 teams of 3
let $teams = (numberOfStudentsTwo - 6) / 4 + 2;
for (let j=1; j < $teams+1; j++){
$teamDrops += '<ul class="teamDrops connected printMe"><h4>Team ' + j +':</h4></ul>';
}
} else {
//if remainder 3, then subtract the one team of 3 then divide by four and add back the 1 team of 3
let $teams = (numberOfStudentsTwo - 3) / 4 + 1;
for (let j=1; j < $teams+1; j++){
$teamDrops += '<ul class="teamDrops connected printMe"><h4>Team ' + j +':</h4></ul>';
}
}
//append the instructions to the top
$('#top').append(makeTeams);
//append the team ul drops to the top
$('#top').append($teamDrops);
//create empty list for student roster to fill into
let studentRoster = '<ul id="rosterDrag" class="connected printMe"><h4>Student Roster</h4></ul>';
//append the student roster to the top
$('#top').append(studentRoster);
//call the function to make the student roster list for dragging
makingCards();
}
//making the individual student cards based off of the input from step 2
function makingCards () {
//get student number info
const numberOfStudentsTwo = parseInt($("#numberOverall").text());
//start response html
let fourthResponse = '';
//start array to hold student data
let StudentsTwo = [];
//start loop to create object for each student
for (i =1; i < numberOfStudentsTwo+1; i++) {
let $firstName = $('#studentFirstName'+i+'').val();
let $lastName = $('#studentLastName'+i+'').val();
let $studentLevel = $('#exampleSelect'+i+' :selected').text();
StudentsTwo[i] = new Object({$firstName, $lastName, $studentLevel});
//add html to the response
fourthResponse += '<li class="card teamCard'+i+' draggable printMe" style="width: 10rem;">';
fourthResponse += '<h4 class="card-title teamCard-title">'+ StudentsTwo[i].$firstName;
fourthResponse += ' '+ StudentsTwo[i].$lastName;
fourthResponse += '</h4>';
fourthResponse += '<h6 class="card-subtitle mb-2 text-muted teamCard-subtitle">Student Level: '+ StudentsTwo[i].$studentLevel;
fourthResponse += '</h6>';
fourthResponse += '</li>';
}
//append the student roster to the ul
$('#rosterDrag').append(fourthResponse);
//jquery ui to sort students into teams
$( function() {
//making the individual team ul's sortable and connected to each other
$( ".teamDrops" ).sortable({
connectWith: ".connected"
}).disableSelection();
//making the student roster ul sortable and connected to the others
$( "#rosterDrag" ).sortable({
connectWith: ".connected"
}).disableSelection();
});
//get number of teams info from first response
let reminder = $('.responseText').text();
//set reminder text to last page
$('#reminderTeams').text(reminder);
//show the print button
$('#printbtn').show();
}
//print the page
function pdfPrint () {
//hide unwanted elements from the printed page
$('#printbtn').hide();
$('#rosterDrag').hide();
$('#makeTeams').hide();
//print the window
window.print();
}
* {
box-sizing: border-box;
}
body {
background-color: lightgrey;
}
#opArrows {
width: 10rem;
height: auto;
}
.opbtn {
color: #fff;
background-color: #434343;
border-color: #434343;
}
.opbtn:hover {
color: #fff;
background-color: #f5822d;
border-color: #f5822d;
}
.opbtn:disabled {
color: #fff;
background-color: #8c8c8c;
border-color: #8c8c8c;
}
#title {
background-color: #0a6c8e;
color: black;
}
h4 span {
color: #c4da59;
}
#numberOverall {
color: #fff;
display: none;
}
#studentNumberResponse {
padding-top: 2rem;
font-size: 1.5rem;
color: #8c8c8c;
}
#listResponse p:nth-child(odd) {
background-color: lightgrey;
}
.studentRosterList {
width: 25%;
padding-left: 0.5rem;
}
.lightText {
color: #8c8c8c;
}
.form-group {
width: 50%;
}
.teamDrops, #rosterDrag {
border: 1px solid #eee;
width: 75%;
min-height: 5rem;
list-style-type: none;
margin: 1rem;
padding: 1rem 0rem;
}
.teamDrops h4, #rosterDrag h4 {
margin-bottom: 1.5rem;
padding-left: 1rem;
}
.draggable {
margin: 0 5px 5px 5px;
padding: 5px;
font-size: 1.2rem;
width: 20rem;
display: inline-block;
}
#reminderTeams {
font-weight: bold;
}
#printbtn {
margin: 2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnPoint Team Generator</title>
<meta name="description" content="OnPoint Team Generator">
<meta name="author" content="MeganRoberts">
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="scripts/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles/main.css" type="text/css">
</head>
<body>
<div class="card printMe" id="top">
<h3 id="title" class="card-header" style="text-align: center;"><img src="https://lh6.googleusercontent.com/N8Syzsw2aCV_qrh4pKOFgdamHSgD6gDQvGeKayDJBVfHBK2TMeQ3PnlpJ5BHD5ZVXk7YE4toSpav1co=w1920-h950-rw" alt="OnPoint Arrows" id="opArrows"> Team Generator</h3>
<div id="stepOne" class="card-block hideMe">
<h4 class="card-title"><span>Step 1:</span> Number of Teams</h4>
<p class="card-text lightText">How many students do you have in your class?</p>
<form id="teamForm">
<div class="form-group">
<input type="text" class="form-control" id="numberOfStudents" aria-describedby="numberStudents" placeholder="Enter Number of Students" data-toggle="tooltip" data-placement="top" title="Please enter a number larger than 7.">
</div>
<button type="submit" class="btn btn-primary opbtn" id="submitTeams" disabled>Submit</button>
</form>
</div>
</div>
<div class="card hideMe">
<div class="card-block" id="studentNumberResponse">
</div>
</div>
<div id="secondsStep" class="card hideMe">
</div>
<div id="listResponse" class="card hideMe listResponse">
<div class="card-block" id="studentListResponse">
</div>
</div>
<footer>
<div>
<button type="submit" id="printbtn" class="btn btn-primary btn-lg clearfix opbtn" onclick="pdfPrint()">Print</button>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>

Whack a mole game with jQuery

I am working on a whack-a-mole game for a school assignment and I can't get it to work.
The full code can be found on jsfiddle (https://jsfiddle.net/Lc30u5h7/5/) to make this question shorter.
Whenever I load the code my "moles" (black square divs) disappear. By turning parts of my code in to comments I nailed down the error to this part of the code:
function showMole(tile) {
if (gameRunning) {
$(this).css({"background-color": "green"});
$(tile).data('mole', true);
randomInt(400, 1200) {hideMole(this)};
};
};
function hideMole(tile) {
$(tile).css({"background-color": "black"});
$(tile).data('mole', false);
randomInt(4000,48000) {showMole(this)};
};
More specifically the error is located witht the function randomInt() which uses the following code:
function randomInt(min, max){
return Math.ceil(Math.random() * (max - min) ) + min;
};
The functions are supposed to represent the different states of the moles. After a random interval a mole will switch from hideMole() to showMole() and it will turn green and reward a point if clicked (which is handled by another piece of code).
I appreciate any help I can get.
I have tried to get you started with some example code. This code uses a handful of times to help manage the game.
var game = function() {
var gameBoard_Selector = "#gameBoard";
var tile_Selector = ".tile";
var mole_ClassName = "mole";
var $gameBoard = $(gameBoard_Selector);
var $gameTiles = $gameBoard.find(tile_Selector);
var gameTime = 20 * 1000;
var turnTime = 1000;
var moleInterval;
var moleLifeMin = 1000;
var moleLifeMax = 3 * 1000;
var gameScore = 0;
var getRandomIntInclusive = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// ------------------------
// Add a click handler to the board
// This could be added and removed at start and end as an alternative.
// or added to each individual tile if you liked that strategy.
// ------------------------
$gameBoard.on("click", ".tile", function() {
var $this = $(this);
// -------------------------
// if this is not a mole do nothing...
// -------------------------
if (!$this.hasClass(mole_ClassName)) { return; }
// -------------------------
// -------------------------
// "hide" this mole and increment the score
// -------------------------
$this.removeClass(mole_ClassName);
gameScore += 1;
// -------------------------
});
// ------------------------
var startGame = function() {
gameScore = 0;
// -------------------------
// Every turnTime, spawn a new mole.
// Record moleInterval so we can cancel it when the game ends.
// -------------------------
moleInterval = setInterval(spawnMole, turnTime);
// -------------------------
// -------------------------
// The game ends in gameTime
// -------------------------
setTimeout(endGame, gameTime);
// -------------------------
}
var endGame = function() {
// -------------------------
// Stop spawning new moles
// -------------------------
clearInterval(moleInterval);
// -------------------------
// -------------------------
// "hide" any existing moles.
// -------------------------
$gameTiles.removeClass(mole_ClassName);
// -------------------------
alert("Game Over! Score: " + gameScore);
}
var spawnMole = function(timeToLive) {
// -------------------------
// Select a random tile to set as a mole.
// You might adjust to only spawn moles where there are none already.
// -------------------------
var $targetTile = $($gameTiles[getRandomIntInclusive(0, $gameTiles.length - 1)]);
// -------------------------
// -------------------------
// Moles shall live for a random amount of time
// -------------------------
var timeToLive = getRandomIntInclusive(moleLifeMin , moleLifeMax);
// -------------------------
// -------------------------
// "show" the mole
// -------------------------
$targetTile.addClass(mole_ClassName);
// -------------------------
// -------------------------
// after timeToLive, automatically "hide" the mole
// -------------------------
setTimeout(function() { $targetTile.removeClass(mole_ClassName); }, timeToLive);
// -------------------------
}
return {
startGame
};
}();
game.startGame();
#gameBoard {
margin: auto;
margin-top: 75px;
width: 250px;
height: 250px;
}
#gameBoard .tile {
background-color: black;
height: 20%;
width: 20%;
margin: 2px;
display: inline-block;
}
#gameBoard .tile.mole {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gameBoard">
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
</div>
I created my own version of this game to help you out.
Breakdown
Start by creating variables to store the user's score, level and how many lives they have. Also create a boolean variable for whether or not the game is in progress. This prevents accidental re-clicks of the start game button.
We will be incrementing the score quite a bit, so it is best to create a re-usable function for that. In my example, this is the displayScore() function. In my game, as you gain points, you will level up, so the view needs to be updated to relect that. That's where the levelUp() function comes in handy.
In the game board there are 16 cells, arranged in a 4 x 4 matrix. We can query the collection of all the cells with document.querySelectorAll(".cell"). To make the game fun, it's better not to know which cell will pop-up. That's why a cell will randomly light up in the randomCell() function.
Throughout the game, there are multiple times when the script needs to check if the player has lost. Because of that, I created a reusable gameOver() function that counts the player's lives. If the player has no lives remaining, the interval will be cleared, the playing status will be reset to not playing and the variables will be reset.
Try it out here.
var score = 0;
var level = 1;
var lives = 5;
var playing = false;
var start = document.getElementById("start");
var scoreDisplay = document.getElementById("score-display");
var cells = document.querySelectorAll(".cell");
function displayScore() {
levelUp();
scoreDisplay.innerHTML = "Score: " + score + "<span id='level-display'> Level: " + level + "</span><span id='lifes-display'> Lives: " + lives + "</span>";
}
function levelUp() {
level = Math.max(Math.floor(score / 10), 1);
}
function randomCell() {
return Math.floor(Math.random() * 16);
}
function gameOver() {
if (lives === 0) {
clearInterval(getCells);
score = 0;
level = 1;
lives = 5;
playing = false;
}
}
function highlightCell() {
var target = randomCell();
var prevScore = score;
cells[target].style.background = "green";
setTimeout(function() {
cells[target].style.background = "red";
if (score === prevScore) {
lives--;
displayScore();
gameOver();
}
}, 1000)
}
start.addEventListener("click", function() {
if (!playing) {
playing = true;
displayScore();
getCells = setInterval(function() {
highlightCell();
}, 1500);
}
});
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
if (playing) {
var cell = this;
if (this.style.background === "green") {
score++;
}
else {
lives--;
gameOver();
}
displayScore();
}
})
}
#game-board {
height: 330px;
width: 330px;
margin: 0 auto;
border: 1px solid black;
}
.cell {
display: inline-block;
width: 21%;
margin: 4px;
height: 21%;
border: 1px solid black;
background: red;
}
#game-info {
height: 40px;
width: 330px;
margin: 0 auto;
background: lightblue;
}
#level-display, #lifes-display {
margin-left: 30px;
}
#start {
margin: 10px 37%;
}
<div id="game-info">
<p id="score-display"></p>
</div>
<div id="game-board">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<button id="start">Start Game</button>

Using one function for two images

Consider the following markup
<div class="like-buttons">
<img src="up.png" onclick="onClick()" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick()" />
</div>
And the following JavaScript function
<script type="text/javascript">
var clicks = 0;
function onClick() {
if (clicks < 10) {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
} else {
document.getElementById("clicks").innerHTML = clicks;
}
};
</script>
Now what I'm trying to achieve is that when Up image is clicked the count goes up by 1 to a max of 10 and when down is clicked the count to go down by 1 and shouldn't go below 0. Currently the count goes up but I was wondering is there a way which I can add an event for each image in the same function or would I have to write two separate functions one for each image?
Thanks in advance for your help
call onClick() function with param, e.g. onClick(1) (for up button) and onClick(-1) for down button.
function onClick(value) {
var clicks = parseInt(document.getElementById("clicks").innerHTML);
clicks += value;
if (clicks > 10)
clicks = 10;
if (clicks < 0)
clicks = 0;
document.getElementById("clicks").innerHTML = clicks;
}
<div class="like-buttons">
<img src="up.png" onclick="onClick(plus)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(min)" />
</div>
<script type="text/javascript">
var clicks = parseInt(document.getElementById("clicks").innerHTML);
function onClick(type){
if (type=='plus' && clicks < 10) {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
} else {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
};
var clicks = 0;
function onClick(element) {
var imge = element.src;
if (clicks < 10 && imge.indexOf('up.png') != -1) {
clicks++;
} else if(clicks >0 && imge.indexOf('down.png') != -1) {
clicks--;
}
document.getElementById("clicks").innerHTML = clicks;
};
<div class="like-buttons">
<img src="up.png" onclick="onClick(this)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(this)" />
</div>
adding logic to #bhushans ans to complete the requirement when Up image is clicked the count goes up by 1 to a max of 10 and when down is clicked the count to go down by 1 and shouldn't go below 0.
fiddle
<div class="like-buttons">
<img src="up.png" onclick="onClick(true)" /> <span id="clicks">0</span>
<img src="down.png" onclick="onClick(false)" />
</div>
and js should be
var clicks = 0;
function onClick(flag) {
if (flag) {
if (clicks < 10) {
clicks += 1;
} }else{
if (clicks > 0) {
clicks -= 1;
}
}
document.getElementById("clicks").innerHTML = clicks;
}
You can use the same function as the event handler for both images. Just check the id of the event object to check whether to add or subtract.
Example Snippet:
var result = 0,
img1 = document.getElementById('i1'),
img2 = document.getElementById('i2'),
span = document.getElementById('clicks');
img1.addEventListener('click', calc);
img2.addEventListener('click', calc);
function calc(e) {
var img = e.target;
result = img.id == 'i1' ? (result+1) : (result-1);
result = result < 0 ? 0 : result > 10 ? 10 : result;
span.textContent = result;
}
img { cursor: pointer; margin: 5px; vertical-align: middle; }
<div class="like-buttons">
<img id='i1' src="//placehold.it/32x32?text=Up" title="Up" />
<span id="clicks">0</span>
<img id='i2' src="//placehold.it/32x32/?text=Dn" title="Down" />
</div>
You can try this : As Johan commented, pass flag. Flag could be true / false or up /down or anything you want which will identify that which button clicked (up or down).
See below code
var clicks = 0;
function onClick(flag) {
if(flag && clicks < 10)
clicks += 1;
else if(!flag && clicks > 0)
clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
};
<div class="like-buttons">
<img src="up.png" onclick="onClick(true)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(false)" />
</div>
Have a look at this snippet if can be a better solution, in order to have multiple images and same result. I've also added a 0 control for -1
$(document).ready(function(){
$('.up').click(function() {
var clicks = parseInt($(this).parent().find('.clicks').html());
clicks = clicks +1
if(clicks == 10) {
$(this).hide();
}
$(this).parent().find('.clicks').html(clicks);
});
$('.down').click(function() {
var clicks = parseInt($(this).parent().find('.clicks').html());
if(clicks > 0) {
clicks = clicks - 1
}
if(clicks < 10) {
$(this).parent().find('.up').show()
}
$(this).parent().find('.clicks').html(clicks);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="like-buttons">
<button type="button" class="up">+1</button>
<span class="clicks">0</span>
<button type="button" class="down">-1</button>
</div>
<div class="like-buttons2">
<button type="button" class="up">+1</button>
<span class="clicks">0</span>
<button type="button" class="down">-1</button>
</div>

Keep element in the bottom of dynamically changing panel

I'm using bootstrap and i have text fields which will make panel larger as they're added dynamically. Now these text fields are inside of a panel element and textfield size is col-lg-9 and there's more room in the col-lg-3 right next to it.
I would like to place a button in that col-lg-3 div, which would stay always in the bottom of the panel - so if the panel height increases due to new text field the button stays still in the bottom. I've tried absolute and relative positioning but nothing has helped + some of the methods pointed out break the scalability (which i really need to keep).
I'm adding my code:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title panel-header-text">Sisesta nimed, mis pannakse tabelisse</h3>
</div>
<div class="panel-body">
<div class="col-lg-9" id="inputcontainer">
<h4>Sisestamisel tekib uus väli (TAB-iga saab vahetada rida). Tühjasid välju ei arvestata!</h4>
<div class="input-group input-group-lg pdgtop">
<span class="input-group-addon" id="basic-addon1">1.</span>
<input type="text" id="one" class="form-control text-controller" placeholder="Sisesta nimi siia">
</div>
</div>
<div class="col-lg-3 konteiner">
<button type="button" class="btn btn-success buttonel">Valmista tabel</button>
</div>
</div>
The javascript:
/*
#FN01: This function handles the creation of new text fields according to the change in the textfield.
*/
var createNew = true;
var counter = 2;
function getNewInsertion() {
var container = document.getElementById("inputcontainer");
var inputs = document.getElementsByClassName("text-controller");
var lastField = inputs[inputs.length-1];
if (document.activeElement.value.length == 0 && createNew == false){ //if new element is chosen createNew will be set true
createNew = true;
}
else if (createNew == true && lastField.value.localeCompare("") != 0 ){
createNew = false;
//Creates Input Field
var input = document.createElement("input");
input.type = "text";
input.className = "form-control text-controller";
input.placeholder = "Sisesta siia nimi";
//Creates Span to hold the count
var span = document.createElement("span");
span.textContent = counter;
span.className = "input-group-addon";
//Creates input group to put span & input field together
var inputgroup = document.createElement("div");
inputgroup.className = "input-group input-group-lg";
inputgroup.appendChild(span);
inputgroup.appendChild(input);
container.appendChild(inputgroup);
counter += 1;
}
return createNew;
}
/*
#FN02: This is the function to delete the last field (empty) in case the one before last is empty.
*/
function canWeDeleteField(){
var inputs = document.getElementsByClassName("input-group");
var lastInput = inputs[inputs.length-1];
var lastArr = lastInput.childNodes
if (inputs.length < 2){
var last = lastArr[3];
}
else{
var last = lastArr[1];
}
console.log(lastArr);
if (inputs.length >= 2){
var last_prev_Input = inputs[inputs.length-2];
var last_prev_Arr = last_prev_Input.childNodes
if (inputs.length == 2){
var last_prev = last_prev_Arr[3];
}
else{
var last_prev = last_prev_Arr[1];
}
if (last.value.localeCompare("") == 0 && last_prev.value.localeCompare("") == 0){
lastInput.parentNode.removeChild(lastInput);
counter = counter - 1;
}
}
}
/*
#FN03: The call-out function which is triggered when key is pressed while focus is on the textfield.
*/
$(function() {
$("#inputcontainer").bind("paste cut keydown",function(e) {
getNewInsertion();
canWeDeleteField();
})
});
AND THE CSS:
.konteiner {
position: relative;
}
.buttonel {
width: 95%;
padding-right: 1%;
position: absolute;
}
You can check the solution to your problem in the following link Bootstrap equal-height columns experiment.
Basically you have to wrap your columns in a div element containing the classes "row" and "row-eq-height".
Here's a snippet of the result (using your code):
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<style type="text/css">
.row-eq-height {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.buttonel {
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title panel-header-text">Sisesta nimed, mis pannakse tabelisse</h3>
</div>
<div class="panel-body">
<div class="row row-eq-height">
<div class="col-lg-9 col-md-9" id="inputcontainer">
<h4>Sisestamisel tekib uus väli (TAB-iga saab vahetada rida). Tühjasid välju ei arvestata!</h4>
<div class="input-group input-group-lg pdgtop">
<span class="input-group-addon" id="basic-addon1">1.</span>
<input type="text" id="one" class="form-control text-controller" placeholder="Sisesta nimi siia">
</div>
</div>
<div class="col-lg-3 col-md-3">
<button type="button" class="btn btn-success buttonel">Valmista tabel</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var createNew = true;
var counter = 2;
function getNewInsertion() {
var container = document.getElementById("inputcontainer");
var inputs = document.getElementsByClassName("text-controller");
var lastField = inputs[inputs.length - 1];
if (document.activeElement.value.length == 0 && createNew == false) { //if new element is chosen createNew will be set true
createNew = true;
} else if (createNew == true && lastField.value.localeCompare("") != 0) {
createNew = false;
//Creates Input Field
var input = document.createElement("input");
input.type = "text";
input.className = "form-control text-controller";
input.placeholder = "Sisesta siia nimi";
//Creates Span to hold the count
var span = document.createElement("span");
span.textContent = counter;
span.className = "input-group-addon";
//Creates input group to put span & input field together
var inputgroup = document.createElement("div");
inputgroup.className = "input-group input-group-lg";
inputgroup.appendChild(span);
inputgroup.appendChild(input);
container.appendChild(inputgroup);
counter += 1;
}
return createNew;
}
/*
#FN02: This is the function to delete the last field (empty) in case the one before last is empty.
*/
function canWeDeleteField() {
var inputs = document.getElementsByClassName("input-group");
var lastInput = inputs[inputs.length - 1];
var lastArr = lastInput.childNodes
if (inputs.length < 2) {
var last = lastArr[3];
} else {
var last = lastArr[1];
}
console.log(lastArr);
if (inputs.length >= 2) {
var last_prev_Input = inputs[inputs.length - 2];
var last_prev_Arr = last_prev_Input.childNodes
if (inputs.length == 2) {
var last_prev = last_prev_Arr[3];
} else {
var last_prev = last_prev_Arr[1];
}
if (last.value.localeCompare("") == 0 && last_prev.value.localeCompare("") == 0) {
lastInput.parentNode.removeChild(lastInput);
counter = counter - 1;
}
}
}
/*
#FN03: The call-out function which is triggered when key is pressed while focus is on the textfield.
*/
$(function() {
$("#inputcontainer").bind("paste cut keydown", function(e) {
getNewInsertion();
canWeDeleteField();
})
});
</script>
</body>
</html>
Hope it helps!

Categories