Why is putting style inside if statement not working? - javascript

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>

Related

Continually fade background box with each click of the fade button

Brand new to coding. Trying to get "fade" button to fade a little more each time I click it.
I have used this code to grow and shrink the box and I was trying to do the same thing for the opacity:
document.getElementById("growbutton").addEventListener("click", function() {
var growVariable = 10;
var newValueHeight = parseInt(document.getElementById("box").style.height)
document.getElementById("box").style.height = newValueHeight + growVariable + "px";
var newValueWidth = parseInt(document.getElementById("box").style.width)
document.getElementById("box").style.width = newValueWidth + growVariable + "px";
});
document.getElementById("fadebutton").addEventListener("click", function() {
var opVariable = .2;
var newOpValue = parseInt(document.getElementById("box").style.opacity)
document.getElementById("box").style.opacity = newValueHeight - opVariable;
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
Can you tell me what I'm missing so the box fades .2 with each click?
Your existing code produces the error: Uncaught ReferenceError: newValueHeight is not defined. There were a few issues:
You were referencing newValueHeight instead of newOpValue by accident.
parseInt() will return an integer, i.e., if the current opacity is 0.8, parseInt(0.8) returns 1. You need to use parseFloat() to get a floating point back.
Initially, style.opacity is undefined because it has not been set yet. You should use opValue = ... || 1 so that it defaults to 1 if not yet set.
let box = document.getElementById('box'),
fadeBtn = document.getElementById('fadebutton'),
growBtn = document.getElementById('growbutton');
growBtn.addEventListener('click', function() {
let growVariable = 10,
boxHeight = parseInt(box.style.height),
boxWidth = parseInt(box.style.width);
box.style.height = boxHeight + growVariable + "px",
box.style.width = boxWidth + growVariable + "px";
});
fadeBtn.addEventListener("click", function() {
let opVariable = .2,
opValue = parseFloat(box.style.opacity) || 1;
box.style.opacity = opValue - opVariable;
});
<div id="box" style="height: 100px; max-height: 600px; min-height: 5px; width:100px; max-width: 600px; min-width: 5px; background-color:orange; margin:1rem"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>
You need to use parseFloat when dealing with non-whole numbers or with decimal points as parseInt returns an integer or a whole number
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
document.getElementById("fadebutton").addEventListener("click", function() {
//var opVariable = .2;
let box = document.getElementById("box")
let currentOpacity = parseFloat(box.style.opacity)
box.style.opacity = currentOpacity - .2
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px;opacity:1"></div>
<button id="fadebutton">
Fade
</button>
If you just want to fade the image onclick, you can simply decrement the style.opacity property. Something like this:
const box = document.querySelector('#box');
document.addEventListener('click', e => {
if (e.target.id === 'fadebutton') {
if (box.style.opacity > 0) {
box.style.opacity -= .2;
}
}
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px; opacity: 1"></div>
<button id="fadebutton">Fade</button>

JavaScript doesn't write on the page

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");
}

how to make a div grow to cover a paragraph in javascript with transition?

I am trying to make a transition with a div that should grow and overlap a text.
Here are my codes
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if(box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
}
else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
postion: fixed;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
At the moment, on the click of the button, both the button and the paragraph para move down, I want them to be fixed and I want the div, #box to cover the para but its not working. I tried putting it to fixed but doesnt work. And on the click on the button again, it should reveal the text again.
If you use position: fixed;, you should manually set the top property.
To make a div overlay some text, use z-index
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if (box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
} else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#mybutt {
position: fixed;
top: 120px;
}
#box {
background: red;
position: fixed;
height: 50px;
width: 50px;
z-index: 2;
}
#para {
position: fixed;
z-index: 1;
top: 60px;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
Firstly, you spelled "position" wrong for #para. Change it to:
#para {
position: absolute;
top: 10%;
}
This will keep the paragraph positioned in one spot; it won't move.
Fixed will work, although you might want to use 'absolute' instead if you want it to anchored to it's parent instead of the window itself.
Also, 'position' is misspelled; not sure if it is in your testing code.
The 'top' property has to be set for the element to know where to anchor itself, the 'position' property is what to anchor to.
HTML
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
</div>
<button id="mybutt">click</button>
CSS
<style>
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
position: absolute;
top:70;
}
</style>
*You also might want to move '#para' outside '#parentdiv', but it depends what you'll trying to ultimately do, it does work inside too.
Added:
To include an alert at 75px, you have to use a function that gives you more granular control(as far as I know at least). This is one solution:
<script>
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
var intHeight = $("#box").css("height").split("p")[0];
function transitionfunction() {
if(intHeight < 100) {
intHeight++;
$("#box").css("height", intHeight + "px");
if (intHeight===76)
alert("75px!")
requestAnimationFrame(transitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", revtransitionfunction);
mybutt.removeEventListener("click", transitionfunction);
}
function revtransitionfunction() {
if(intHeight >= 50) {
intHeight--;
$("#box").css("height", intHeight + "px");
if (intHeight===74)
alert("75px!")
requestAnimationFrame(revtransitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", transitionfunction);
mybutt.removeEventListener("click", revtransitionfunction);
}

event.stopPropagation() not working in firefox javascript

event.stopPropagation() Does not work as it should be in the Firefox browser, but in Google Chrome or Internet Explorer or opera it is works well, the problem in Firefox browser when Clicking on btn_1 should show message btn_1 not show div1 .Is there another function or a solution to this problem? Gratefully
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Hello!</title>
<style type="text/css">
<!-- body {
text-align: center;
}
#main {
position: absolute;
height: 400px;
width: 600px;
border: 1px solid black;
left: 400px;
}
#btn1 {
position: absolute;
height: 30px;
width: 200px;
border: 1px solid black;
left: 500px;
top: 420px;
}
#btn2 {
position: absolute;
height: 30px;
width: 200px;
border: 1px solid black;
left: 800px;
top: 420px;
}
#div1 {
height: 100px;
width: 100%;
background-color: #FF3399;
}
#div2 {
height: 100px;
width: 100%;
background-color: #99FF00;
position:relative;
}
#div3 {
height: 100px;
width: 100%;
background-color: #00CC99;
}
-->
</style>
<script>
function addElement2() {
var element = document.getElementById("main");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var newContent = 0;
for (var i = 0; i <= 2; i++) {
newContent = newContent + 1;
var divname = "div" + newContent;
var divname2 = "div" + newContent;
var Content_text = "newContent" + newContent;
divname = document.createElement("div");
document.getElementById("main").appendChild(divname);
Content_text = document.createTextNode(divname2);
divname.id = divname2.toString().trim();
divname.appendChild(Content_text);
var btn = document.createElement("BUTTON")
document.getElementById(divname2.toString().trim()).appendChild(btn);
var btn_id= "btn_" + newContent;
btn.id =btn_id;
var Content_text2 = document.createTextNode("btn_" + newContent);
btn.appendChild(Content_text2);
btn.onclick = function(){delete_cooke1(this) ;} ;
divname.onclick = function(){go_to(this) ;} ;
}
}
function delete_cooke1(mmm){
event.stopPropagation();
var str = mmm.id.toString() ;
alert(str);
return;
}
function go_to(mmm){
var str = mmm.id.toString() ;
alert(str);
return;
}
</script>
</head>
<body>
<div id="main"></div>
<button id="btn1" onclick="addElement2()">1-Create 3 divs</button>
</body>
</html>
You will need to explicitly pass the event object into your callback function. For example:
document.querySelector("body").onclick = function(e){
console.log(e); // the current event
};
You are taking advantage of the fact that Chrome exposes the current event as a global on the window (i.e. window.event or just event). Firefox does not do this -- and other browsers are affected as well.
Calling event.preventDefault() worked in my case.
I have a react app and I was calling event.stopPropagation() inside the onclick handler of a material-ui checkbox like so:
<StyledCheckBox
icon={<CircleUnchecked />}
checkedIcon={<CircleChecked />}
checked={shipmentEditIds.includes(id)}
onClick={event => {
event.stopPropagation();
setShipmentEditIds({ id });
}}
/>
For some reason, only in firefox browser, this wasn't stopping the event from propagating.
Once I added event.preventDefault() to the onClick handler it fixed the problem.
I know this doesn't provide an answer as to why stopPropagation() isn't working in Firebox browser but just sharing what worked for me.
Pass event from onclick:
btn.onclick = function(){delete_cooke1(this, event) ;} ;
And use event argument with stopPropagation()
function delete_cooke1(mmm, e){
e.stopPropagation();
e.preventDefault(); // Add this line also
var str = mmm.id.toString() ;
alert(str);
return;
}

