Javascript : dropping specific objects only in specific places - javascript

I have several draggable objects and several places where it is possible to drop an object. But I don't want anything to be dropped anywhere. Let's say object A should only be dropped in place 1 and object B should only be dropped in place 2.
I discovered that fiddling with "function drop(event)" was not a good idea. If Firefox couldn't drop, it tried to redirect instead and to go to a site name-of-my-object.com.
Setting .ondragover to "return false;", even under specific conditions (ie. wrong object for this place) made the place undroppable for all objects.
Using
document.addEventListener("dragover", function(event) {
event.preventDefault();
});
to get the place to accept objects again was indiscriminate : every place accepted any object.
I've been fighting this for more than a day and, try as I might, I couldn't find a functioning example anywhere online.

The function to interfere with was the "function allowDrop(event)".
Complete functioning example :
var draggedObject = "";
var sentence = "";
var rectangle = "";
var canDrop = true;
function dragStart(event) {
event.dataTransfer.setData("text", event.target.id);
draggedObject = event.dataTransfer.getData("text");
document.getElementById("textHere").innerHTML = draggedObject + " is moving<br>";
}
function allowDrop(event) {
event.preventDefault();
if (event.dataTransfer.getData("text") == "drag1") {
sentence = "<br>" + draggedObject + " is OVER ";
}
if (event.dataTransfer.getData("text") == "drag2") {
sentence = "<br>" + draggedObject + " is OVER ";
}
rectangle = event.target.id;
if (rectangle == 'droptarget2') {
document.getElementById("textHere").innerHTML = sentence + "droptarget2";
} else {
document.getElementById("textHere").innerHTML = sentence + "droptarget1";
}
if ((rectangle == 'droptarget2') && (draggedObject == 'drag1')) canDrop = false;
if ((rectangle == 'droptarget1') && (draggedObject == 'drag2')) canDrop = false;
if ((rectangle == 'droptarget1') && (draggedObject == 'drag1')) canDrop = true;
if ((rectangle == 'droptarget2') && (draggedObject == 'drag2')) canDrop = true;
}
function drop(event) {
event.preventDefault();
if (canDrop == false) return;
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
document.getElementById("demo").innerHTML = draggedObject + " was dropped.";
}
.droptarget1 {
float: left;
width: 200px;
height: 35px;
margin: 15px;
margin-top: 15px;
padding: 10px;
border: 1px solid #aaaaaa;
background: lightgreen;
}
.droptarget2 {
float: left;
width: 200px;
height: 35px;
margin: 15px;
margin-top: 15px;
padding: 10px;
border: 1px solid #aaaaaa;
background: pink;
}
.drag1 {
color: green;
}
.drag2 {
color: red;
}
<table>
<tr>
<td colspan="2">
<h3>
Drag and drop possibilities : </h3>
<p>The green "Drag1" text can only be dropped into the green rectangle. The red "Drag2" text can only be dropped into the pink rectangle.
</p>
</td>
</tr>
<tr>
<td>
<div ondragstart="dragStart(event)" draggable="true" id="drag1" name="drag1" class="drag1">Drag1</div>
</td>
<td>
<div ondragstart="dragStart(event)" draggable="true" id="drag2" name="drag2" class="drag2">Drag2</div>
</td>
</tr>
<tr>
<td>
<div id="droptarget1" class="droptarget1" name="droptarget1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</td>
<td>
<div id="droptarget2" class="droptarget2" name="droptarget2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</td>
</tr>
<tr>
<td>
<div id="textHere"></div>
</td>
</tr>
</table>
<p id="demo"></p>

Related

Cell change background colour with clicked

I have a table and I have one 1 cell that I can't fix. What I want is to have a background colour blue and when I click the
<p> 2 click me </p>
I want to make this background cell green. I take only the code for this specific cell, what I have done and it doesn't work as I want..
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
var x = document.getElementById('colour');
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
#click{
background-color: blue;
padding: 1rem;
width : 50%;
height: 50px;
margin: auto;
}
<tr>
<td id="click">
<div id="colour" onclick="myFunction()">
<p>2 click me<p>
</div>
</td>
</tr>
is this what you want? I think you just need to assign a variable to the element colour and then use it to make your changes
function myFunction() {
const x = document.getElementById("colour");
const y = document.getElementById("click");
x.innerHTML = "YOU CLICKED ME!";
if (y.style.backgroundColor === 'green') {
y.style.backgroundColor = 'blue';
} else {
y.style.backgroundColor = 'green';
}
}
#click {
background-color: blue;
padding: 1rem;
width: 50%;
height: 50px;
margin: auto;
}
<table>
<tr>
<td id = "click">
<div id="colour" onclick="myFunction()">
<p>2 click me</p>
</div>
</td>
</tr>
</table>
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
var x = document.getElementById('colour');
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
**</script>**
You forgot to close with the script tag I think, right?
Because for me closing with the tag it works
#click{
background-color:blue;
padding:1rem;
width : 50%;
height:50px;
margin:auto;
}
<body>
<tr>
<td id="click" > <div id="colour" onclick="myFunction()"><p>2 click me<p></div></td>
</tr>
</body>
<script type="text/javascript">
var x = document.getElementById('colour');
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
x.addEventListener('click', function()
{
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
});
</script>
With this it should work!

