Click function not updating global variable - javascript

I want to change the global variable x when the user clicks a button. However, it is not being changed. I have researched this on Google, and it seems like I'm doing everything right.
testing.html:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="testing.js"></script>
<style>
div {
border: solid 1px orange;
height: 50px;
width: 50px;
font-size: 45px;
text-align: center;
}
</style>
</head>
<body>
<button>Click here</button>
<div><div/>
</body>
</html>
tesing.js:
var x;
$(document).ready(function() {
x = 0;
$("div").text(x);
$("button").on("click", function() {
x = 1;
});
$("div").text(x); //the div stays at "0" even after I click the button
});
If I put $("div").text(x); inside the click function after x = 1, then it works, but I need it to change x in the global scope, not the local one, so I can use it in other JS functions in the html file.
EDIT:
The reason I'm trying to test x outside of the click function is because I'll need to use that updated x in a document ready function inside the html file, so I can't do everything inside the click function. Maybe what I'm trying to do isn't possible? But I thought that's why global variables exist?

You have to update the HTML inside the click handler. $("div").text(x); assigns the value of x as the text of $("div"), it does not bind the text to that variable, so the text must be updated when the value of the variable is updated.
var x = 0;
$("div").text(x);
$("button").on("click", function() {
$("div").text(++x);
});
div {
border: solid 1px orange;
padding: 10px 15px;
display: inline-block;
font-size: 45px;
text-align: center;
}
div::before {
content: "x = ";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button>Increment</button><br>
<div></div>

Related

Why doesn't this code display the button after I hide it?

When I run this JavaScript code, button2 doesn't get displayed again. I'm not sure why this is happening. I am trying to use this in a game I am creating. I searched this up on Google multiple times and couldn't find an answer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2"></button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "auto";
}
</script>
</html>
A good way to handle this and provide more reusable code is to use <element>.classList.remove() and <element>.classList.add() to set or unset a hidden class. This can also be useful for toggling with <element>.classList.toggle().
This has the added advantage of being able to set your default display style in the CSS rather than burying it in the javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
/* allows setting preferred display in CSS */
display: block;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn1" onclick="toggleBtn2()">
Toggle Button 2
</button>
<button class="btn2 hidden" id="btn2">Button 2</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.classList.remove("hidden");
}
function toggleBtn2() {
btn2.classList.toggle("hidden");
}
</script>
</html>
There is no auto display is CSS. As tarkh mentioned in his answer, display block would insert the new button below the initial button, and other display options would have other behaviors. But the display property does not have a value auto.
This may be my opinion, but I think modern websites shouldn't use the onclick function for events. We should separate our HTML, JS and CSS. This helps with reusability. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
So I would create a solution that uses an event handler in the Javascript. Something like:
window.onload = function(){
const btn2 = document.getElementById("btn2");
const btn1 = document.getElementsByClassName("btn1");
for(let i = 0; i < btn1.length; i++) {
btn1[i].addEventListener('click', function(){
btn2.style.display = "block";
})
}
}
Maybe btn2.style.display = "block";?
Or, as #charlietfl added, btn2.style.display = "inline"; since that is what browser default is for a button
display: block means that the element is displayed as a block, as
paragraphs and headers have always been. A block has some whitespace
above and below it and tolerates no HTML elements next to it, except
when ordered otherwise (by adding a float declaration to another
element, for instance).
display: inline means that the element is displayed inline, inside the
current block on the same line. Only when it's between two blocks does
the element form an 'anonymous block', that however has the smallest
possible width.
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">new button here</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "block";
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">Button 2</button>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "inline";
}
</script>
</body>
</html>
Use display = inline or block instead of auto.
Add some text content to button 2 like this:
<button class="btn2" id="btn2">Button 2</button>
CSS: "display: auto;"?
display does not have an auto attribute.
you can try "inline" or "block".
'''
function showBtn2() {
btn2.style.display = "inline";
}
'''
Try using
btn2.style.display = "block";
for your script because css display doesn't have that kind of attribute you
you can read it more here : more
you'll see there's no such thing as display:auto

How to set the window's Y middle to element's Y middle?

I have created a button which should shift the window's Y to "BOX - 5" div's Y middle through onclick. So in other words I want to set the "Box - 5" div in the middle of the window. I have tried many methods using window.scrollTo and using elements.innerHeight/2, but I still cannot center the element to the middle of the window/screen. Please Help.
I wish to only use Javascript, but if its not possible with it then I would accept jQuery script.
index.html:
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll("#box")[4];
/*
NEED HELP HERE
*/
}
body {
margin: 0;
}
#box {
position: relative;
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
Updated your snippet as below. You can use DOM element property offsetTop to check its Y position and use window.scroll to scroll the view to that element. Another sidenote, it's better to not assign the same id to multiple elements, so I change the id property to class and added identifier _{index} for the class name.
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.className += "box _" + (y+1);
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll(".box._5")[0];
if (box_5) {
// scroll the window view to the element
window.scroll({
top: box_5.offsetTop,
behavior: 'smooth',
})
}
}
body {
margin: 0;
}
.box {
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>

How do I increment the rotation property of this box one degree at a time?

I've wrote the following code in an attempt to rotate the box identified as "player" by one single degree to the left every time I strike the left arrow key on the key board. I tried setting the initial value of the degree by declaring a variable called "numberD" and setting it to 0. Then I incremented this variable with the numberD++; statement. Then I tried to attach the value from numberD into the statement following it by inserting it into the rotate degrees statement.
Im not getting any syntax errors however the box is not moving, i know the keystroke is working because i attached a console log to fire every time i strike the left key. i think my issue is that when i declare the numberD it doesn't know to connect it the the transform property of the CSS element player.
Any thoughts would be appreciated. Thx!
Also heres a CODEPEN LINK for this example.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #1f1f2e;
margin: 0px;
padding: 0px;
}
#arena {
background-color:black;
margin: 0px;
padding: 0px;
width: 500px;
height: 500px;
}
#player {
background-color: white;
width: 10px;
height: 10px;
position: relative;
top:50%;
left:50%;
transform:rotate(0deg);
}
</style>
<script>
document.addEventListener("keydown", keyBoardInput);
function keyBoardInput() {
var i = event.keyCode;
if (i == 37) {
numberD = 0;
numberD ++;
document.getElementById('player').style.transform = "rotate(" +
numberD +"deg)";
console.log('fired');
}
}
</script>
<body>
<div id="arena">
<div id="player"></div>
</div>
</body>
</head>
</html>
Every time the function is called, you reset the value for the rotation: numberD = 0;
To fix this you have to declare the variable outside of the function. You could do this by defining it as a document wide variable: document.numberD = 0;
Here is the code:
document.addEventListener("keydown", keyBoardInput);
document.numberD = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 37) {
document.numberD++;
document.getElementById('player').style.transform = "rotate(" + document.numberD + "deg)";
console.log('fired');
}
}
And here is a working example.

