JavaScript doesn't write on the page - javascript

I'm making this game where there are 2 boxes and if you click the right one you win.
I have this problem where when the player clicks on a box it doesn't show if he won or lost and it can only be seen if you inspect element.
I already tried to change the "console.log" to "document.write" but it doesn't work. Can someone tell me how to write something when the player clicks on a box ?
var button1 = document.getElementById('button1')
var button2 = document.getElementById('button2')
var array = [('button1'), ('button2')];
var winItem = 1;
function getRandomItemNum(length) {
return Math.ceil(Math.random() * length)
}
function recalculateWinItem() {
winItem = getRandomItemNum(array.length);
}
function checkIsWin(buttonNum) {
console.log(`Clicked ${buttonNum}. Win item: ${winItem}`);
console.log(buttonNum === winItem ? "You won" : "You lose");
}
recalculateWinItem();
<button id="button1" onclick="checkIsWin(1)" style="height: 200px; width: 200px; position: absolute; left: 33%; background-color: black; color: blue;">1</button>
<button id="button2" onclick="checkIsWin(2)" style="height: 200px; width: 200px; position: absolute; right: 33%; background-color: black; color: red;">2</button>

Add a container to the page
<div id="result"></div>
and use
document.getElementById("result").innerText = winItem ? "You won" : "You lose"; // or innerHTML if tags in the result
NEVER use document.write after the page has loaded since it will wipe the page and scripts
function getRandomItemNum(length) {
return Math.ceil(Math.random() * length)
}
function recalculateWinItem() {
winItem = getRandomItemNum(array.length);
}
function checkIsWin(buttonNum) {
var text = `Clicked <b>${buttonNum}</b>. Win item: ${winItem}; `
text += buttonNum === winItem ? "You won" : "You lose";
document.getElementById("result").innerHTML = text;
}
var array = [...document.querySelectorAll("#container .but")].map(function(but) {
but.addEventListener("click",function() { checkIsWin(+this.id.replace("button",""))})
return `(${but.id})`
});
window.addEventListener("load", function() {
document.getElementById("start").addEventListener("click", recalculateWinItem)
recalculateWinItem();
})
.but {
height: 200px;
width: 200px;
position: absolute;
top: 10%;
background-color: black;
}
#button1 {
left: 33%;
background-color: black;
color: blue;
color: blue;
}
#button2 {
right: 33%;
background-color: black;
color: red;
}
<div id="result"></div>
<hr/>
<div id="container" style="width:100%">
<button id="button1" class="but">1</button>
<button id="button2" class="but">2</button>
</div>
<button type="button" id="start">Start</button>

document.write is just for test not for use in real world, don't use it in your work, rather you can create a div or a modal that for example will have a class or id #modal and use innerHTML to show your results;
document.getElementById('modal').innerHTML = your results

create a paragrapg with an id
get the ID of the paragraph
and use .innerhtml to add the output
document.getElementById('response').innerHTML='you win;

HTML
<button id="button1" onclick="checkIsWin(1)" style="height: 200px; width: 200px; position: absolute; left: 33%; background-color: black; color: blue;">1</button>
<button id="button2" onclick="checkIsWin(2)" style="height: 200px; width: 200px; position: absolute; right: 33%; background-color: black; color: red;">2</button>
<div id="container"></div>
Javascript
function checkIsWin(buttonNum) {
document.getElementById('container').innerText = (buttonNum === winItem ? "You won" : "You lose");
}

Related

Can I have a button that is always showing but still changes the images when you click on it?