Support resizing two side by side iframes in JavaScript

I have a web page where I need to show two iFrames side by side, and allow a user to resize them horizontally (so they can easily see the complete contents of either side).
My code looks like this:
<div style="padding:30px">
<table style="width:100%;border:0px;border-collapse:collapse;">
<tr>
<td class="cLeft cSide">
<iframe class="cFrame" src="{MyLeftPage}">
</iframe>
</td>
<td class="cRight cSide">
<iframe class="cFrame" src="{MyRightPage}">
</iframe>
</td>
</tr>
</table>
</div>
Finally managed it: jsFiddle
The problem with using the standard approaches as mentioned here (Thanks user!) is that when you have iFrames and you move the mouse over them, the $(document).mousemove() stops firing.
The trick is to have a column in the middle, and have a div that shows up when you click the column. Since the div is in the parent page, the mousemove event keeps firing, allowing you to easily resize it.
Here's what the final HTML looks like:
<div style="user-select:none;padding:30px">
<table style="width:100%;border:0px;border-collapse:collapse;">
<tr>
<td class="cLeft cSide">
<iframe class="cFrame" src="{MyLeftPage}">
</iframe>
</td>
<td class="resize-bar">
<div class="resize-panel"></div>
</td>
<td class="cRight cSide">
<iframe class="cFrame" src="{MyRightPage}">
</iframe>
</td>
</tr>
</table>
</div>
This is the CSS
.resize-bar {
width: 5px;
cursor: col-resize;
position:relative;
background-color: #AAA;
margin:20px;
}
.resize-panel {
height: 100%;
background-color: #DDDDDD00;
display: inline-block;
position: absolute;
top:0px;
left:-2px;
right:-2px;
cursor: col-resize;
}
.resize-panel.rx {
left:-400px;
right:-400px;
}
.cSide {
min-width:200px;
}
.cFrame {
width: 100%;
border: 1px solid #DDD;
height: calc(100vh - 170px);
overflow-x:scroll;
}
And this is the JavaScript:
$(function() {
var pressed = false;
$("table td").mousedown(function(e) {
pressed = true;
$(".resize-panel").addClass("rx");
e.stopPropagation();
});
$(".resize-panel").mousedown(function(e) {
pressed = false;
});
$(document).mousemove(function(e) {
if (e.which == 1 && pressed) {
var ww = $(window).width();
var cPos = e.pageX;
if (cPos < 0.20 * ww) cPos = 0.2 * ww;
if (cPos > 0.80 * ww) cPos = 0.8 * ww; {
$(".cLeft").width(cPos);
}
}
});
$(document).mouseup(function() {
if (pressed) {
$(".resize-panel").removeClass("rx");
pressed = false;
}
});
});

Modal pops up after Ajax call completes instead of before or during

