I was wondering why the button doesn't change to the other function where the button will turn red when clicking it a second time.
My goal is to have one button that will change function depending on whether you pressed it once
<!DOCTYPE html>
<html>
<head>
<style>
#hello {
padding: 30px 60px;
background-color: #4db8ff;
width: 100px;
text-align: center;
margin-left: auto;
margin-right: auto;
cursor: pointer;
color: white;
font-family: arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="hello" onclick="button()">START</div>
</body>
<script>
var x = true;
if(x == true) {
function button() {
x = false;
alert("once");
}
}
if(x == false) {
function button() {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}
</script>
</html>
You're conditionally creating, on page load, one of two possible function definitions. The second definition won't replace the first just because you've reassigned the boolean flag at some point.
Create a single function that checks the status of x internally:
function button() {
if(x) { // Comparing against true is redundant
x = false;
alert("once");
} else {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}
Your function button() is only being defined once. You can not define a function based on a condition, it will be defined as soon as its surrounding code is executed. Thus, you need to place your if statements inside the function.
<!DOCTYPE html>
<html>
<head>
<style>
#hello {
padding: 30px 60px;
background-color: #4db8ff;
width: 100px;
text-align: center;
margin-left: auto;
margin-right: auto;
cursor: pointer;
color: white;
font-family: arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="hello" onclick="button()">START</div>
</body>
<script>
var x = true;
function button(){
if(x) {
x = false;
alert("once");
} else {
alert("twice");
document.getElementById("hello").style.background = "#ff3333";
}
}
</script>
</html>
Related
I don't want a button I want a timer instead that counts down 5 seconds then the javascript function executes on page load
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/app.min.css" />
<title>
Test
</title>
</head>
<body>
<!-- I don't want a button I want a timer instead that counts down 5 seconds then the javascript function executes -->
<button onclick="myFunction()">Click Me</button>
<div id="myDIV", class="myDIV">
Initializing Hide
</div>
<div id="myDIVS", class="myDIVS">
Hide Successful
</div>
<script type="text/javascript">
function myFunction(){
var target = document.getElementById("myDIV");
var show = document.getElementById("myDIVS");
if(target.style.display = "none"){
// target.style.display = "block";
show.style.display = "block";
}else{
show.style.display = "block";
}
}
</script>
</body>
<style>
.myDIV{
background-color: aqua;
margin: 30px;
padding: 50px 30px;
/* display: none; */
}
.myDIVS{
background-color: green;
margin: 30px;
padding: 50px 30px;
display: none;
}
</style>```
You need to use setTimeout(). Just put the onClick code inside this, also I have corrected the = vs. == mistake.
function myFunction() {
var target = document.getElementById("myDIV");
var show = document.getElementById("myDIVS");
if (target.style.display == "none") {
target.style.display = "block";
show.style.display = "none";
} else {
target.style.display = "none";
show.style.display = "block";
}
}
setTimeout(myFunction, 5000);
.myDIV {
background-color: aqua;
margin: 30px;
padding: 50px 30px;
/* display: none; */
}
.myDIVS {
background-color: green;
margin: 30px;
padding: 50px 30px;
display: none;
}
<div id="myDIV" class="myDIV">
Initializing Hide
</div>
<div id="myDIVS" class="myDIVS">
Hide Successful
</div>
Wait for five seconds and see?
I am currently practicing using just vanilla JavaScript to program a website. At the moment, I am making a website where clicking on the fingerprint icon triggers an input to show for the user to key in the password. This is the code I have tried, some of which I adapted from https://gomakethings.com/how-to-show-and-hide-elements-with-vanilla-javascript/.
Despite that, I can't make it work. Please can you help fix the code.
Code
var show = function(elem) {
elem.style.display = 'block';
};
var hide = function(elem) {
elem.style.display = 'none';
};
var toggle = function(elem) {
elem.classList.toggle('wash');
};
// Listen for click events
document.addEventListener('click', function(event) {
// Make sure clicked element is our toggle
if (!event.target.classList.contains('wash')) return;
// Prevent default link behavior
event.preventDefault();
// Get the content
var content = document.querySelector(event.target.hash);
if (!content) return;
// Toggle the content
toggle(content);
}, false);
h1 {
font-family: 'Libre Baskerville', serif;
text-align: center;
font-size: 4em;
color: #e0e4ec
}
html {
background: #556c9a
}
.keys {
text-align: center;
}
.fa-fingerprint {
text-align: center;
padding-left: 2%;
padding-right: 2%;
font-size: 3rem;
}
h2 {
position: relative;
text-align: center;
}
.press:hover {
color: yellow;
}
.type {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital#1&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/923b4d30ed.js" crossorigin="anonymous"></script>
<h1>Pineapple</h1>
</head>
<body>
<div class="keys">
<span class="press"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type"><input placeholder="Password"></span>
</div>
</body>
</html>
This would do in regular JS. Target and id and toggle display state.
function myFunction() {
var x = document.getElementById("my");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
h1{
font-family: 'Libre Baskerville', serif;
text-align: center;
font-size: 4em;
color:#e0e4ec
}
html{
background: #556c9a
}
.keys{
text-align:center;
}
.fa-fingerprint{
text-align:center;
padding-left:2%;
padding-right:2%;
font-size:3rem;
}
h2{
position:relative;
text-align:center;
}
.press:hover{
color:yellow;
}
.type{
display:none;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital#1&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/923b4d30ed.js" crossorigin="anonymous"></script>
<h1>Pineapple</h1>
</head>
<body>
<div class="keys">
<span class="press" onclick="myFunction()"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type" id="my"><input placeholder="Password"></span>
</div>
</body>
</html>
It would seem you need to add an onclick() method to your <span> containing the input box you want to show, which once clicked will change the display property from none to block.
You can view the solution here.
In Javascript you can do this in a simple way by just checking the property of block and none.
input type is self closing element you don't need to add </input> at the end.
You need to set the display property to the input type and based on the click event you can toggle on the condition.
document.addEventListener('click', function(event) {
var type = document.getElementById('inputType'); // the type you want to hide/show
if (type.style.display !== 'none') {
type.style.display = 'none';
} else {
type.style.display = 'block';
}
});
h1 {
font-family: 'Libre Baskerville', serif;
text-align: center;
font-size: 4em;
color: #e0e4ec
}
html {
background: #556c9a
}
.keys {
text-align: center;
}
.fa-fingerprint {
text-align: center;
padding-left: 2%;
padding-right: 2%;
font-size: 3rem;
}
h2 {
position: relative;
text-align: center;
}
.press:hover {
color: yellow;
}
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital#1&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/923b4d30ed.js" crossorigin="anonymous"></script>
<h1>Pineapple</h1>
<body>
<div class="keys">
<span class="press"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span id="inputType" style="display:none;"><input placeholder="Password"/></span>
</div>
</body>
You can add an event listener to the .press class to toggle between setting the <input>'s display to none and block.
document.getElementsByClassName('press')[0].addEventListener('click', () => {
var input = document.getElementsByClassName('type')[0];
input.style.display = (input.style.display == 'none') ? 'block' : 'none';
});
h1 {
font-family: 'Libre Baskerville', serif;
text-align: center;
font-size: 4em;
color: #e0e4ec
}
html {
background: #556c9a
}
.keys {
text-align: center;
}
.fa-fingerprint {
text-align: center;
padding-left: 2%;
padding-right: 2%;
font-size: 3rem;
}
h2 {
position: relative;
text-align: center;
}
.press:hover {
color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital#1&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/923b4d30ed.js" crossorigin="anonymous"></script>
<h1>Pineapple</h1>
</head>
<body>
<div class="keys">
<span class="press"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type" style="display: none;"><input placeholder="Password"></span>
</div>
</body>
</html>
could anybody please help me.
I've found this nice countup-script:
https://codepen.io/alemarengo/pen/mOWqwy
Now I would like to call this function multiple times for some other elements on the same site. But with different settings.
start += 0.125;
Set addition from 0.125 to 5.25, for example.
Thank you in advance!
This is one possible approach: instantiate different go functions with different parameters:
var start = {
"counter-1": 7500000,
"counter-2": 1500000
};
var speed = 1000;
$(document).ready(function() {
launch("counter-1", 1.5);
launch("counter-2", 100)
});
function launch(elem, increment) {
var go = goFactory(elem, increment)
go();
setInterval(go, speed);
}
function goFactory(elemId, increment) {
function go() {
$("#" + elemId).html(start[elemId].toFixed(0));
start[elemId] += increment;
}
return go;
}
div {
font-weight: normal;
letter-spacing: 5px;
padding: 6px;
font-size: 1.8em;
font-family: 'Gill Sans';
width: 500px;
text-align: center;
height: auto;
color: #333;
display: block;
margin: 0px auto;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Contatore</title>
</head>
<body>
<div id="counter-1"></div>
<div id="counter-2"></div>
</body>
</html>
I have an error in the console that says:
Uncaught TypeError: Cannot read property 'addEventListener' of null
at (index):14
Here is my code to analyze:
<html>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Quicksand" />
<head>
<script type="text/javascript">
var div = document.getElementById('text'),
randomColor = function(e) {
var hex = Math.floor( Math.random() * 0xFFFFFF ),
res = e.target,
result = "#" + hex.toString(16);
res.style.backgroundColor = result;
res.innerHTML = result;
};
div.addEventListener('mouseover', randomColor);
</script>
<style>
#text{
width: 1000px;
height: 500px;
text-align: center;
font-size: 50px;
font-family: 'Quicksand';
}
body{
text-align: center;
font-family: 'Quicksand';
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
}
</style>
</head>
<body>
<h1>Hover over me to get a random color!</h1>
<div id="text">Hex code</div>
</body>
</html>
I do not understand because it works in JSFIDDLE. Someone please help!
Here's a stack snippet with your code but with the various css, js and html re-arranged.
In your original single html file, you should include your js after the html.
var div = document.getElementById('text'),
randomColor = function(e) {
var hex = Math.floor(Math.random() * 0xFFFFFF),
res = e.target,
result = "#" + hex.toString(16);
res.style.backgroundColor = result;
res.innerHTML = result;
};
div.addEventListener('mouseover', randomColor);
#text {
width: 1000px;
height: 500px;
text-align: center;
font-size: 50px;
font-family: 'Quicksand';
}
body {
text-align: center;
font-family: 'Quicksand';
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
}
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Quicksand" />
<h1>Hover over me to get a random color!</h1>
<div id="text">Hex code</div>
The issue with running the code in browser is that your script is in head tag, so its loading before the DOM. In Jsfiddle the script loads after the DOM. So you have to put the script Just before ending the <body> tag.
Its always better to wrap the code
$(document).ready(function() {
// Handler for .ready() called.
});
or (as suggested upper one is not required any more)
$(function() { ... });
if you use jQuery.
or if in case of pure javascript
document.addEventListener("DOMContentLoaded", function(){
// Handler when the DOM is fully loaded
});
Hope it helps.
Edit: Added code (Just placed the script tag before body ends)
<html>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Quicksand" />
<head>
<style>
#text{
width: 1000px;
height: 500px;
text-align: center;
font-size: 50px;
font-family: 'Quicksand';
}
body{
text-align: center;
font-family: 'Quicksand';
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
}
</style>
</head>
<body>
<h1>Hover over me to get a random color!</h1>
<div id="text">Hex code</div>
<script type="text/javascript">
var div = document.getElementById('text'),
randomColor = function(e) {
var hex = Math.floor( Math.random() * 0xFFFFFF ),
res = e.target,
result = "#" + hex.toString(16);
res.style.backgroundColor = result;
res.innerHTML = result;
};
div.addEventListener('mouseover', randomColor);
</script>
</body>
</html>
I am using pubnub in Javascript (version 3.10.2, which I believe is the latest version as of now). I am making a little game, and alongside the game is a chat div, where I append an li containing my message to a ul. I also have a occupancy counter. I call a function in pubnub.subscribe (presence: displayOccupancy) to display m.occupancy. (sorry if all of this was useless info, first question) The problem is that there is a UUID which I named "test3" which will not timeout from channel "chat" and when I made a button to force that UUID to unsubscribe, it would rejoin automatically after a few seconds. After changing UUIDs and trying this again, they would timeout normally according to my heartbeat and if I made the UUID unsubscribe, it would generate a leave event and that was it. Why does the UUID not leave or timeout from the channel?
EDIT: It's not only the "test3" UUID which lingers. Every time I reopen and test my code from Dreamweaver, the most recent test UUID which I have assigned the previous time I have worked on it "replaces" the UUID which was there before. ("previously" as in from the previous day, not every previous test)
// JavaScript Document
var uuid = PUBNUB.uuid();
var pubnub = PUBNUB.init({
publish_key: 'pub-c-bbf633c9-8ddb-43f7-bf4c-c03215ccd8d8',
subscribe_key: 'sub-c-a1b830fa-d9f5-11e5-a22c-02ee2ddab7fe',
uuid: uuid,
heartbeat: 10
});
var noOfWordsInRow = 0;
//arrays
var consanantArray = ["b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","y"];
var vowelArray = ["a","e","i","o","u"];
var submittedWordsArray = [];
//containers
var lettersDiv = $("div#letterDisplay");
var wordAreaDiv = $("div#wordArea");
var submitDiv = $("div#submitDiv");
var startDiv = $("div#start");
var checkDiv = $("div#checkDiv");
var consanantUl = $("ul#consanantUl");
var vowelUl = $("ul#vowelUl");
var chatUl = $("#chatList");
var confirmWord = $("p#word");
var confirmBtn = $("#confirmBtn");
var error = $("#error");
var noOfPlayers = $("p#noOfPlayers");
//buttons
var startGame = $("button#enterGame");
//input
var chatInput = $("#chatInput");
//other
/**
var consanantOne = $("#firstConsanant");
var consanantTwo = $("#secConsanant");
var consanantThree = $("#thirdConsanant");
var consanantFour = $("#fourthConsanant");
var vowelOne = $("#firstVowel");
var vowelTwo = $("#firstVowel");
var vowelThree = $("#firstVowel");
**/
//pubnub portion of game
$("#testLeave").click(function(){
"use strict";
pubnub.unsubscribe({
channel: "chat"
});
});
//game and chat stuff below
$(window).load(function(){
"use strict";
generateLetters();
});
startGame.click(function(){
"use strict";
//channel
startDiv.css("display", "none");
});
function handleMessage(message){
"use strict";
chatUl.append("<li>"+message+"</li>");
}
function getNoOfUsers(m){
"use strict";
console.log(m);
if(m.action === "join"){
}
else if(m.action === "timeout" || m.action === "leave"){
pub("chat","Player left");
}
noOfPlayers.html(m.occupancy);
}
function playerJoined(){
"use strict";
pub("chat","Player joined");
}
function pub(channel, message){
"use strict";
pubnub.publish({
channel: channel,
message: message
});
}
chatInput.keydown(function(key){
"use strict";
if(key.which === 13){
pub("chat",$("#chatInput").val());
chatInput.val('');
}
});
function generateLetters(){
"use strict";
//vowels
generateRandomLetters(vowelArray, vowelUl, 3);
//consanants
generateRandomLetters(consanantArray, consanantUl, 4);
}
function generateRandomLetters(array, ul, noOfElementsNeeded){ //noOfElementsNeeded = 3 or 4
"use strict";
var usedLetters = [];
var successCount = 0;
while(successCount < noOfElementsNeeded){
var letter = array[Math.floor(Math.random()*array.length)];
var successful = usedLetters.indexOf(letter) === -1; //boolean, checks if the generated letter has been generated before
if(successful){
ul.append("<li><button>"+letter+"</button></li>");
usedLetters.push(letter);
successCount++;
}
}
}
function duplicateLetter(letter){
"use strict";
if((confirmWord.text()).indexOf(letter) > -1){
return true;
}
else {
return false;
}
}
function wordLengthAboveTwo(){
"use strict";
if((confirmWord.text()).length < 3){
return false;
} else {
return true;
}
}
function repeatWords(){
"use strict";
if(submittedWordsArray.indexOf(confirmWord.text()) === -1){
return false;
} else {
return true;
}
}
$(document).on('click', 'ul li button', function(){
"use strict";
var letter = $(this).text();
if(duplicateLetter(letter)){
error.text("You cannot use the same letter twice in a word.");
}
else {
confirmWord.append(letter);
}
});
confirmBtn.click(function(){
"use strict";
if(wordLengthAboveTwo()){
if(!repeatWords()){
if(noOfWordsInRow === 5){
$("#tableOfSubmittedWords").append("<tr><td><p>"+confirmWord.text()+"</p></td></tr>");
noOfWordsInRow++;
noOfWordsInRow = 1;
} else {
$("#tableOfSubmittedWords tr:last").append("<td><p>"+confirmWord.text()+"</p></td>");
noOfWordsInRow++;
}
submittedWordsArray.push(confirmWord.text());
confirmWord.text('');
error.text('');
} else {
error.text("You cannot submit two of the same word.");
}
} else {
error.text("Your word has to be above two letters in length.");
}
});
$(document).on('click', 'p#word', function(){
"use strict";
confirmWord.text('');
});
pubnub.subscribe({
channel: "chat",
presence: getNoOfUsers,
message: handleMessage,
connect: playerJoined
});
#charset "utf-8";
/* CSS Document */
#container {
height: 800px;
position:fixed;
}
div#start {
z-index: 18;
height: 850px;
position: absolute;
background-color: #00FF8C;
width: 100%;
}
#letterDisplay {
position: relative;
background-color: #01ACFF;
height: 200px; /*200px*/
margin: 0 auto;
}
#wordArea {
overflow: scroll;
height: 400px;
width: 100%;
text-align: center;
}
#submitDiv {
background-color: #01ACFF;
height: 250px;
margin: 0 auto;
}
#chatDiv {
position: fixed;
height: 200px;
z-index: 2;
}
ul#chatList li, ul#listOfUsers li{
display: list-item !important;
text-align: left;
}
table {
width: 100%;
height: 100%;
table-layout: fixed;
}
table tr {
width: 100%;
}
table tr td {
size: auto;
}
table tr td p{
font: 25px/1 "Comic Sans MS", Verdana, sans-serif;
text-transform: uppercase;
}
#confirmBtn {
height: 75px;
width: 200px;
}
#checkDiv {
padding-top: 25px;
text-align: center;
size: auto;
}
p#word {
font: 30px/1 "Comic Sans MS", Verdana, sans-serif;
text-transform: uppercase;
}
p#word:hover {
color: #E74C3C;
cursor: pointer;
}
p#error {
color: #E74C3C;
transition: all 0.1s;
-moz-transition: all 0.1s;
-webkit-transition: all 0.1s;
}
div ul li p {
font: 25px/1 "Comic Sans MS", Verdana, sans-serif;
text-transform: uppercase;
}
button {
font: 36px/1 "Comic Sans MS", Verdana, sans-serif;
color: #FFF;
width: 75px;
height: 75px;
text-transform: uppercase;
border-radius: 4px;
background-color: #F2CF66;
text-shadow: 0px -2px #2980B9;
transition: all 0.1s;
-moz-transition: all 0.1s;
-webkit-transition: all 0.1s;
}
button#enterGame {
width: auto;
}
button:hover {
background-color: #E74C3C;
cursor: pointer;
}
button:active {
-webkit-transform: translate(0px,5px);
-moz-transform: translate(0px,5px);
transform: translate(0px,5px);
border-bottom: 1px solid;
}
ul {
list-style-type: none;
text-align: center;
}
ul#consanantUl {
padding-top: 25px;
}
ul#vowelUl {
vertical-align: bottom;
}
ul li{
display: inline;
padding-right: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Word Game</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="container">
<button id="testLeave">clik 2 leev</button>
<div id="start">
Channel Name? <input type="text" id="channelInput">
<button id="enterGame">Join</button>
<p id="startMenuError"></p>
</div>
<div id="presenceDiv">
<p id="noOfPlayers"></p>
</div>
<div id="chatDiv">
<ul id="chatList"></ul>
<input type="text" id="chatInput">
</div>
<div id="letterDisplay">
<ul id="consanantUl"></ul>
<ul id="vowelUl"></ul>
</div>
<div id="wordArea">
<table id="tableOfSubmittedWords">
<tr><td> </td><td> </td><td> </td><td> </td><td> </td></tr>
<tr></tr>
</table>
</div>
<div id="submitDiv">
<div id="checkDiv">
<p id="word"></p>
<button id="confirmBtn">submit</button>
<p id="error"></p>
</div>
</div>
</div>
<!--Jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
<!--Pubnub-->
<script src="https://cdn.pubnub.com/pubnub-3.10.2.js"></script>
<!--My Code-->
<script src="script.js"></script>
</body>
</html>