I followed this tutorial: https://stashable.blog/2018/12/30/make-a-dress-up-game-using-javascript-html-and-css/ and it worked perfectly, but I would like to change something.
The tutorial uses only one doll, and I have multiple dolls (for skin colors) so I treated it like the others options (shoes, pants, etc), and because of that the game appears empty at the beginning.
It is the first time I try doing something like this (well, I used to use flash for similar things when I was 10-12, but I remember almost anything and it was different I think...) and I have no clue how to do what I want. I guessed I had to change something of the ".css" file, and I tried using:
background-image: url("../img/doll1.png");
in the #doll{ part, but that doesn't allow the button to change the image.
I'm really lost here and I wans't able to find any solution or tutorial online. Please help :(
var state = {
a: 0,
b: 0,
c: 0
};
function nexthairback() {
console.log("inside function nexthairback");
console.log(state.a);
var hairback = document.getElementById("hairback");
if (state.a === 0) {
hairback.setAttribute("class", "hairback1");
state.a++;
console.log(state.a);
} else
if (state.a === 1) {
hairback.setAttribute("class", "hairback2");
state.a = 0;
}
}
function nextdoll() {
console.log("inside function nextdoll");
console.log(state.b);
var doll = document.getElementById("doll");
if (state.b === 0) {
doll.setAttribute("class", "doll1");
state.b++;
console.log(state.b);
} else
if (state.b === 1) {
doll.setAttribute("class", "doll2");
state.b = 0;
}
}
function nexthairfront() {
console.log("inside function nexthairfront");
console.log(state.c);
var hairfront = document.getElementById("hairfront");
if (state.c === 0) {
hairfront.setAttribute("class", "hairfront1");
state.c++;
console.log(state.c);
} else
if (state.c === 1) {
hairfront.setAttribute("class", "hairfront2");
state.c = 0;
}
}
window.onload = init;
function init() {
console.log("window has loaded");
state.a = 0;
state.b = 0;
state.c = 0;
}
#container {
position: absolute;
margin: auto;
width: 1200px;
height: 1540px;
background-color: white;
}
#background {
position: absolute;
width: 1000px;
height: 1340px;
left: 100px;
right: 100px;
top: 100px;
bottom: 100px;
background-image: url("../img/background.png");
}
#hairback {
position: absolute;
width: 1000px;
height: 1340px;
}
#doll {
position: absolute;
width: 1000px;
height: 1340px;
}
#hairfront {
position: absolute;
width: 1000px;
height: 1340px;
}
.doll1 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/doll1.png");
}
.doll2 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/doll2.png");
}
.hairback1 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/hairback1.png");
}
.hairback2 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/hairback2.png");
}
.hairfront1 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/hairfront1.png");
}
.hairfront2 {
position: absolute;
width: 1000px;
height: 1340px;
background-image: url("../img/hairfront2.png");
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<title> Dress up game</title>
<body>
<div id="container">
<div id="background">
<div id="hairback"></div>
<div id="doll"></div>
<div id="hairfront"></div>
</div>
<input type="button" value="NEXT" id="nexthairback" onclick="nexthairback()">
<input type="button" value="NEXT" id="nextdoll" onclick="nextdoll()">
<input type="button" value="NEXT" id="nexthairfront" onclick="nexthairfront()">
</div>
<script src="js/code.js"></script>
</body>
</html>
enter image description here
Welcome to StackOverflow Blue Dots!
It is very unclear to me what you exactly want, but from what I understand is that you want to change the doll with a background-image right? We can do this with JavaScript.
What we first do is get the document by the ID that it has been assigned in HTML.
const doll = document.getElementById("doll");
After this, we want to change the styles right? The background-image to be specific, we can do this in JavaScript as well!
doll.style.backgroundImage = "url('Put your image directory here')";
You have to figure out for yourself now how to make this happen on a button click, aswell as making the image directory url change on the button click every time. Good Luck ;)

Function not working after push() elements in html file