How to toggle (hide / show) sidebar div using jQuery

I have 2 <div>s with ids A and B. div A has a fixed width, which is taken as a sidebar.
The layout looks like diagram below:
The styling is like below:
html, body {
margin: 0;
padding: 0;
border: 0;
}
#A, #B {
position: absolute;
}
#A {
top: 0px;
width: 200px;
bottom: 0px;
}
#B {
top: 0px;
left: 200px;
right: 0;
bottom: 0px;
}
I have <a id="toggle">toggle</a> which acts as a toggle button. On the toggle button click, the sidebar may hide to the left and div B should stretch to fill the empty space. On second click, the sidebar may reappear to the previous position and div B should shrink back to the previous width.
How can I get this done using jQuery?
$('button').toggle(
function() {
$('#B').css('left', '0')
}, function() {
$('#B').css('left', '200px')
})
Check working example at http://jsfiddle.net/hThGb/1/
You can also see any animated version at http://jsfiddle.net/hThGb/2/
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
You can visit w3school for the solution on this the link is here and there is another example also available that might surely help,
Take a look
The following will work with new versions of jQuery.
$(window).on('load', function(){
var toggle = false;
$('button').click(function() {
toggle = !toggle;
if(toggle){
$('#B').animate({left: 0});
}
else{
$('#B').animate({left: 200});
}
});
});
Using Javascript
var side = document.querySelector("#side");
var main = document.querySelector("#main");
var togg = document.querySelector("#toogle");
var width = window.innerWidth;
window.document.addEventListener("click", function() {
if (side.clientWidth == 0) {
// alert(side.clientWidth);
side.style.width = "200px";
main.style.marginLeft = "200px";
main.style.width = (width - 200) + "px";
togg.innerHTML = "Min";
} else {
// alert(side.clientWidth);
side.style.width = "0";
main.style.marginLeft = "0";
main.style.width = width + "px";
togg.innerHTML = "Max";
}
}, false);
button {
width: 100px;
position: relative;
display: block;
}
div {
position: absolute;
left: 0;
border: 3px solid #73AD21;
display: inline-block;
transition: 0.5s;
}
#side {
left: 0;
width: 0px;
background-color: red;
}
#main {
width: 100%;
background-color: white;
}
<button id="toogle">Max</button>
<div id="side">Sidebar</div>
<div id="main">Main</div>
$('#toggle').click(function() {
$('#B').toggleClass('extended-panel');
$('#A').toggle(/** specify a time here for an animation */);
});
and in the CSS:
.extended-panel {
left: 0px !important;
}
$(document).ready(function () {
$(".trigger").click(function () {
$("#sidebar").toggle("fast");
$("#sidebar").toggleClass("active");
return false;
});
});
<div>
<a class="trigger" href="#">
<img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
</a>
</div>
<div id="sidebar">
</div>
Instead #sidebar give the id of ur div.
This help to hide and show the sidebar, and the content take place of the empty space left by the sidebar.
<div id="A">Sidebar</div>
<div id="B"><button>toggle</button>
Content here: Bla, bla, bla
</div>
//Toggle Hide/Show sidebar slowy
$(document).ready(function(){
$('#B').click(function(e) {
e.preventDefault();
$('#A').toggle('slow');
$('#B').toggleClass('extended-panel');
});
});
html, body {
margin: 0;
padding: 0;
border: 0;
}
#A, #B {
position: absolute;
}
#A {
top: 0px;
width: 200px;
bottom: 0px;
background:orange;
}
#B {
top: 0px;
left: 200px;
right: 0;
bottom: 0px;
background:green;
}
/* makes the content take place of the SIDEBAR
which is empty when is hided */
.extended-panel {
left: 0px !important;
}

Categories

Resources