Polymer paper-ripple programatically trigger downAction at given x,y coordinates

I am trying to trigger a ripple animation programatically at a given x,y coordinate, but I can't seem to get it right.
I have found a few helpful answers like these:
paper-ripple mouseDown event handler downAction Override
Polymer paper ripple
How to trigger Polymer paper ripple animation by API code?
I didn't find a way to apply the first two since at this stage I'm simply using a paper-ripple element without creating a custom element. The first answer is somewhat helpful, but I'd like to control the x,y coordinates of the ripple.
Here's how I tried to do this, using Jacek's snippet fro the 3rd answer:
<!DOCTYPE html>
<html>
<head>
<base href="https://polygit.org">
<script src="/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="/components/polymer/polymer.html">
<link rel="import" href="/components/paper-ripple/paper-ripple.html">
<style>
.card {
position: relative;
display: inline-block;
width: 300px;
height: 240px;
vertical-align: top;
background-color: #fff;
box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24);
}
</style>
</head>
<body>
<template id="demo" is="dom-bind">
<div class="card">
<paper-ripple recenters></paper-ripple>
</div>
</template>
</body>
<script>
var demo = document.querySelector('#demo');
var mouseDown = new MouseEvent("mouseDown",{"clientX":30,"clientY":30,"screenX":30,"screenY":30});
var mouseUp = new MouseEvent("mouseUp",{"clientX":30,"clientY":30,"screenX":30,"screenY":30});
demo.addEventListener('dom-change', function() {
setInterval(triggerRippleDown, 1000);
setInterval(triggerRippleUp, 1200);
});
var triggerRippleDown = function() {
var paperRipple = document.querySelector('paper-ripple');
paperRipple.downAction(mouseDown);
}
var triggerRippleUp = function() {
var paperRipple = document.querySelector('paper-ripple');
paperRipple.upAction(mouseUp);
}
</script>
</html>
This passing x,y properties via mouse event doesn't seem to work, although this part of the documentation suggests so:
downAction: function(e) {
this.$.ripple.downAction({x: e.x, y: e.y});
}
Any hints on what's the recommended way to trigger a ripple programatically outside of a custom component ?
I dont know the recommended way but I have simple solution.
My solution is not to pass mouse event but object with x,y. look in this example:
<!DOCTYPE html>
<html>
<head>
<base href="https://polygit.org">
<script src="/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="/components/polymer/polymer.html">
<link rel="import" href="/components/paper-ripple/paper-ripple.html">
<style>
.card {
position: relative;
display: inline-block;
width: 300px;
height: 240px;
vertical-align: top;
background-color: #fff;
box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24);
}
</style>
</head>
<body>
<template id="demo" is="dom-bind">
<div class="card">
<paper-ripple recenters></paper-ripple>
</div>
</template>
</body>
<script>
var demo = document.querySelector('#demo');
demo.addEventListener('dom-change', function() {
setInterval(triggerRippleDown, 1000);
setInterval(triggerRippleUp, 1200);
});
var triggerRippleDown = function() {
var paperRipple = document.querySelector('paper-ripple');
paperRipple.downAction({detail:{x:30,y:120}});
console.log(paperRipple.xStart);
}
var triggerRippleUp = function() {
var paperRipple = document.querySelector('paper-ripple');
paperRipple.upAction();
}
</script>
</html>
I use this and dont mouseEvent
paperRipple.downAction({detail:{x:30,y:120}});
paperRipple.upAction();

Removing dynamic divs made with JS on click

My code knowledge is very limited, comes from CodeHS and Codecademy so bear with me.
So I am trying to make a list of numbers, that can be deleted on click. So far so good with the number list, but I still can't figure how to remove them when I click the div box.
I know theres JSFiddle, but I think this is best I could do:
http://www.codecademy.com/rfabrega/codebits/xZ61aJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
color: #000;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
</style>
</head>
<body>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
you have to create a function on click that deletes the target div tag:
so in your code, after creating the div element. insert this:
divTag.onclick = function(){this.parentNode.removeChild(this)};
$(document).ready(function(){
$('p').hide();
$("body").on("click",".divContainer",function(){
$(this).remove();
});
});

Categories

Resources