I want to create a to do list that will add elements typed in <input type="text"> and delete when clicked on button with class .delete. When ever I push elements in an array. And innerHTML it in html page, the delete button stops working. The delete button works for elements that are written into Html code. If someone can help me I will be very thankful.
`
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
addText.addEventListener('click', addItem);
<style>
body {
width: 100%;
height: 100vh;
background-color: rgb(115, 115, 197);
margin: 0;
padding: 0;
position: relative;
}
.container {
width:50%;
height:70%;
position: absolute;
background-color: rgb(241, 241, 241);
font-family: Arial, Helvetica, sans-serif;
border-bottom-left-radius: 25px;
border-bottom-right-radius: 25px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow-y: scroll;
}
.heading {
width: 100%;
height: 122px;
background-color: #5B45B9;
display: flex;
align-items: center;
justify-content: center;
}
.heading h1 {
color: white;
font-size: 40px;
}
.item-list {
width: 100%;
padding: 0 0 30px 0;
}
.item-list div {
width: auto;
height: 60px;
}
p {
width: 60%;
float: left;
font-size: 25px;
padding-left: 30px;
margin-top: 12px ;
}
.item-list button {
width: 60px;
height: 60px;
font-size: 18px;
float: right;
}
.delete {
font-size: 30px;
color: red;
}
.input_form {
width: 100%;
padding: 30px 0 30px 0;
position: absolute;
bottom: 0;
text-align: center;
}
.input_form .input_bar {
width: 80%;
height: 50px;
font-size: 18px;
border: none;
}
.input_form button {
width: 10%;
height: 50px;
float: right;
margin-right: 30px;
}
</style>
<html>
<head>
</head>
<body>
<div class="container">
<div class="heading">
<h1>TO-DO LIST</h1>
</div>
<div class="item-list">
<div>
<p>TEEXT2</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
</div>
</body>
</html>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
<script src="script.js"></script>
</div>
</body>
</html>`
You actually only trigger DOM "original" delete button (button loaded with your HTML code) with the line :
let deleteText = document.querySelectorAll('.delete'); // delete button
Your others .delete are loaded after the first DOM loading and are not even listed in "deleteText" array !
You have to refresh deleteText every time you add a new item. Something like :
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
function triggerDeleteButton(){
deleteText = document.querySelectorAll('.delete'); // delete button
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
}
addText.addEventListener('click', function(){
addItem() ;
triggerDeleteButton() ;
}
);
Without refreshing, you can add and edit data by using local storage
For example, like below, you can try once!
<script>
let customerData = [];
// Inserting new customer record into local storage
function insert() {
let company = document.getElementById("company").value;
let obj = {company};
customerData.push(obj);
synData(customerData);
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
clearFileds();
displayelements(customerDetails);
}
function displayelements(customerDetails) {
let html = "<table id='customer_data' border='1'><tr><th>Sl No</th><th>Company</th><th>Delete</th></tr>";
if(customerDetails == '') {
html+="<tr>No record found!</tr>";
} else {
customerDetails.map((values, index) => {
html+="<tr id='row_data'>";
html+="<td>"+index+"</td>";
html+="<td>"+values.company+"</td>";
html+="<td onclick='deleteRow(" + index + ")'>Delete</td>";
html+="</tr>";
} )
}
html+="</table>";
document.getElementById("display").innerHTML = html;
clearFileds();
}
// Delete the specific customer record from local storage
function deleteRow(deleteKey) {
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
customerDetails.map((values, index) => {
if (index == deleteKey) {
customerDetails.splice(index, 1);
}
})
customerData = customerDetails;
synData(customerDetails);
displayelements(customerDetails);
}
// Clearing the form input field data
function clearFileds() {
document.getElementById("company").value = '';
}
// Updating local storage data
function synData(customerDetails) {
localStorage.setItem('customerString', JSON.stringify(customerDetails));
}
</script>
<html>
<head>
<title>Save</title>
</head>
<script ></script>
<body id="format_background">
<div id="customerAction" >
<h1>Customer data</h1>
<label>Company Name </label>
<input id="company" type="text" />
<button type="button" value="Save&Show" onclick="insert()" id="insert">Save</button>
</div>
<div id="display"></div>
</body>
</html>

Check if DOM elements are present inside a DIV then run functions assigned to those elements in order