I am trying to get a modal popup to show "Please Wait" while an Ajax call is being made. The pop up occurs only after the call completes.
When I click my web link, everything is working, except the modal popup that is supposed to say "Please Wait" flashes for a split second AFTER the delay that the user is supposed to be asked to wait thru. That is, the modal pops up AFTER the Ajax call is completed instead of before.
When the page loads, it calls AjaxInitialUpdate. This works fine.
The issue is when you click the button that calls AjaxChangePassword.
The function is supposed to pull up a modal, then contact the web server, before finally removing the model and calling the AjaxInitialUpdate function to refresh the whole screen.
The issue is that the AjaxChangePassword modal doesn't pop up until the web query completes (by which time, there is no point in telling the user -- Please Wait).
Now, I am totally self-taught here, so I may be calling things by the wrong name or terms. I welcome any ideas to make it run better, but please be detailed, I'm still very novice in Java.
Also, the last time I did any kind of HTML programming was before Style sheets were the way to go, so I'm kind of having to learn them as well (and refresh on all the rest, so please explain any answer in detail).
Lastly, the server side of this is written in Powershell and is single threaded so I am trying to put as much in the HTML file as possible instead of calling secondary files, like style sheets and images.
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
/* Believe these are not needed.
Imported from web site that I copied the code from.
padding: 8px 8px;
outline: none;
border: none;
border-radius: 115px;
box-shadow: 0 3px #999; */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 70%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
#IndividualSystem td, #IndividualSystem th {
text-align: left;
padding: 8px;
color: black
border: 1px solid black;
}
#IndividualSystem tr {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #eeeeee;
}
.tab { margin-left: 40px; }
.button {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
.button2 {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #000080;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button2:hover {background-color: #df330e}
.button2:active {
background-color: #FD2E02;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
</style>
<Title>Cyber Track</title>
</head>
<body>
<table>
<tr>
<td>blah</td>
<td><h1>Systems and Passwords</H1>
<h3>Information within this page is considered confidential.</h3>
</td></tr>
</table>
<hr>
<input type="hidden" id="Leftlink" name="Leftlink" value="0">
<input type="hidden" id="Rightlink" name="Rightlink" value="0">
<input type="hidden" id="serverID" name="serverID" value="server8\admin-server8">
<input type="hidden" id="count" name="count" value="10"> <!--- Number of servers per page on server list //-->
<!-- The Modals #1 -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h4><label id="ModalTextLine1">Loading content from server</label></h4>
</div>
</div>
<!-- The Modals #2 -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close2">×</span>
How long do you need the password?
<form action='#'>
<select name="days">
<option value='1' >1 day or less</option>
<option value='7'>between 1 and 2 days</option>
<option value='7'>between 2 and 7 days</option>
<option value='30'>between 7 and 30 days</option>
<option value='365' selected>for up to a year.</option>
</select>
<br>
<input type="submit" value="Process Request">
</form>
</div>
</div>
<script>
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close2")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it (or actually, just hide it)
window.onclick = function(event) {
if (modal2.style.display != "none")
{
if (event.target == modal2) {
modal2.style.display = "none";
}
}
}
</script>
<!-- End Loaded from function -->
<table id="IndividualSystem"> <!-- IndividualSystem - to define needed style sheet //-->
<tr>
<td style="width: 215px;">Server</td>
<td style="width: 259px;"><label ID="DynServerName">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">User ID</td>
<td style="width: 259px;"><label ID="DynAdminID">Loading</label></td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td style="width: 215px;">Checked out status:</td>
<td style="width: 259px;"><label ID="DynLastCheckedout">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;" valign='top' >Last checked out by:</td>
<td style="width: 259px;" valign='top' ><label ID="DynLastCheckedBy">Loading...</label>
<button class="button" onclick="javascript:AjaxCheckOutPassword()" id="PassStatus">Loading</button> <!-- AjaxCheckOutPassword -->
</td>
</tr>
<tr>
<td valign='top' style="width: 215px;">Expected Check In Date:</td>
<td valign='top' style="width: 259px;"><label ID="DynExpectedBack">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">Date of last password change:</td>
<td style="width: 259px;"><label id="DynLastReset">Loading</label> <button class="button2" onclick="AjaxChangePassword()">Force Change Now!</button>
</td>
</tr>
<tr>
<th colspan="2">Notify:<br>
<table border="1" padding = "0" width=100%>
<tr>
<td width=200>On Use:</td><td><label id="DynEmailCheckOut">Loading</label></td>
</tr>
<tr>
<td width=200>On Checkin:</td><td><label id="DynEmailCheckIn">Loading</label></td>
</tr>
</table>
</th>
</tr>
<tr><td colspan="2">
<label ID="DynAccountPurpose"></label>
</td></tr>
</tbody>
</table>
<!-- Page Footer (if any) //-->
<!-- Page links left/up/right //-->
<table>
<tr><td width = 50>
<label id="Show-Left">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(-1)" text='Prior Server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9+Wwp/wDrVzHxS+Kmk/B3wfda3rdz9lsbPZ5kvlvJ951QfKis3V1HA7074ofE/SPhD4RvNc1m5+x6fZ7PNl8t5Nu50ReFBJyzgcDv6Dj853k8Zf8ABW/4sgY/sv4d6T0X9zPjzIfX9xNzPae/X+6Ob9naPtJ7GXM5Plgfod8H/jHoXxw8FW3iDw7c/btPvt4WTy5I87JHj6SKp+8jfwj8etddvHp+hrm/hb8L9H+EnhO30PQ7f7JZWe7am93xvdnPLsx6sT1P8q6QcDjbjt8prGPdm0rHjv7Yf7JOj/tW/DuTS9Q/0e6jx5M+Hfyv3sTt8qyIDkRAc9O1fH/7GP7T+t/sN+P4/hD8TB5OnQ5+yXX7t/s+Y5rt/kt45C2WmiHMnGeOMgfpEWJb73H0614v+2N+x1oP7WfgiTT9SBt7+HBtrr94/lZkhZvkWRAciEDn8OldCqc0fZzMJU+WXNA9hsb9NQtVlhfdG2drYIzg4PWp8r/drzb9lv4I3fwH+EWn+HNQ1X+2JrPzM3H2YW+7dNLJ90MwGBIB949Pwr0kx8/d/SsIO2jOjRn/2Q==' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
<td>
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(0)" text='Next server'>Return to main list</a>
</td>
<td width = "50">
<label id="Show-Right">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(1)" text='Next server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD97dc1U6Zp000cfnPHt+Tdt3ZIHX8a+Z/2Sv8AgpDpfx98c3/hjWNP/wCEf16Dy/Kt/Pe78zMcsp+ZYVQYSMHk/wAXqK+oihPT8DXx7/wUM/4J8r8Wo4/GXg5fsfi7T85XPmfat/2eH/lrMsabYkf+E5z64NEHGM+WezFUTcbw3PsMgtjj6nNO8pfSvjn/AIJv/wDBRD/hoLTj4b8UDyPFFr99s7vtG43Eg4jhWNdsca9+frmvsPa3/PX/AMdrSdKUHZkQqxmtCPULyK1tXef5YVxuPJ7+3PWvzt/a4/a28S/tm/Ek/Cz4V/vrOX/j7u/3S+ZiKK6T5LmOMjBhlHD+57A/ofqenQ6hbPFP80BxuXkdwRyOetef/Aj9lXwh+zpHer4a077AL7y/NP2iaXds34/1kj4/1jdPWsYqLneey/E0nJqP7vcwv2Ov2OdD/ZM+H/8AZunjzr64/wCPy7zIv2jbJMyfI0jhdolI4PPU+3su5fX9KAdwyRgntmn7hWs6spvmkZwpRjsf/9k=' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
</tr></table>
<!-- End Page links left/up/right //-->
<!-- Dynamic JAVA Script Section //-->
<script>
// disable our NAV pointers till later where we may re-enable them.
document.getElementById('Show-Right').style.display = 'none';
document.getElementById('Show-Left').style.display = 'none';
//
// This is the specific function that I need help with.
// Why does this modal pop up only after the actual query is done?
//
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
document.getElementById('myModal1').style.display = "none";
};
// Navigate left and right..
function AjaxNavigate(link)
{
xx = document.getElementById('Leftlink').value
xx = document.getElementById('Rightlink').value
if (link == 0)
{
// Back to the main page. Get the values that make who we are -- servername and count.
var count = document.getElementById('count').value;
var CurrentSystem = document.getElementById('serverID').value;
var x = '/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime());
location.replace('/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime()));
}
else
{
if (link == 1)
{
document.getElementById('serverID').value = document.getElementById('Rightlink').value
} else {
document.getElementById('serverID').value = document.getElementById('Leftlink').value
}
// we've moved left or right. Lets update.
AjaxInitialUpdate()
}
}
function AjaxCheckOutPassword() {
console.log("Checkout Code not yet written");
};
function AjaxInitialUpdate() {
var xhr = ""
var xhr = new XMLHttpRequest();
var count = document.getElementById('count').value;
var link = document.getElementById('serverID').value
document.getElementById('myModal1').style.display = "block"; // show we are updating everything..
document.getElementById('myModal2').style.display = "none"; // should already be hidden, but lets make sure..
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=refresh&server=' + link + '&count=' + count + '&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Response.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
WebFields = xhr.responseText.split("|");
document.getElementById("DynServerName").innerHTML = WebFields[0];
document.getElementById("DynAdminID").innerHTML = WebFields[1];
document.getElementById("DynLastCheckedout").innerHTML = WebFields[2];
document.getElementById("DynLastCheckedBy").innerHTML = WebFields[3];
document.getElementById("DynExpectedBack").innerHTML = WebFields[4];
document.getElementById("DynLastReset").innerHTML = WebFields[5];
document.getElementById("PassStatus").innerHTML = WebFields[6];
document.getElementById("DynEmailCheckIn").innerHTML = WebFields[7];
document.getElementById("DynEmailCheckOut").innerHTML = WebFields[8];
// if no comment, don't even dispay the table cells.
if (WebFields[9].slice(0,1) == "{" && WebFields[9].slice(-1) == "}" && WebFields[9] != "{}" )
{
var res = WebFields[9].split("{");
var res = res[1].split("}")[0];
document.getElementById("DynAccountPurpose").innerHTML = "<tr><td style='width: 474px;' colspan='2'><p><b>Account Comments:</b></p><p class='tab'>" + res + "</p></td></tr>";
}
else
{
document.getElementById("DynAccountPurpose").innerHTML = "";
console.log("No Comment");
};
// lets populate the nav buttons..
if (WebFields[10] == '\\')
{
// hide go left
document.getElementById('Show-Left').style.display = 'none';
document.getElementById("Leftlink").value = "0/0"
}
else
{
//Enable go left
document.getElementById('Show-Left').style.display = 'block';
document.getElementById('Leftlink').value = WebFields[10];
};
// lets populate the nav buttons..
if (WebFields[11] == "\\")
{
// hide go right
document.getElementById('Show-Right').style.display = 'none';
document.getElementById("Rightlink").value = "0/0";
}
else
{
// Enable go right
document.getElementById('Show-Right').style.display = 'block';
document.getElementById("Rightlink").value = WebFields[11];
};
document.getElementById('myModal1').style.display = "none";
}
if (xhr.status === 403) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Access Denied';
}
if (xhr.status === 404) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Unable to load';
};
}
else
{
document.getElementById("PassStatus").innerHTML = "Failed";
};
};
xhr.send(null);
};
// Now, load the initial value..
window.onload = AjaxInitialUpdate();
</script>
When I call AjaxChangePassword(), I expected the modal to open BEFORE the query.
As it is now, if I stop the server after the page loads, but before this function is started, the modal never pops up, then once I start the server side back up, and I see the query come in and get answers, only then does it pop up, and then only for a split second.
What am I doing wrong in the way I am calling it?
As I reviewed your code and found that in the function AjaxChangePassword firstly you opened modal and then called ajax then closed modal the problem is that basically javascript executes synchronously but if there is ajax call then it executes asynchronously, so according to that your modal opens and then call ajax untill ajax is busy in getting response before that next line will be executed that line is for modal close and this happens in the fraction of ms so you don't see anything, And you said that after ajax call modal is showing because in AjaxChangePassword the call back method is AjaxInitialUpdate and also in this method you opened modal then closed but remember in this method you closed modal in the call back method so it appears for some time and you can see so according to me just remove
document.getElementById('myModal1').style.display = "none";
this line from AjaxChangePassword method below is corrected AjaxChangePassword function
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('myModal1').style.display = "none";
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
};
and check. I may be wrong but check it.

