Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
line 5 of my javascript is failing after first click. It 'will' open a subnav and then when I click on a second one, the first will disappear. But that all, after that, every one you click on will remain and will not go away without a screen refresh. .style.display = "none" is completely failing to clear my ma[m] value thus my subnav menu fails to disappear when another value is clicked. http://jsfiddle.net/w9ztQ/
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Bite Me</title>
<script type="text/javascript">
var ma = ["dropmenu1","dropmenu2","dropmenu3"];
function dropMenu(x){
for (var m in ma){
if(ma[m] != x){
document.getElementById(ma[m]).style.display = "none";
}
}
if(document.getElementById(x).style.display == 'block'){
fadeOut(x);
}else{
fadeIn(x);
}
}
</script>
<script type="text/javascript">
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element){
var target = document.getElementById(element);
target.style.display ="block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
//opacity
fade_in_from++;
if(fade_in_from == 10){
target.style.opacity = 1;
clearTimeout(looTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')',50);
}
function fadeOut(element){
var target = document.getElementById(element);
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0){
target.style.opacity = 0;
target.style.display = "none";
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')',50);
}
</script>
<script type="text/javascript">
var ma = ["dropmenu1","dropmenu2","dropmenu3"];
function dropMenu(x){
for (var m in ma){
if(ma[m] != x){
document.getElementById(ma[m]).style.display = "none";
}
}
if(document.getElementById(x).style.display == 'block'){
fadeOut(x);
}else{
fadeIn(x);
}
}
</script>
<style type="text/css">
body{ margin:0px; }
div#myheader{
height:100px;
background:#D2E9FF;
border-bottom:#09F 1px solid;
}
div#logo{
height:75px;
border:#09F 1px dashed;
font-size:44px;
padding:0px 12px;
}
div#headermenusystem{ margin-left:16px; }
div#headermenusystem > div{ float:left; margin:0px 20px; }
div.dropmenus {
display:none;
position:absolute;
top:100px;
width:120px;
background:#D2E9FF;
z-index:2;
padding:4px;
border:#0385CB 3px solid;
border-top:none;
-moz-border-radius:0px 0px 8px 8px;
border-radius:0px 0px 8px 8px;
}
div.dropmenus > a {
display:block;
margin:4px;
padding:7px;
font-size:14px;
text-decoration:none;
background:#E8E8E8;
border:#666 1px solid;
-moz-border-radius:3px;
border-radius:3px;
color:#000;
}
div.dropmenus > a:hover {
background:#FFF;
border:#06F 1px solid;
color: #06F;
}
div#dropmenu1{left:24px;}
div#dropmenu2{left:116px;}
div#dropmenu3{left:214px;}
div#restofpage{ padding:36px; }
</style>
</head>
<body>
<!-- START HEADER -->
<div id="myheader">
<div id="logo">Test Company</div>
<!-- START MENU SYSTEM -->
<div id="headermenusystem">
<div id="cont1">
Services
<div id="dropmenu1" class="dropmenus">
Pool Cleaning
Yard Work
Pest Removal
</div>
</div>
<div id="cont2">
Locations
<div id="dropmenu2" class="dropmenus">
Queens
Brooklyn
Bronx
</div>
</div>
<div id="cont3">
Staff
<div id="dropmenu3" class="dropmenus">
George
Allen
Frank
</div>
</div>
<div>
Contact Us
</div>
</div>
<!-- END MENU SYSTEM -->
</div>
<!-- END HEADER -->
<div id="restofpage" onmousedown="dropMenu()" style="height:500px;">
<h2>Welcome</h2>
<p>blah...</p>
</div>
</body>
</html>
I found 2 small bugs.
One is clearTimeout(looTimer); I think you mean loopTimer.
Second is that you define var ma = ["dropmenu1","dropmenu2","dropmenu3"]; 2 times in your script. Removing that I think it works.
Is this (demo) the behavior you expect?
var ma = ["dropmenu1","dropmenu2","dropmenu3"];
function dropMenu(x){
for (var m in ma){
if(ma[m] != x){
document.getElementById(ma[m]).style.display = "none";
}
}
if(document.getElementById(x).style.display == 'block'){
fadeOut(x);
}else{
fadeIn(x);
}
}
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element){
var target = document.getElementById(element);
target.style.display ="block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
//opacity
fade_in_from++;
if(fade_in_from == 10){
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')',50);
}
function fadeOut(element){
var target = document.getElementById(element);
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0){
target.style.opacity = 0;
target.style.display = "none";
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')',50);
}
//var ma = ["dropmenu1","dropmenu2","dropmenu3"];
function dropMenu(x){
for (var m in ma){
if(ma[m] != x){
document.getElementById(ma[m]).style.display = "none";
}
}
if(document.getElementById(x).style.display == 'block'){
fadeOut(x);
}else{
fadeIn(x);
}
}
Related
Ive attempted to make Tic Tac Toe as a javascript learning project and Im currently testing the first row winning state for Player 1, but for some reason every time the 3rd box is clicked regardless if the 1st and 2nd box has been clicked, it displays the winning message. Obviously thats not how tic tac toe works, as you need 3 in a row not 1 or 2.
Im using 2 arrays to test the winning state. 1 array for the boxes that have been already been clicked by the player, and 1 array that contains the winning combination for the first row. My goal was to test using an if statement to see if the boxes already clicked by the player matches the ones in the array with the winning combo.
I have tried using the .every method
for(let i=0;i<fRowBoxes.length;i++){
let fRowWin= () => X_Checked.includes((fRowBoxes[0],fRowBoxes[1],fRowBoxes[2])) ;
if(fRowBoxes.every(fRowWin) === true){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
.textContent
if((fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2]).textContent == " x "){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
and the .includes method
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){/*Only checks for fRowBoxes[2]?*/
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
Still nothing seems to work or it leads to the same result, any advice or suggestions would be highly appreciated.
let player1 = `<div class="symbol x"> x </div>`;
let player2 = `<div class="symbol o"> o </div>`;
let turn = player1;
let gridBoxes = document.querySelector('.grid').children;
let boxes = [];/*Stores all boxes in 3x3 grid*/
for(let i = 0; i < gridBoxes.length; i++){
boxes.push(gridBoxes[i]);
}
const msg = document.querySelector('div.msg ');
let fRowBoxes = [boxes[0],boxes[1],boxes[2]];/*Array with first row boxes*/
let sRowBoxes = [boxes[3],boxes[4],boxes[5]];
let tRowBoxes = [boxes[6],boxes[7],boxes[8]];
let fColBoxes = [boxes[0],boxes[3],boxes[6]];
let sColBoxes = [boxes[1],boxes[4],boxes[7]];
let tColBoxes = [boxes[2],boxes[5],boxes[8]];
let dBoxes1 =[boxes[0],boxes[4],boxes[8]];
let dBoxes2 = [boxes[2],boxes[4],boxes[6]];
let X_Checked = [];/*Stores boxes clicked by player 1*/
let O_Checked = [];
msg.display ='block';
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){/*Only checks for fRowBoxes[2]?*/
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
const tictactoe = (function(){/*START*/
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
for(let i = 0; i<boxes.length; i++){
boxes[i].addEventListener('click',() =>{
if(boxes[i].value){
boxes[i].click(false);
}
else if(boxes[i].textContent === ""){
boxes[i].innerHTML = turn;
checkPlayer();
/**------------------------------------------- */
if (turn === player1){
O_Checked.push(boxes[i]);
console.log(O_Checked);
checkScore();/*Checks for a winner*/
}
else if (turn === player2){
X_Checked.push(boxes[i]);
console.log( X_Checked);
checkScore();
}
}
});}
}());/*END*/
let checkPlayer = (function(){
if(turn === player1){
turn = player2;
msg.innerHTML = `<h1>Player 2 (O)</h1>`;
}
else if(turn === player2){
turn = player1;
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
}
});
let player1 = `<div class="symbol x"> x </div>`;
let player2 = `<div class="symbol o"> o </div>`;
let turn = player1;
let gridBoxes = document.querySelector('.grid').children;
let boxes = [];
for(let i = 0; i < gridBoxes.length; i++){
boxes.push(gridBoxes[i]);
}
const msg = document.querySelector('div.msg ');
let fRowBoxes = [boxes[0],boxes[1],boxes[2]];
let sRowBoxes = [boxes[3],boxes[4],boxes[5]];
let tRowBoxes = [boxes[6],boxes[7],boxes[8]];
let fColBoxes = [boxes[0],boxes[3],boxes[6]];
let sColBoxes = [boxes[1],boxes[4],boxes[7]];
let tColBoxes = [boxes[2],boxes[5],boxes[8]];
let dBoxes1 =[boxes[0],boxes[4],boxes[8]];
let dBoxes2 = [boxes[2],boxes[4],boxes[6]];
let X_Checked = [];
let O_Checked = [];
msg.display ='block';
function checkScore(){
if (X_Checked.includes(fRowBoxes[0] && fRowBoxes[1] && fRowBoxes[2])){
msg.innerHTML =`<h1> ${player1} Wins! </h1>`;
}
}
const tictactoe = (function(){/*START*/
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
for(let i = 0; i<boxes.length; i++){
boxes[i].addEventListener('click',() =>{
if(boxes[i].value){
boxes[i].click(false);
}
else if(boxes[i].textContent === ""){
boxes[i].innerHTML = turn;
checkPlayer();
/**------------------------------------------- */
if (turn === player1){
O_Checked.push(boxes[i]);
console.log(O_Checked);
checkScore();
}
else if (turn === player2){
X_Checked.push(boxes[i]);
console.log( X_Checked);
checkScore();
}
}
});}
}());/*END*/
let checkPlayer = (function(){
if(turn === player1){
turn = player2;
msg.innerHTML = `<h1>Player 2 (O)</h1>`;
}
else if(turn === player2){
turn = player1;
msg.innerHTML = `<h1>Player 1 (X)</h1>`;
}
});
*{box-sizing:border-box;}
body{
margin:0;
padding:0;
font-family:arial;
}
.container{
display:flex;
height:100vh;
width:100%;
position:relative;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: tomato;
/* background-image:linear-gradient(to right, tomato, black, rgb(225, 225, 225)); */
}
.box:hover{
background-color:rgb(230,230,230);
transition: .4s ease-in-out;
}
.box,.grid{
cursor:pointer;
}
.box{
display:flex;
flex-direction:column;
justify-content: center;
align-items:center;
background-color:black;
}
.symbol{
font-size:4em;
font-style:bold;
font-family:arial;
text-transform:uppercase;
text-shadow:0px 0px 5px rgb(100,100,100);
}
.x{
color:tomato;
}
.o{
color:white;
}
.grid{
display: grid;
width: 350px;
grid-gap:10px;
border-radius:10px;
border:solid 10px white;
background-color:white;
grid-template-rows: repeat(3,100px);
grid-template-columns: repeat(3,1fr);
box-shadow: 0px 1px 8px rgb(50, 50, 50);
}
/* .grid:nth-child(even) */
.msg{
color:white;
position:absolute;
text-shadow: 0px 1px 3px rgb(50, 50, 50);
top:15px;
font-size:2em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv ="author" content="Carl Dawkins">
<meta name ="description" content="A Tic Tac Toe Game">
<link type="text/css" href="../css/style.css" rel="stylesheet">
<title>TicTacToe</title>
</head>
<body>
<div class="container">
<div class="msg"> </div>
<div class="grid">
<div id="box-1" class="box" ></div>
<div id="box-2" class="box" ></div>
<div id="box-3" class="box" ></div>
<div id="box-4" class="box" ></div>
<div id="box-5" class="box" ></div>
<div id="box-6" class="box" ></div>
<div id="box-7" class="box" ></div>
<div id="box-8" class="box" ></div>
<div id="box-9" class="box" ></div>
</div>
</div>
<script src="../js/script.js"></script>
</body>
</html>
You are storing elements to array and try to compare elements.
I think comparing value (o or x) or id (box-1 ...) is better
X_Checked.every(e => e.innerText.trim() == 'x')
I have two divs, one is hidden and the other one is visible. I'm using css display:none; to hide first and using style.display="block";
when I refresh the page it gives same div name in the address bar but the div is hidden.
I just want the div to stay block after refreshing or submitting the form inside the div
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<style>
#content {
flex:8;
display:flex;
flex-direction:row;
justify-content:space-between;
flex-basis:100%;
padding:0 10px 0x 10px;
text-align:center;
}
#leftnav {
flex:1;
padding-top:20px;
}
#midcontent {
flex:9;
text-align:center;
padding-top:20px;
display:block;
}
#leftnav ul {
display: block;
margin: 0px;
padding: 0px;
list-style-type: none;
}
#m1,#m2,#m3 {
flex:9;
text-align:center;
padding-top:20px;
display:none;
}
</style>
</head>
<body>
<div id="content">
<div id="leftnav" align="center">
<ul>
<li>Page m1</li>
<li>Page m2</li>
<li>Page m3</li>
</ul>
</div>
<div id="midcontent" align="center">
<p>Home Page</p>
</div>
<div id="m1" align="center">
<p>Div m1</p>
</div>
<div id="m2" align="center">
<p>Div m2</p>
</div>
<div id="m3" align="center">
<p>Div m3</p>
</div>
</div>
<script type="text/javascript">
var d=document.getElementById('midcontent');
var d1=document.getElementById('m1');
var d2=document.getElementById('m2');
var d3=document.getElementById('m3');
function div1() {
if(d.style.display === "block") {
d.style.display = "none";
d1.style.display = "block";
} else {
d.style.display = "none";
d1.style.display = "block";
d2.style.display = "none";
d3.style.display = "none";
}
}
function div2() {
if(d.style.display === "block") {
d.style.display = "none";
d2.style.display = "block";
} else {
d.style.display = "none";
d1.style.display = "none";
d2.style.display = "block";
d3.style.display = "none";
}
}
function div3() {
if(d.style.display === "block") {
d.style.display = "none";
d3.style.display = "block";
} else {
d.style.display = "none";
d1.style.display = "none";
d2.style.display = "none";
d3.style.display = "block";
}
}
</script>
</body>
</html>
change:
function div1() {
var d=document.getElementById('midcontent');
var d1=document.getElementById('m1');
if(d.style.display === "block") {
d.style.display = "none";
d1.style.display = "block";
} else {
d.style.display = "none";
d1.style.display = "block";
}
}
to:
function toggleDiv() {
document.getElementById('midcontent').style.display = "none";
document.getElementById('m1').style.display = "block";
}
"i just want the div to stay block after refreshing" call the function on page load in html to make it execute after refresh of page:
<body onLoad="toggleDiv()">
<!-- Your html content -->
</body>
alternatively you can also do it in js:
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
toggleDiv()
});
If you want more in depth persistance and/or variable changes please provide additional information on how and why you want to do this exactly! Hope it helps! :)
I'm trying to make an alert in JavaScript which warns the user that they probably shouldn't reload the page. But I want them to be able to navigate to other pages without an alert, just not refresh the current page. I have found some alerts but they either provide alerts in both cases, or provide an alert and refresh the page anyway. I want the user to be warned and then be able to stop the page from refreshing. I guess it means that they also shouldn't be able to go back to the page once they have left it?
<body onunload="window.alert('Hello!');">
You can use onbeforeunload and set a variable as follows:
var l=false;
window.onbeforeunload = function() {
if (!l) {
return "you shouldn't leave";
}
}
Leave
(This doesn't work on Run Snippet because it's in an iframe)
This you may find useful. In conjunction With above code;;;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #000;
border-radius:7px;
width:550px;
z-index: 10;
}
#dialogbox > div{ background:#FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: #666; font-size:19px; padding:10px; color:#CCC; }
#dialogbox > div > #dialogboxbody{ background: #333; padding:20px; color:#FFF; }
#dialogbox > div > #dialogboxfoot{ background: #666; padding:10px; text-align:right; }
</style>
<script>
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Acknowledge This Message";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function deletePost(id){
var db_id = id.replace("post_", "");
// Run Ajax request here to delete post from database
document.body.removeChild(document.getElementById(id));
}
function CustomConfirm(){
this.render = function(dialog,op,id){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "Confirm that action";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Confirm.yes(\''+op+'\',\''+id+'\')">Yes</button> <button onclick="Confirm.no()">No</button>';
}
this.no = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
this.yes = function(op,id){
if(op == "delete_post"){
deletePost(id);
}
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Confirm = new CustomConfirm();
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div>
<div id="dialogboxhead"></div>
<div id="dialogboxbody"></div>
<div id="dialogboxfoot"></div>
</div>
</div>
<p id="post_1">
Today is a lovely day ...
<button onclick="Confirm.render('Delete Post?','delete_post','post_1')">Delete</button>
</p>
<p id="post_2">
I like pickles ...
<button onclick="Confirm.render('Delete Post?','delete_post','post_2')">Delete</button>
</p>
<button onclick="Alert.render('Hello World')">Custom Alert</button>
</body>
</html>
This allows you to give Custom alerts.
Explination of the code here: Alert Box
I want to use drag & drop functionality for ibooks app of ipad using Javascript. Attached is the code that i have used in file, though it is working on browser but am not able to see it in ipad. It would be great if someone will help me with the same.
dfgdf
<style type="text/css" xml:space="preserve">
/* DEMO CSS */
body{
width:100%;
margin:0px;
padding:0px;
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; /* Font to use */
}
#heading{
height:100px;
}
/* END DEMO CSS */
#dragScriptContainer{ /* BIG div containing HTML needed for the entire script */
width:400px;
margin:0 auto;
border:1px solid #000;
height:400px;
margin-top:20px;
padding:3px;
-moz-user-select:no;
}
#questionDiv{ /* Big div for all the questions */
float:left;
height:100%;
width:100px;
border:1px solid #000;
padding:2px;
}
#answerDiv{ /* Big div for all the answers */
float:right;
height:100%;
width:50px;
border:1px solid #000;
padding:2px;
}
#questionDiv div,#answerDiv div,#dragContent div{ /* General rules for small divs - i.e. specific questions and answers */
width:45px;
height:20px;
line-height:20px;
float:left;
margin-right:2px;
margin-bottom:2px;
text-align:center;
}
#dragContent div{ /* Drag content div - i.e. specific answers when they are beeing dragged */
border:1px solid #000;
}
#answerDiv .dragDropSmallBox{ /* Small answer divs */
border:1px solid #000;
cursor:pointer;
}
#questionDiv .dragDropSmallBox{ /* Small answer divs */
border:1px solid #000;
cursor:pointer;
background-color:#E2EBED; /* Light blue background color */
}
#questionDiv div div{ /* div after it has been dragged from right to left box */
margin:0px;
border:0px;
padding:0px;
background-color:#FFF;
}
#questionDiv .destinationBox{ /* Small empty boxes for the questions - i.e. where answers could be dragged */
border:0px;
background-color:#DDD;
width:47px;
height:22px;
}
#questionDiv .correctAnswer{ /* CSS indicating correct answer */
background-color:green;
color:#fff;
border:1px solid #000;
}
#questionDiv .wrongAnswer{ /* CSS indicating wrong answer */
background-color:red;
color:#fff;
border:1px solid #000;
}
#dragContent div{
background-color:#FFF;
}
#questionDiv .dragContentOver{ /* Mouse over question boxes - i.e. indicating where dragged element will be appended if mouse button is relased */
border:1px solid #F00;
}
#answerDiv.dragContentOver{ /* Mouse over answer box - i.e. indicating where dragged element will be appended if mouse button is relased */
border:1px solid #F00;
}
/* NEVER CHANGE THIS */
#dragContent{
position:absolute;
display:none;
}
</style>
<script type="text/javascript">
//<![CDATA[
/************************************************************************************************************
(C) www.dhtmlgoodies.com, November 2005
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var shuffleQuestions = true; /* Shuffle questions ? */
var shuffleAnswers = true; /* Shuffle answers ? */
var lockedAfterDrag = false; /* Lock items after they have been dragged, i.e. the user get's only one shot for the correct answer */
function quizIsFinished()
{
// This function is called when everything is solved
}
/* Don't change anything below here */
var dragContentDiv = false;
var dragContent = false;
var dragSource = false;
var dragDropTimer = -1;
var destinationObjArray = new Array();
var destination = false;
var dragSourceParent = false;
var dragSourceNextSibling = false;
var answerDiv;
var questionDiv;
var sourceObjectArray = new Array();
var arrayOfEmptyBoxes = new Array();
var arrayOfAnswers = new Array();
function getTopPos(inputObj)
{
if(!inputObj || !inputObj.offsetTop)return 0;
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue;
}
function getLeftPos(inputObj)
{
if(!inputObj || !inputObj.offsetLeft)return 0;
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
function cancelEvent()
{
return false;
}
function initDragDrop(e)
{
if(document.all)e = event;
if(lockedAfterDrag && this.parentNode.parentNode.id=='questionDiv')return;
dragContentDiv.style.left = e.clientX + Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + 'px';
dragContentDiv.style.top = e.clientY + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + 'px';
dragSource = this;
dragSourceParent = this.parentNode;
dragSourceNextSibling = false;
if(this.nextSibling)dragSourceNextSibling = this.nextSibling;
if(!dragSourceNextSibling.tagName)dragSourceNextSibling = dragSourceNextSibling.nextSibling;
dragDropTimer=0;
timeoutBeforeDrag();
return false;
}
function timeoutBeforeDrag(){
if(dragDropTimer>=0 && dragDropTimer<10){
dragDropTimer = dragDropTimer +1;
setTimeout('timeoutBeforeDrag()',10);
return;
}
if(dragDropTimer>=10){
dragContentDiv.style.display='block';
dragContentDiv.innerHTML = '';
dragContentDiv.appendChild(dragSource);
}
}
function dragDropMove(e)
{
if(dragDropTimer<10){
return;
}
if(document.all)e = event;
var scrollTop = Math.max(document.documentElement.scrollTop,document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
dragContentDiv.style.left = e.clientX + scrollLeft + 'px';
dragContentDiv.style.top = e.clientY + scrollTop + 'px';
var dragWidth = dragSource.offsetWidth;
var dragHeight = dragSource.offsetHeight;
var objFound = false;
var mouseX = e.clientX + scrollLeft;
var mouseY = e.clientY + scrollTop;
destination = false;
for(var no=0;no<destinationObjArray.length;no++){
var left = destinationObjArray[no]['left'];
var top = destinationObjArray[no]['top'];
var width = destinationObjArray[no]['width'];
var height = destinationObjArray[no]['height'];
destinationObjArray[no]['obj'].className = 'destinationBox';
var subs = destinationObjArray[no]['obj'].getElementsByTagName('div');
if(!objFound && subs.length==0){
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destinationObjArray[no]['obj'].className='dragContentOver';
destination = destinationObjArray[no]['obj'];
objFound = true;
}
}
}
sourceObjectArray['obj'].className='';
if(!objFound){
var left = sourceObjectArray['left'];
var top = sourceObjectArray['top'];
var width = sourceObjectArray['width'];
var height = sourceObjectArray['height'];
if(mouseX < (left/1 + width/1) && (mouseX + dragWidth/1) >left && mouseY < (top/1 + height/1) && (mouseY + dragHeight/1) >top){
destination = sourceObjectArray['obj'];
sourceObjectArray['obj'].className='dragContentOver';
}
}
return false;
}
function dragDropEnd()
{
if(dragDropTimer<10){
dragDropTimer = -1;
return;
}
dragContentDiv.style.display='none';
sourceObjectArray['obj'].style.backgroundColor = '#FFF';
if(destination){
destination.appendChild(dragSource);
destination.className='destinationBox';
// Check if position is correct, i.e. correct answer to the question
if(!destination.id || destination.id!='answerDiv'){
var previousEl = dragSource.parentNode.previousSibling;
if(!previousEl.tagName)previousEl = previousEl.previousSibling;
var numericId = previousEl.id.replace(/[^0-9]/g,'');
var numericIdSource = dragSource.id.replace(/[^0-9]/g,'');
if(numericId==numericIdSource){
dragSource.className='correctAnswer';
checkAllAnswers();
}
else
dragSource.className='wrongAnswer';
}
if(destination.id && destination.id=='answerDiv'){
dragSource.className='dragDropSmallBox';
}
}else{
if(dragSourceNextSibling)
dragSourceNextSibling.parentNode.insertBefore(dragSource,dragSourceNextSibling);
else
dragSourceParent.appendChild(dragSource);
}
dragDropTimer = -1;
dragSourceNextSibling = false;
dragSourceParent = false;
destination = false;
}
function checkAllAnswers()
{
for(var no=0;no<arrayOfEmptyBoxes.length;no++){
var sub = arrayOfEmptyBoxes[no].getElementsByTagName('div');
if(sub.length==0)return;
if(sub[0].className!='correctAnswer'){
return;
}
}
quizIsFinished();
}
function resetPositions()
{
if(dragDropTimer>=10)return;
for(var no=0;no<destinationObjArray.length;no++){
if(destinationObjArray[no]['obj']){
destinationObjArray[no]['left'] = getLeftPos(destinationObjArray[no]['obj'])
destinationObjArray[no]['top'] = getTopPos(destinationObjArray[no]['obj'])
}
}
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
}
function initDragDropScript()
{
dragContentDiv = document.getElementById('dragContent');
answerDiv = document.getElementById('answerDiv');
answerDiv.onselectstart = cancelEvent;
var divs = answerDiv.getElementsByTagName('div');
var answers = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='dragDropSmallBox'){
divs[no].onmousedown = initDragDrop;
answers[answers.length] = divs[no];
arrayOfAnswers[arrayOfAnswers.length] = divs[no];
}
}
if(shuffleAnswers){
for(var no=0;no<(answers.length*10);no++){
var randomIndex = Math.floor(Math.random() * answers.length);
answerDiv.appendChild(answers[randomIndex]);
}
}
sourceObjectArray['obj'] = answerDiv;
sourceObjectArray['left'] = getLeftPos(answerDiv);
sourceObjectArray['top'] = getTopPos(answerDiv);
sourceObjectArray['width'] = answerDiv.offsetWidth;
sourceObjectArray['height'] = answerDiv.offsetHeight;
questionDiv = document.getElementById('questionDiv');
questionDiv.onselectstart = cancelEvent;
var divs = questionDiv.getElementsByTagName('div');
var questions = new Array();
var questionsOpenBoxes = new Array();
for(var no=0;no<divs.length;no++){
if(divs[no].className=='destinationBox'){
var index = destinationObjArray.length;
destinationObjArray[index] = new Array();
destinationObjArray[index]['obj'] = divs[no];
destinationObjArray[index]['left'] = getLeftPos(divs[no])
destinationObjArray[index]['top'] = getTopPos(divs[no])
destinationObjArray[index]['width'] = divs[no].offsetWidth;
destinationObjArray[index]['height'] = divs[no].offsetHeight;
questionsOpenBoxes[questionsOpenBoxes.length] = divs[no];
arrayOfEmptyBoxes[arrayOfEmptyBoxes.length] = divs[no];
}
if(divs[no].className=='dragDropSmallBox'){
questions[questions.length] = divs[no];
}
}
if(shuffleQuestions){
for(var no=0;no<(questions.length*10);no++){
var randomIndex = Math.floor(Math.random() * questions.length);
questionDiv.appendChild(questions[randomIndex]);
questionDiv.appendChild(questionsOpenBoxes[randomIndex]);
destinationObjArray[destinationObjArray.length] = destinationObjArray[randomIndex];
destinationObjArray.splice(randomIndex,1);
questionsOpenBoxes[questionsOpenBoxes.length] = questionsOpenBoxes[randomIndex];
questionsOpenBoxes.splice(randomIndex,1);
questions[questions.length] = questions[randomIndex];
questions.splice(randomIndex,1);
}
}
questionDiv.style.visibility = 'visible';
answerDiv.style.visibility = 'visible';
document.documentElement.onmouseup = dragDropEnd;
document.documentElement.onmousemove = dragDropMove;
setTimeout('resetPositions()',150);
window.onresize = resetPositions;
}
/* Reset the form */
function dragDropResetForm()
{
for(var no=0;no<arrayOfAnswers.length;no++){
arrayOfAnswers[no].className='dragDropSmallBox'
answerDiv.appendChild(arrayOfAnswers[no]);
}
}
window.onload = initDragDropScript;
//]]>
</script>
</head>
<body>
<div id="dragScriptContainer">
<div id="questionDiv">
<div class="dragDropSmallBox" id="q1">
5x1
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q2">
5x2
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q3">
5x3
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q4">
5x4
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q5">
5x5
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q6">
5x6
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q7">
5x7
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q8">
5x8
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q9">
5x9
</div>
<div class="destinationBox"></div>
<div class="dragDropSmallBox" id="q10">
5x10
</div>
<div class="destinationBox"></div>
</div>
<div id="answerDiv">
<div class="dragDropSmallBox" id="a1">
5
</div>
<div class="dragDropSmallBox" id="a2">
10
</div>
<div class="dragDropSmallBox" id="a3">
15
</div>
<div class="dragDropSmallBox" id="a4">
20
</div>
<div class="dragDropSmallBox" id="a5">
25
</div>
<div class="dragDropSmallBox" id="a6">
30
</div>
<div class="dragDropSmallBox" id="a7">
35
</div>
<div class="dragDropSmallBox" id="a8">
40
</div>
<div class="dragDropSmallBox" id="a9">
45
</div>
<div class="dragDropSmallBox" id="a10">
50
</div>
</div>
</div>
<div id="dragContent"></div>
<input type="button" onclick="dragDropResetForm();return false"
value="Reset" />
</body>
</html>
I have two pages with almost the same code. Both have this CSS code and the two divs:
<style type="text/css">
.visfarve { position:relative; float:left; padding:5px; border:1px solid #666; }
.farver { border:1px solid black; width:75px; height:10px; }
.valgtfarve { width:95px; height:15px; display:block; background-color:white; text-align:center; }
</style>
<div id="vis" style="display:block; font-size:11px;">
Vis farver
</div>
<div id="skjul" style="display:none; font-size:11px;">
Skjul farver
</div>
One page then has this construct:
<table style="width:730px;">
<tr>
<td width="510px">
<div id="visfarve" style="display:none; margin-top:11px;">&npsp;</div>
</td>
<td id="viser" style="border-radius:10px; width:220px; height:inherit"></td>
</tr>
</table>
The other page has this obstruction:
<div id="visfarve" style="display:none; margin-top:11px;"> </div>
<div id="viser" style="margin-top:50px; border-radius:10px; display:none;"> </div>
They share these two js functions:
var farve1 = ["3D3D34","463834","3F383D","433839","333F44","3B3B40","38413D","304344","483C33","313F48","37463B","35453F"];
var farve2 = ["S8505-Y20R","7812-Y87R","S8010-R30B","S8010-R10B","8108-R93B","8207-R38B","S8502-G","S8010-B30G","S8010-Y70R","S8010-R90B","S8010-G10Y","S8010-B90G"];
function colors(vis) {
var setheight = 0;
for(i=farve1.length-1;i>-1;i--) { skriv += "<div class='visfarve' onmouseover=\"document.getElementById('viser').style.background = '#" + farve1[i] + "';\" onmouseout=\"document.getElementById('viser').style.background = 'white';\" onclick='valgtfarve(\"" + farve2[i] + "\",\"#" + farve1[i] + "\");'><table><tr><td class='farver' title='Klik for at vælge' style='background-color:#" + farve1[i] + ";'></td></tr><tr><td><p>" + farve2[i] + "</p></td></tr></table></div>"; setheight += 10; }
document.getElementById('visfarve').innerHTML = skriv;
if(vis) {
document.getElementById('vis').style.display = "none";
document.getElementById('skjul').style.display = "block";
document.getElementById('visfarve').style.display = "block";
document.getElementById('viser').style.display = "block";
document.getElementById('viser').style.height = setheight + "px";
}
else {
document.getElementById('vis').style.display = "block";
document.getElementById('skjul').style.display = "none";
document.getElementById('visfarve').style.display = "none";
document.getElementById('viser').style.display = "none";
document.getElementById('viser').style.height = 0 + "px";
}
}
function valgtfarve(kode, farve) {
if(!valgt) {
if(confirm("Tones en maling kan den ikke returneres.\nAccepter fraskrivelse af returret for tonet maling?")) { valgt = true; }
else {
document.getElementById('vis').style.display = "block";
document.getElementById('skjul').style.display = "none";
document.getElementById('viser').style.height = "0px";
document.getElementById('visfarve').style.display = "none"; return false;
}}
document.getElementById('valgtfarve').value = kode;
document.getElementById('valgtfarve').style.backgroundColor = farve;
}
When I use the div construct the floating divs lies niceley next to each other with 5 divs in each line and breaks when the container div edge is reached. However, inside the td the divs insists on each having the full width of the td - resulting in only one div per line.
How do I get divs inside a td to keep width and float left?
Let's start from a jsFiddle link : Here
I think it's a good practice when you post question.
Please explain where is the problem, in the jsfiddle page I don't see your bug.
I did only little modification, no relevant code changes.
I only defined the variable
var skriv = "";