i'm trying to develop a game using html, css and js. At the moment I'm focusing on manipulating DOM elements without using the canvas tag. My idea is to create a pseudo graphical programming language, similar to the Blockly environment. So far I have inserted 3 clickable elements inside #toolbox that create their copies in #workspace.
Now, I am trying to assign functions to the elements present in #workspace, which once pressed the Run button are executed in order of appearance, so as to create a queue of commands that is able to move the pink square inside #output_section.
Therefore I cannot understand how to write the function that is able to verify the presence of the elements and then be able to perform the different functions assigned to these elements.
Any ideas? :D
I'm using Jquery 3.3.1
function addRed() {
var redWorkspace = document.createElement("DIV");
redWorkspace.className = "remove-block block red";
document.getElementById("workspace").appendChild(redWorkspace);
};
function addBlue() {
var blueWorkspace = document.createElement("DIV");
blueWorkspace.className = "remove-block block blue";
document.getElementById("workspace").appendChild(blueWorkspace);
};
function addGreen() {
var greenWorkspace = document.createElement("DIV");
greenWorkspace.className = "remove-block block green";
document.getElementById("workspace").appendChild(greenWorkspace);
};
$("#clear_workspace").click(function () {
$("#workspace").empty();
});
$(document).on("click", ".remove-block", function () {
$(this).closest("div").remove();
});
html,
body {
margin: 0;
padding: 0;
}
#workspace {
display: flex;
height: 100px;
padding: 10px;
background: black;
}
#toolbox {
display: flex;
padding: 10px;
width: 300px;
}
#output_section {
height: 500px;
width: 500px;
border: solid black;
margin: 10px;
position: relative;
}
#moving_square {
position: absolute;
bottom: 0;
right: 0;
width: 100px;
height: 100px;
background: pink;
}
.block {
height: 100px;
width: 100px;
}
.red {
background: red;
}
.blue {
background: cyan;
}
.green {
background: green;
}
.grey {
background: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div id="workspace"></div>
<div id="workspace-menu">
<button id="run_workspace">Run</button>
<button id="clear_workspace">Clear</button>
</div>
<div id="toolbox" class="grey">
<div onclick="addRed()" class="block red">Left</div>
<div onclick="addBlue()" class="block blue">Up</div>
<div onclick="addGreen()" class="block green">Right</div>
</div>
<div id="output_section">
<div id="moving_square"></div>
</div>
</body>
</html>
Completely untested but run button does something along the lines of:
$("#run_workspace").click(function() {
$("#workspace .block").each(function(elem) {
if (elem.hasClass("red")) {
moveObjectLeft();
} else if (elem.hasClass("green")) {
moveObjectRight();
} else if (elem.hasClass("blue")) {
moveObjectUp();
}
});
});
Commonly, it's a good idea to store all required information in arrays and objects, and use HTML only to display your data.
Also, if you are already using jQuery - use it for all 100%)
Made some improvements:
let mobs = {
pinky: {
node: $('#moving_square'),
coors: { top: 400, left: 400 },
step: 30,
moveQueue: [],
// moveTimeout ???
},
}; // storing here all created objects, that must move.
/* Each [moveQueue] array will store the chain of moves, like ["up", "up", "left"]
You can take each "key-word" of move, and get required function buy that key,
from the 'move' object */
let move = { // Think about how to simlify this object and functions. It's possible!)
left: function (obj) {
let left = obj.coors.left = (obj.coors.left - obj.step);
obj.node.css('left', left + 'px');
},
up: function (obj) {
let top = obj.coors.top = (obj.coors.top - obj.step);
obj.node.css('top', top + 'px');
},
right: function (obj) {
let left = obj.coors.left = (obj.coors.left + obj.step);
obj.node.css('left', left + 'px');
}
};
let stepTimeout = 1000;
let running = false;
let timeouts = {}; // store all running timeouts here,
// and clear everything with for( key in obj ) loop, if required
$('#toolbox .block').on('click', function () {
let color = $(this).attr('data-color');
let workBlock = '<div class="remove-block block ' + color + '"></div>';
$('#workspace').append(workBlock);
mobs.pinky.moveQueue.push( $(this).text().toLowerCase() ); // .attr('data-direction');
// instead of pinky - any other currently selected object
// $(this).text().toLowerCase() — must be "left", "up", "right"
});
$('#run_workspace').on('click', function () {
running = true;
runCode();
function runCode() {
for (let obj in mobs) { // mobile objects may be multiple
// Inside the loop, obj == mobs each key name. Here it's == "pinky"
let i = 0;
let pinky = mobs[obj];
localRun();
function localRun() {
let direction = pinky.moveQueue[i]; // getting direction key by array index.
move[direction](pinky); // calling the required function from storage.
if (pinky.moveQueue[++i] && running ) {
// self-calling again, if moveQueue has next element.
// At the same time increasing i by +1 ( ++i )
timeouts[obj] = setTimeout(localRun, stepTimeout);
}
}
}
}
});
$("#clear_workspace").click(function () {
$("#workspace").empty();
});
$('#workspace').on("click", ".remove-block", function () {
$(this).closest("div").remove();
});
html,
body {
margin: 0;
padding: 0;
}
#workspace {
display: flex;
height: 100px;
padding: 10px;
background: black;
}
#toolbox {
display: flex;
padding: 10px;
width: 300px;
}
#output_section {
height: 500px;
width: 500px;
border: solid black;
margin: 10px;
position: relative;
}
#moving_square {
position: absolute;
top: 400px;
left: 400px;
width: 100px;
height: 100px;
background: pink;
}
.block {
height: 100px;
width: 100px;
}
.red {
background: red;
}
.blue {
background: cyan;
}
.green {
background: green;
}
.grey {
background: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="workspace"></div>
<div id="workspace-menu">
<button id="run_workspace">Run</button>
<button id="clear_workspace">Clear</button>
</div>
<div id="toolbox" class="grey">
<div data-color="red" class="block red">Left</div>
<div data-color="blue" class="block blue">Up</div>
<div data-color="green" class="block green">Right</div>
</div>
<div id="output_section">
<div id="moving_square"></div>
</div>
But... jQuery was used only for clicks... Translation to JS:
let mobs = {
pinky: {
node: document.getElementById('moving_square'),
coors: { top: 400, left: 400 },
step: 30,
moveQueue: [],
},
};
let move = {
left: function (obj) {
let left = obj.coors.left = (obj.coors.left - obj.step);
obj.node.style.left = left + 'px';
},
up: function (obj) {
let top = obj.coors.top = (obj.coors.top - obj.step);
obj.node.style.top = top + 'px';
},
right: function (obj) {
let left = obj.coors.left = (obj.coors.left + obj.step);
obj.node.style.left = left + 'px';
}
};
let stepTimeout = 1000;
let running = false;
let timeouts = {};
let blocks = document.querySelectorAll('#toolbox .block');
let workSpace = document.getElementById('workspace');
blocks.forEach(function(block){
block.addEventListener('click', function(){
let color = this.dataset.color;
let workBlock = '<div class="remove-block block ' + color + '"></div>';
workSpace.insertAdjacentHTML('beforeend', workBlock);
mobs.pinky.moveQueue.push( this.textContent.toLowerCase() );
});
});
document.getElementById('run_workspace').addEventListener('click', function () {
running = true;
runCode();
function runCode() {
for (let obj in mobs) { // mobile objects may be multiple
// Inside the loop, obj == mobs each key name. Here it's == "pinky"
let i = 0;
let pinky = mobs[obj];
localRun();
function localRun() {
let direction = pinky.moveQueue[i]; // getting direction key by array index.
move[direction](pinky); // calling the required function from storage.
if (pinky.moveQueue[++i] && running ) {
// self-calling again, if moveQueue has next element.
// At the same time increasing i by +1 ( ++i )
timeouts[obj] = setTimeout(localRun, stepTimeout);
}
}
}
}
});
document.getElementById("clear_workspace").addEventListener('click', function () {
workSpace.textContent = "";
});
workSpace.addEventListener('click', function (e) {
if( e.target.classList.contains('remove-block') ){
e.target.remove();
}
});
html,
body {
margin: 0;
padding: 0;
}
#workspace {
display: flex;
height: 100px;
padding: 10px;
background: black;
}
#toolbox {
display: flex;
padding: 10px;
width: 300px;
}
#output_section {
height: 500px;
width: 500px;
border: solid black;
margin: 10px;
position: relative;
}
#moving_square {
position: absolute;
top: 400px;
left: 400px;
width: 100px;
height: 100px;
background: pink;
}
.block {
height: 100px;
width: 100px;
}
.red {
background: red;
}
.blue {
background: cyan;
}
.green {
background: green;
}
.grey {
background: #ccc;
}
<div id="workspace"></div>
<div id="workspace-menu">
<button id="run_workspace">Run</button>
<button id="clear_workspace">Clear</button>
</div>
<div id="toolbox" class="grey">
<div data-color="red" class="block red">Left</div>
<div data-color="blue" class="block blue">Up</div>
<div data-color="green" class="block green">Right</div>
</div>
<div id="output_section">
<div id="moving_square"></div>
</div>