representing a character at various array in an html table w/JQuery/JavaScript

I've run into some issue graphically representing some of my data via J Query in my Hangman game- right now I'm working on the last part of my play(space) function to take into account if there is more than one correctly guessed letter in a word & to display all instances of that letter- I've made a function to loop through the array created out of the split word, I'm getting the correct indexes of those letters, I'm just kind of stuck as to how to display these letters at these indexes in my table via J Query correctly & I'm kind of stuck... I've been console.log - ing my data & I'm getting the correct data (the letter and the indexes of that letter in my array), I now just need to figure out how to display these letters in my html table at their correct indexes corresponding to the table (I'm feeling kind of stuck & wondering if this is possible to salvage- I'm sure there must be a way to do it, I just haven't figured it out- I'm not sure if I should be creating a dictionary object to pair the correct letter w/it's indexes in the array to use .each() to loop through to graphically represent in my table or if there's a way to graphically represent it w/the data as is). I'd really appreciate any help.
Here's my code:
JS/JQuery:
var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];
var word = [];
var wrongGuesses = [];
var rightGuesses = [];
var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];
var y = 0;
var i = 1;
$(document).ready(function() {
function randomWord() {
var random = Math.floor(Math.random() * wordBank.length);
var toString = wordBank[random];
console.log(toString);
word = toString.split("");
console.log(word);
}
randomWord();
function wordSpaces() {
for (var i = 0; i < word.length; i++) {
$(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
}
}
wordSpaces();
function play(space) {
//indexOf()==inArray()
var lIndex = jQuery.inArray(space, word);
console.log(lIndex);
if (lIndex == -1) {
wrongGuesses.push(space);
var wrong = wrongGuesses.length;
console.log('wrong ' + wrong);
$('.wrongLetters tbody tr td:nth-of-type(' + wrong + ')').text(space);
// $(this).css("background-color", "#ff4500").fadeIn(300).delay(800).fadeOut(300);
$(images[i - 1]).hide();
$(images[i]).show();
i++;
$("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);
console.log(word);
} else {
console.log(word + "word");
console.log(space + "space");
function getInstances(word,space) {
var indexes = [], w;
for(w=0; w<word.length;w++ )
if (word[w] === space)
indexes.push(w);
return indexes;
}
console.log(word + "word");
console.log(space + "space");
var indexes = getInstances(word, space);
console.log(indexes);
rightGuesses.push(space);
console.log(rightGuesses);
$(".word-spaces tbody tr td:nth-of-type(" + indexes + ")").css('color', 'black');
// rightGuesses.push(space);
}
}
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val();
play(space);
$(this).val('');
endGame();
return false;
}
});
function endGame() {
if (wrongGuesses.length >= 10 || rightGuesses.length == word.length) {
$("body").css("background-color", "#ff4500");
$(".form-control").prop('disabled', true);
}
}
});
html:
<header>
<h2 style="font-family:paganini;">
Hangman
</h2>
</header>
<main style="font-family:paganini;">
<figure class="hangman">
<img src="https://i.imgur.com/gSxmkUf.gif" id="gallows" align="middle top">
<img src="https://i.imgur.com/Mb4owx9.gif" id="head" align="middle top" style="display:none;">
<img src="https://i.imgur.com/xkXISte.gif" id="body" align="middle top" style="display:none;">
<img src="https://i.imgur.com/U44ReUi.gif" id="armL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/49kkaQF.gif" id="handL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/tqtNazW.gif" id="armR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/ydnz7eX.gif" id="handR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/dlL7Kek.gif" id="legL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/3AQYFV9.gif" id="footL" align="middle top" style="display:none;">
<img src="https://i.imgur.com/j9noEN7.gif" id="legR" align="middle top" style="display:none;">
<img src="https://i.imgur.com/kJofX7M.gif" id="footR" align="middle top" style="display:none;">
</figure>
<table class="word-spaces">
<caption>Your Word is: </caption>
<tbody>
<tr>
</tr>
</tbody>
</table>
<br/>
<fieldset class="guessIn">
<legend>
Guess a Letter
</legend>
<label for="form">Type a Letter then Click <b>Enter</b></label>
<input type="text" id="form" class="form-control" placeholder="guess">
</fieldset>
<table class="wrongLetters">
<caption>Letters Guessed Wrong:</caption>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</main>
<footer>
</footer>
Note that when you make a selection you get the following error in the console:
Uncaught Error: Syntax error, unrecognized expression: :nth-of-type
That's because of this line:
$(".word-spaces tbody tr td:nth-of-type(" + indexes + ")").css('color', 'black');
Since a correct guess can set multiple indexes, you'll need to use a loop for the correct guesses like this:
$.each(indexes,function(e,i){
$(".word-spaces tbody tr td:nth-of-type(" + i + ")").css('color', 'black');
})
Additionally, I think this line is wrong:
$(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
You probably meant to use the value of i like this:
$(".word-spaces > tbody > tr").append('<td data-idx='+i+'>' + word[i] + '</td>')
(though you dont really need the data-idx attribute at all since it will always be the same as the child index within the tr tag and you're using that to get the cells anyway)
Here is a working jsFiddle
I figured this out on my own (I sort of panicked) like this: first I created a .forEach loop to loop through the word, then the issue was the difference btwn array concatenation in JS & html/css... I creates the index variable, and added one & also an additional plus sign outside of the parenthesis... So, this solves the problem:
indexes.forEach(function(index) {
$(".word-spaces tbody tr td:nth-of-type(" + (index + 1) + ")").css('color', 'black');
});
Ok, it does everything now. In addition to the first version's features, version 2 has the following:
If a letter is guessed wrong more than once, an alert will inform the player of doing so and ignore it.
If a correct guess has more than one letter, all letters will be exposed.
Improved endGame() function with a message, but it needs one more fix, I'll leave that one to you ;-)
Plunker
<!doctype>
<html>
<head>
<meta charset="utf-8">
<title>35387864</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<style>
html {
font: 400 16px/1.428 'Verdana';
}
main {
padding: 20px;
}
footer,
header {
padding: 5px 20px;
}
footer {
border-top: 2px ridge #666;
}
header {
border-bottom: 2px ridge #666;
}
.wordSpaces,
.wrongLetters {
border: 1px ridge grey;
table-layout: fixed;
border-collapse: collapse;
margin: 10px 0;
}
.wordSpaces td,
.wrongLetters td {
border: 2px inset #BBB;
width: 3ch;
height: 1.5rem;
padding: 1px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
color: white;
}
.wrongLetters td {
color: red;
}
.form-control {
width: 10ch;
text-align: center;
}
ul {
font-size: 1rem;
list-style: none;
padding-left: 0;
}
.msg {
font-size: 0;
color: #000;
text-align: center;
}
</style>
</head>
<body>
<header>
<h2> Hangman </h2>
</header>
<main>
<figure class="hangman"> <img src="https://i.imgur.com/gSxmkUf.gif" id="gallows" align="middle top"> <img src="https://i.imgur.com/Mb4owx9.gif" id="head" align="middle top" style="display:none;"> <img src="https://i.imgur.com/xkXISte.gif" id="body" align="middle top" style="display:none;"> <img src="https://i.imgur.com/U44ReUi.gif" id="armL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/49kkaQF.gif" id="handL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/tqtNazW.gif" id="armR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/ydnz7eX.gif" id="handR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/dlL7Kek.gif" id="legL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/3AQYFV9.gif" id="footL" align="middle top" style="display:none;"> <img src="https://i.imgur.com/j9noEN7.gif" id="legR" align="middle top" style="display:none;"> <img src="https://i.imgur.com/kJofX7M.gif" id="footR" align="middle top" style="display:none;"> </figure>
<table class="wordSpaces">
<caption>
Your Word is:
</caption>
<tbody>
<tr>
</tr>
</tbody>
</table>
<br/>
<h1 class="msg">
</h1>
<fieldset class="guessIn">
<legend> Guess a Letter </legend>
<label for="form">Type a Letter then Click <kbd>Enter</kbd></label>
<input type="text" id="form" class="form-control" placeholder="guess" maxlength="1" required/>
</fieldset>
<table class="wrongLetters">
<caption>
Letters Guessed Wrong:
</caption>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</main>
<footer>
<ul>
<li>Hangman Gameplay in JavaScript</li>
<li>jsFiddle</li>
</ul>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script>
var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];
/*var wordBank = ["xxxbnvkllyyybns"];*/
var word = [];
var wrongGuesses = [];
var rightGuesses = [];
var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];
var img = 1;
$(document).ready(function() {
function randomWord() {
var random = Math.floor(Math.random() * wordBank.length);
var toString = wordBank[random];
console.log(toString);
word = toString.split("");
console.log(word);
}
randomWord();
function wordSpaces() {
for (var i = 0; i < word.length; i++) {
$(".wordSpaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
}
}
wordSpaces();
function play(letter) {
var wIdx = jQuery.inArray(letter, word);
var wrong = wrongGuesses.length;
if (wIdx === -1) {
if (wrong === 0) {
wrongGuesses.push(letter);
$('.wrongLetters tbody tr td:first-of-type').text(letter);
hangman();
} else {
for (var j = 0; j < wrong; j++) {
if (wrongGuesses[j] === letter) {
alert('The "' + letter + '" has already beem played.\nPlease try again.');
return true;
}
console.log('wrong' + wrong);
}
wrongGuesses.push(letter);
$('.wrongLetters tbody tr td:nth-of-type(' + (wrong + 1) + ')').text(letter);
hangman();
}
} else {
for (var w = 0; w < word.length; w++) {
if (word[w] === letter) {
W = w + 1;
$(".wordSpaces tbody tr td:nth-of-type(" + W + ")").css("color", "black");
rightGuesses.push(letter);
}
}
}
}
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var letter = $(this).val();
play(letter);
$(this).val('');
endGame();
return false;
}
});
function hangman() {
$(images[img - 1]).hide();
$(images[img]).show();
img++;
$("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);
}
function endGame() {
if (rightGuesses.length == word.length) {
$("body").css("background-color", "rgba(0, 185, 41, .3)");
$(".msg").text(word + " is correct!\nYou win!").css("font-size", "24px");
$(".form-control").prop('disabled', true);
} else if (wrongGuesses.length === 10) {
$("body").css("background-color", "rgba(227, 0, 0, .3)");
$(".msg").text(word + " was the answer.\nYou lose.").css("font-size", "24px");
$(".form-control").prop('disabled', true);
} else return false;
}
});
</script>
</body>
</html>