Why is putting style inside if statement not working?

I'm trying to do a basic toggle clicking with js... I have this
<div id="box"></div>
<button id="btn"></button>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
js:
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.style.left === '50px') {
box.style.left = '200px';
}
if (box.style.left === '200px') {
box.style.left = '50px';
}
});
I looked it up and this seems to be the method everyone uses for toggle clicking with pure js so I have no idea why it's not working for me, any ideas?
You should use the window.getComputedStyle instead (This way you will get the actual value of the style that applied to that element, and not just what's on the style attribute)..
You are missing an else there (otherwise you will always get the two if and nothing will change)
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (window.getComputedStyle(box).left === '50px') {
box.style.left = '200px';
} else if (window.getComputedStyle(box).left === '200px') {
box.style.left = '50px';
}
});
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
<div id="box"></div>
<button id="btn"></button>
#Dekel's answer already explains what was wrong with your code. However, you should work with classes instead. Not only is this way faster than retrieving window.getComputedStyle, it's also much easier
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var box = document.getElementById('box');
box.classList.toggle('left-50');
box.classList.toggle('left-200');
});
.left-50 {
left: 50px;
}
.left-200 {
left: 200px;
}
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
}
<div id="box" class="left-50"></div>
<button id="btn">bt</button>
Better use offset. Beside you are making a kind of toggle operation in here. Meanwhile, I modified your script to make it work:
<div id="box"></div>
<input type="button" id="btn" value=" Try it ">
<style>
#box {
background: black;
width: 50px;
height: 50px;
position: absolute;
left: 50px;
}
</style>
<script>
var btn = document.getElementById('btn');
var box = document.getElementById('box');
btn.addEventListener('click', function(){
if (box.offsetLeft == 50 ) {
box.style.left = 200 ;
}
else if (box.offsetLeft == 200 ) {
box.style.left = 50;
}
});
</script>