jquery - showing box with if statement by click on button when field is completed - quiz creation

I'm desperately trying to create something very simple for you!
Here's my problem:
I'd like to create a small quiz in which when someone writes anything in a field (), and then click the button "ok" (not sure if I should use a or a ), then 3 possibilities arise (for each case a box appearing under the field input):
The answer is exact and correctly written: then the text will be "Great job!"
The answer is almost correct, meaning that the word is not correctly written (we can define if necessary "almost answers"): the text will be "Almost there..."
The answer is completely wrong, the text will be "Try again!"
Right now I have that:
<body>
<div>
<table>
<tbody>
<tr>
<td>To whom it belongs?</td>
</tr>
<tr>
<td>
<img src="#" alt="Tim's coat" width="100%"/>
</td>
</tr>
<tr>
<td class="answer-box">
<input type="text" class="field-answer" placeholder="Write it there!">
<button id="showresult" class="button-answer" value="Ok">OK</button>
</td>
</tr>
<tr>
<td>
<div class="res" id="switch">Great job!</div>
<div class="res" id="switch2">Almost there...</div>
<div class="res" id="switch3">Try again!</div>
</td>
</tr>
</tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$(document).ready(function(){
$('.field-answer').bind('keyup', function(){
if("#showresult").click(function() {
if($.inArray($(this).val().toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g, ''), artist) >= 0){
$('#switch').show('good');
}
else if($.inArray($(this).val().toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g, ''), almostartist) >= 0){
$('#switch2').addClass('soso');
if{
$('#switch3').addClass('non');
}
else {
$('#switch3').removeClass('non');
}
});
});
}
</script>
But of course this is not working...
In case, my CSS is here:
.res {
display: none;
color: white;
font-weight: bold;
text-align: center;
background-color: #490058;
height: 75px;
max-width: 100%;
line-height: 70px;
font-size: 140%;
}
.res.good {
display: block;
}
.res.soso {
display: block;
}
.res.non {
display: block;
}
.answer-box {
text-align: center;
}
.button-answer {
border: none;
background-color: #490058;
color: white;
font-size: 120%;
font-weight: bold;
padding: 8px;
left: 260px;
}
.field-answer {
text-align: center;
border: none;
border-bottom: 2px solid black;
background-color: transparent;
max-width: 230px;
height: 40px;
font-size: 20px;
text-transform: uppercase;
outline: 0;
}
Someone could help me to figure that out, please?
I'm quite sure I'm not far, but cannot solve it...
If you need more precisions on stuffs, please don't hesitate! ;)
Thanks guys!
Baptiste
A slightly different approach - no better than any other suggestion - FIDDLE.
JS
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$('.field-answer').focus(function(){
$('.res').css('display', 'none');
$(':input').val('');
});
$('#showresult').on('click', function(){
useranswer = $('.field-answer').val();
useranswer = useranswer.toLowerCase().trim().replace(/[^\w\s\-\_!##\$%\^\&*\\")\(+=._-]/g);
if( $.inArray( useranswer, artist ) === 0 )
{
$('#switch1').css('display', 'block');
}
else if ( $.inArray( useranswer, almostartist ) >= 0 )
{
$('#switch2').css('display', 'block');
}
else //if ( $.inArray( useranswer, almostartist ) < 0 )
{
$('#switch3').css('display', 'block');
}
});
your whole function is bound in to 'keyup' event.
keyup event only occurs once when key is released from pressed.
try deleting bind('keyup', function)
I've found a solution to your problems.
Check this Fiddle
In this script every time you click on the button the field text is compared with the values of the array
Depending on the value of the the corrisponding div is showed.
code
<script type="text/javascript">
$(document).ready(function(){
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$("#showresult").click(function() {
var text=$('.field-answer').val();
if(artist.indexOf(text) > -1){
$('#switch').show();
}
else if(almostartist.indexOf(text) > -1){
$('#switch2').show();
}
else{$('#switch3').show();}
});
});
</script>
if you want the message appears on keyup you have to use this code
<script type="text/javascript">
$(document).ready(function(){
var artist = ["abba"];
var almostartist = ["abaa", "aaba", "aabaa"];
$(".field-answer").on('keyup',function() {
$('.res').hide()
var text=$('.field-answer').val().toLowerCase();
if(artist.indexOf(text) > -1){
$('#switch').show();
}
else if(almostartist.indexOf(text) > -1){
$('#switch2').show();
}
else{$('#switch3').show();}
});
});
</script>
If you like one of these solutions remember to falg in green my answer ;) thanks.

Categories