I am trying to display a div on click of a checkbox

I need to display an image and some info about the item when a checkbox is clicked. For some reason nothing is happening and I have been tweaking this for a while with no response whatsoever.
Here is my javascript:
<script type = "text/javascript">
function displayOnChecked(var checkboxID, var id) {
if(document.getElementById(checkboxID)) {
document.getElementById(id).style.display = "block";
} else {
document.getElementById(id).style.display = "none";
}
}
</script>
In the stylesheet I have it on display: none;
Here is one of my invocations:
<input type="checkbox" name="purchasedItem" id = "item" onclick="displayOnChecked('item', 'itemInfo');">
No need for the var keyword in the arguments list of displayOnChecked, just have the variable names alone.
If you look in your console, you should be getting an error: Uncaught SyntaxError: Unexpected token var
You don't intialize variables as function arguments:
function displayOnChecked(var checkboxID, var id)
should be
unction displayOnChecked(checkboxID, id)
You can achieve this, just using the CSS pseudo-element :checked:
.checkmeout {
display: none;
position: absolute;
top: 12px;
left: 150px;
width: 400px;
height: 100px;
padding: 12px;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
}
.checkmeout img {
display: block;
width: 200px;
height: 50px;
background-color: rgb(0,0,255);
}
.checkme:checked ~ .checkmeout {
display:block;
}
<form>
<input type="checkbox" name="checkme" class="checkme" /> Check Me
<div class="checkmeout">
<img src="" alt="Check Me Out Image" />
<p>Check Me Out Text Description</p>
</div>
</form>

Categories

Resources