I'm having trouble with the .innerHTML not working properly - javascript

I cant get the "if" part to work, thus not outputting the text Test0 or Test1 to my "Test" div after I press either of the links. I have checked for any error messages, which there are none of. I also added the changing color to check if it was the event listeners that were the problem, but that worked fine. So my only problem is that I can't get the text to output.
var testEl = document.querySelector("#test");
var menyEl = document.querySelectorAll("a");
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].addEventListener("click", byttInfo);
}
function byttInfo(e) {
if (e.target.className === "ikke_aktiv") {
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].className = "ikke_aktiv";
}
e.target.className = "aktiv"
}
if (e.target.value === 0) {
testEl.innerHTML = "Test0"
} else if (e.target.value === 1) {
testEl.innerHTML = "Test1"
}
}
.innpakning {
width: 80%;
background-color: #708790;
padding: 10px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.loddrett_meny {
display: flex, block;
flex: 1;
padding-top: 6px;
}
.loddrett_meny a {
display: block;
text-align: center;
padding: 12px;
margin: 4px;
color: white;
font-size: 20px;
text-decoration: none;
}
.loddrett_meny a:hover {
background-color: black;
border-radius: 8px;
transition: 0.75s;
}
.aktiv {
background-color: #3cb500;
}
.ikke_aktiv {
background-color: #555;
}
.innhold,
#test {
flex: 6;
height: auto;
background-color: #a6d4a3;
padding-left: 2px;
border-radius: 2px;
margin: 10px;
margin-right: 0px;
font-size: 20px;
}
<div class="innpakning">
<div class="loddrett_meny">
<a class="aktiv" value="0">Kapittel 20</a>
<a class="ikke_aktiv" value="1">Kapittel 20.1</a>
</div>
<div id="test"></div>
</div>

You need to use quotes around values or convert them to Number
if(e.target.value === "0"){
testEl.innerHTML = "Test0"
}else if(Number(e.target.value) === 1){
testEl.innerHTML = "Test1"
}

Adding on what Abdulah Proho said: You can't add the value attribute to a tags, so it's discarded and e.target.value. You may use data attributes for this:
var testEl = document.querySelector("#test");
var menyEl = document.querySelectorAll("a");
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].addEventListener("click", byttInfo);
}
function byttInfo(e) {
if (e.target.className === "ikke_aktiv") {
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].className = "ikke_aktiv";
}
e.target.className = "aktiv"
}
if (e.target.dataset.value === "0") {
testEl.innerHTML = "Test0"
} else if (e.target.dataset.value === "1") {
testEl.innerHTML = "Test1"
}
}
.innpakning {
width: 80%;
background-color: #708790;
padding: 10px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.loddrett_meny {
display: flex, block;
flex: 1;
padding-top: 6px;
}
.loddrett_meny a {
display: block;
text-align: center;
padding: 12px;
margin: 4px;
color: white;
font-size: 20px;
text-decoration: none;
}
.loddrett_meny a:hover {
background-color: black;
border-radius: 8px;
transition: 0.75s;
}
.aktiv {
background-color: #3cb500;
}
.ikke_aktiv {
background-color: #555;
}
.innhold,
#test {
flex: 6;
height: auto;
background-color: #a6d4a3;
padding-left: 2px;
border-radius: 2px;
margin: 10px;
margin-right: 0px;
font-size: 20px;
}
<div class="innpakning">
<div class="loddrett_meny">
<a class="aktiv" data-value="0">Kapittel 20</a>
<a class="ikke_aktiv" data-value="1">Kapittel 20.1</a>
</div>
<div id="test"></div>
</div>

e.target.value is undefined. Due to anchor tags usually not having value attribute. The 'a' elements don't have the data prototype for value.
You should try getting the value using:
e.target.getAttribute('value')
Also while comparing try using:
e.target.getAttribute('value') === '0'
Given the value you get from getAttribute function is a string the value getting compared with should also be a string.

The following works I have tested it as a snippet. Trying copying this entirely and replace it with your js. you need to use the getAttribute method to get the value.
var testEl = document.getElementById("test");;
var menyEl = document.querySelectorAll("a");
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].addEventListener("click", byttInfo);
}
function byttInfo(e) {
if (e.target.className === "ikke_aktiv") {
for (var i = 0; i < menyEl.length; i++) {
menyEl[i].className = "ikke_aktiv";
}
e.target.className = "aktiv"
}
if (e.target.getAttribute("value") === "0"){
testEl.innerText = "Test0"
} else if (e.target.getAttribute("value") === "1") {
testEl.innerText = "Test1"
}
}

Related

Yet again, CSS being problematic again

So basically this is Day 3 (other days, I pretty much did nothing to complete the game) of making a game from HTML5. So I'm making a moves system right now, and I guess I'm doing well? (mainly because I'm not sure if I provided the user with too many moves...) But the thing about it is that, I'm kind of having ANOTHER styling issue.
As you can see in the image: I've CLEARLY set dimensions up for the headerDisplay class/id, but NO, it goes out of the div's dimensions and even goes on the grid. I'm also aiming for the time and moves text to be stuck right on top of the grid, similarly to how the word bank is stuck to the bottom of the grid.
I was also aiming for a button that says refresh right under the word bank, however no matter what I tried, the button would just be right the score text, which looks like this:
When I am aiming for this:
Code:
<div class="content" id="content">
<div class="headerDisplay" id="headerDisplay">
</div>
<div class="gameArea" id="gameArea">
</div>
<div class="wordBank" id="wordBank">
</div>
<div class="bottomMenu" id="bottomMenu">
</div>
</div>
::before,
::after {
box-sizing: border-box;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.content {
display: grid;
grid-template-rows: repeat(3, max-content);
margin-block: 1em;
margin-inline: auto;
width: 512px;
}
.bottomMenu {
font-size: 24px;
text-align: right;
}
.wordBank {
border: 2.5px solid #000;
border-radius: 5px;
display: flex;
font-size: 1.6em;
min-height: 3em;
justify-content: space-between;
padding: 0.25em;
}
.wordBank span:nth-child(even) {
align-self: end;
}
.gameArea {
font-size: 0;
justify-self: center;
max-width: 100%;
}
.cell {
border: 1px solid black;
width: 50px;
font-size: 1rem;
height: 50px;
display: inline-block;
}
.headerDisplay {
width: 100%;
height: 76.8px;
text-align: right;
font-size: 1.6em;
}
let score = 0;
const headerDisplay = document.getElementById("headerDisplay")
const bottomMenu = document.getElementById("bottomMenu");
const wordBank = document.getElementById("wordBank")
const gameArea = document.getElementById("gameArea")
const rows = document.getElementsByClassName("gridRow");
const cells = document.getElementsByClassName("cell");
const words = [ // snippet
"ability",
"able",
"about",
"above",
"abroad",
"absence",
"absent",
"absolute",
"accept",
"accident",
"accord",
"account",
"accuse",
"accustom",
"ache",
"across",
"act"
]
let selectedWords = [];
bottomMenu.innerHTML = "<p>Score: " + score;
bottomMenu.innerHTML += "<button>Refresh"
while (selectedWords.length < 5) {
const selectedWord = words[Math.floor(Math.random() * words.length)];
if (selectedWord.length <= 9) {
wordBank.innerHTML += "<span>" + selectedWord + "</span>"
selectedWords.push(selectedWord);
}
}
let longestWord = selectedWords.reduce((a, b) => a.length < b.length ? b : a, "")
let charCount = longestWord.length
var moves = charCount * 5
headerDisplay.innerHTML += "<p>Time: "
headerDisplay.innerHTML += "<p>Moves: " + moves
function makeRows(rowNum) {
for (let r = 0; r < rowNum; r++) {
let row = document.createElement("div");
gameArea.appendChild(row).className = "gridRow";
}
}
function makeColumns(cellNum) {
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < cellNum; j++) {
let newCell = document.createElement("div");
rows[j].appendChild(newCell).className = "cell";
}
}
}
function defaultGrid() {
makeRows(charCount);
makeColumns(charCount);
}
defaultGrid();
To fix header you need to set its height to fit content, so it will be over your grid even if you change it later:
.headerDisplay {
width: 100%;
height: content-fit; /* previous: 76.8px */
text-align: right;
font-size: 1.6em;
}
And to fix bottom menu you need to add flexbox:
.bottomMenu {
font-size: 24px;
text-align: right;
display: flex; /* new */
flex-direction: row-reverse; /* new */
justify-content: space-between; /* new */
align-items: center; /* new */
}
For the button, you could try this:
button {
position: relative;
right: 400px;
bottom: 50px;
transform: scale(2,2)
}

First time deploying Chrome extension - Uncaught TypeError: Cannot read properties of null (reading 'length')

I am trying to deploy my first javascript application, which is a Chrome extension.
This simply generates random passwords and stores it with the url of current active tab.
App runs fine on local but after deploying it to Chrome, I got this error:
Uncaught TypeError: Cannot read properties of null (reading 'length')
index.js:65 (anonymous function)
I am a beginner, so any kind of criticism about my code is highly appreciated.
Thank you so much.
function render() {
*line65* **if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
Here is the full index.js file:
var characters = [];
for (var i=32; i<127; i++)
characters.push(String.fromCharCode(i));
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '<') {
characters.splice(i, 1);
i--;
}
}
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '>') {
characters.splice(i, 1);
i--;
}
}
let pw1El = document.getElementById("pw1-el")
let pw1 = ""
let passwords = []
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
let links = []
links = JSON.parse(localStorage.getItem("savedLinks"))
render()
document.getElementById("char-count-el").value = 20
document.getElementById("gen-btn").addEventListener("click", function() {
var charCount = document.getElementById("char-count-el").value
pw1 = ""
for(let i = 0; i < charCount; i++) {
let randomIndex = Math.floor(Math.random() * characters.length)
pw1 += (characters[randomIndex])
}
pw1El.textContent = pw1
})
document.getElementById("save-btn").addEventListener("click", function() {
passwords.push(pw1El.innerText)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
links.push(tabs[0].url)
})
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
function render() {
**if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
document.getElementById("clear-btn").addEventListener("click", function() {
passwords = []
links = []
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
document.getElementById("copy-btn").addEventListener("click", function() {
var input = document.getElementById("pw1-el").textContent;
navigator.clipboard.writeText(input);
alert("Copied Text: " + input);
})
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Generate a</br>random password</h1>
<p>Never use an unsecure password again.</p>
<hr>
<div>
<label for="char-count-el">Character Count:</label>
<input type="number" id="char-count-el">
<button id="gen-btn"><span>Generate password</span></button>
</div>
<div>
<label>Your Password:</label>
<div class="pw-container">
<span class="password-line" id="pw1-el">...</span>
<button class="side-btn" id="save-btn">SAVE</button>
<button class="side-btn" id="copy-btn">COPY</button>
</div>
</div>
<div id="saved-passwords-container">
<hr>
<label>Saved Passwords:</label>
<div class="pw-container">
<div id="passwords-el">...</div>
<button class="side-btn" id="clear-btn">CLEAR</button>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
index.css
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #ffffff;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
h1::first-line {
color: white;
}
h1 {
color: #00ffaa;
margin-bottom: 5px;
line-height: 1;
}
label {
font-size: 11px;
display: block;
color: #D5D4D8;
margin-top: 10px;
}
input {
height: 38px;
border-radius: 5px;
border: none;
width: 70px;
padding: 0px 10px;
text-align: center;
background-color: #D5D4D8;
margin-right: 20px;
font-size: 14px;
}
.container {
background: #1F2937;
margin: 0;
padding: 10px 30px 40px;
width: 100%;
min-width: 500px;
box-shadow: 0px 10px 30px 10px #2640644b;
display: flex;
flex-direction: column;
}
.pw-container {
display: flex;
border-radius: 5px;
background-color: #3e4f66;
padding: 10px;
margin-top: 10px;
}
.password-line {
color: #00ffaa;
font-size: 16px;
padding: 5px 10px;
margin-top: 0px;
flex-grow: 1;
flex: 1 1 1;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
#passwords-el {
padding-right: 30px;
flex-grow: 1;
flex: 1 1 0;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
.saved-password-line {
color: #D5D4D8;
font-size: 14px;
padding: 10px 15px;
border-bottom: solid 1px #d5d4d814;
border-radius: 5px;
margin-bottom: 10px;
line-height: 0.9;
}
a {
color: #d5d4d872;
text-decoration: underline;
}
.side-btn {
font-size: 12px;
width: 60px;
border: none;
background: none;
color: #D5D4D8;
padding: 5px 10px;
border-radius: 5px;
justify-self: flex-end;
}
.side-btn:hover {
background-color: #ffffff28 ;
}
#gen-btn {
color: #ffffff;
background: #0EBA80;
text-transform: capitalize;
text-align: center;
width: 200px;
height: 40px;
padding: 10px 10px;
border: none;
border-radius: 5px;
margin-bottom: 10px;
margin-top: 10px;
transition: all 0.5s;
box-shadow: 0px 0px 30px 5px #0eba8135
}
#gen-btn:hover {
box-shadow: 0px 0px 30px 10px #0eba8157
}
#gen-btn span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
#gen-btn span:after {
content: '\279c';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
#gen-btn:hover span {
padding-right: 25px;
}
#gen-btn:hover span:after {
opacity: 1;
right: 0;
}
p {
color: #D5D4D8;
margin-top: 0px;
}
hr {
border-width: 1px 0px 0px 0px;
border-color: #95959576;
margin: 15px 0;
}
manifest.json
{
"manifest_version": 3,
"version": "1.0",
"name": "Password Generator",
"action": {
"default_popup": "index.html",
"default_icon": "icon.png"
},
"permissions": [
"tabs"
]
}
I solved it.
I understand that (please correct me if I'm wrong)
if the local storage is empty, it does not return an empty array when parsed.
Apparently, when I do:
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
passwords is no longer an array.
I instead use:
passwords.push(JSON.parse(localStorage.getItem("savedPasswords")))
But that just pushes a nested array inside passwords.
So I added a for loop, and used an if statement to address the initial error:
let locSavedPasswords = localStorage.getItem("savedPasswords")
if(locSavedPasswords !== null) {
for( var i = 0; i < (JSON.parse(locSavedPasswords)).length; i++){
passwords.push(JSON.parse(locSavedPasswords)[i])
}}
Initially, savedPasswords won't exist in localStorage, so localStorage.getItem('savedPasswords') will return null.
You then do JSON.parse(null), which doesn't immediately crash because null is first coerced to a string and becomes 'null' which is then JSON-parsed and turns back to null since the string with contents null is valid JSON.
But you then do .length on it and crash.
The solution is to handle the case where the item is not yet set and handle it like it was a JSON-stringified empty array. You can do so for example using the nullish coalescing operator ??:
let passwords = JSON.parse(localStorage.getItem("savedPasswords") ?? '[]')
Or, you can keep initializing it with [] as you did before but wrap the assignment with the actual value in a condition:
let passwords = []
const json = localStorage.getItem('savedPasswords')
if (json !== null) {
passwords = JSON.parse(json)
}
Personally, what I like to do for structured data in localStorage is something like this, which also handles the case that other things like invalid JSON somehow got stored there (without bricking the application):
let passwords = []
try {
const data = JSON.parse(localStorage.getItem('savedPasswords'))
if (Array.isArray(data)) passwords = data
} catch {}

javascript remove an item from an array stored in the local Storage

I have an input field that add task. when i add the task a delete button appear next to each task
these task are stored in the local storage as an array
when i click delete button i want to delete the specific item not all the local storage
in general we use localStorage.removeItem(key);
let inputTask = document.querySelector('.input');
let tasks = document.querySelector('.tasks');
let add = document.querySelector('.add');
let alls = [];
//show tasks
function show() {
if (window.localStorage.task) {
let storedTaskes = JSON.parse(localStorage.getItem("task"));
storedTaskes.forEach((item) => {
let paragraph = document.createElement('p');
let deleteBtn = document.createElement('button');
deleteBtn.className = "delete";
deleteBtn.innerHTML = "Delete";
deleteBtn.id = item;
deleteBtn.setAttribute("onclick","deleteBtn(this)");
console.log(deleteBtn.value);
paragraph.innerHTML = item;
paragraph.appendChild(deleteBtn);
tasks.appendChild(paragraph);
});
}
}
// add tasks
add.onclick = function () {
if (inputTask.value.trim() !== "") {
alls.push(inputTask.value);
for (let i = 0; i < alls.length; i++) {
window.localStorage.setItem(`task`, JSON.stringify(alls));
}
}
inputTask.value = '';
show();
}
show();
//Delete Task
function deleteBtn(ob) {
let id = ob.id;
let taskArray = JSON.parse(localStorage.getItem("task"));
for(let i = 0; i < taskArray.length; i++){
if(taskArray[i] === id){
localStorage.removeItem(taskArray[i]);
}
}
}
body{
height: 90vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
display: flex;
align-items: center;
flex-direction: column;
gap: 20px;
}
.form {
background-color: #f0f0f0;
padding: 20px;
width: 500px;
text-align: center;
display: flex;
align-item: center;
justify-content: center;
gap: 15px;
}
.input{
border: 0;
outline: none;
padding: 10px 20px;
width: 300px;
border-radius: 5px;
}
.add,
.delete{
border: 0;
outline: none;
background-color: red;
color: white;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
.tasks {
background-color: #f0f0f0;
padding: 20px;
width: 500px;
}
p {
display: block;
background-color: white;
padding: 15px;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: space-between;
}
<div class="container">
<div class="form">
<input type="text" class="input">
<input type="submit" class="add" value="Add Task">
</div>
<div class="tasks"></div>
</div>
How can i delete the specific item from the array in the local storage and show the new result for the user
You need to remove from the array and store the array again since that is how your other part works
function deleteBtn(ob) {
let id = ob.id;
let taskArray = JSON.parse(localStorage.getItem("task"));
taskArray = taskArray.filter(item => item != id)
localStorage.setItem("task", JSON.stringify(taskArray));
show()
}
ALso change
for (let i = 0; i < alls.length; i++) {
window.localStorage.setItem(`task`, JSON.stringify(alls));
}
to
localStorage.setItem(`task`, JSON.stringify(alls));
Here is a better version
I use delegation for the delete and save to localstorage without reading it again
I use a generated ID as id
Note I have to comment out the localstorage part since SO does not allow it
let inputTask = document.querySelector('.input');
let tasks = document.querySelector('.tasks');
let add = document.querySelector('.add');
let storedTasks // = localStorage.getItem("task"); // uncomment on your server
let allTasks = storedTasks ? JSON.parse(storedTasks) : [];
function show() {
tasks.innerHTML = allTasks
.map(task => `<p>${task.input} <button class="delete" data-id="${task.id}">X</button></p>`)
.join('<br/>');
}
// add tasks
add.onclick = function() {
const input = inputTask.value.trim();
if (input !== "") {
const id = allTasks.length; // use the length at this time
allTasks.push({ id:new Date().getTime(), input });
// localStorage.setItem("task",JSON.stringify(allTasks)); // uncomment on your server
inputTask.value = '';
show();
}
};
show();
document.querySelector(".tasks").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("delete")) {
let id = tgt.dataset.id;
allTasks = allTasks.filter(item => item.id != id)
tgt.closest("p").remove();
// localStorage.setItem("task",JSON.stringify(allTasks)); // uncomment on your server
}
});
body {
height: 90vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
display: flex;
align-items: center;
flex-direction: column;
gap: 20px;
}
.form {
background-color: #f0f0f0;
padding: 20px;
width: 500px;
text-align: center;
display: flex;
align-item: center;
justify-content: center;
gap: 15px;
}
.input {
border: 0;
outline: none;
padding: 10px 20px;
width: 300px;
border-radius: 5px;
}
.add,
.delete {
border: 0;
outline: none;
background-color: red;
color: white;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
.tasks {
background-color: #f0f0f0;
padding: 20px;
width: 500px;
}
p {
display: block;
background-color: white;
padding: 15px;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: space-between;
}
<div class="container">
<div class="form">
<input type="text" class="input">
<input type="submit" class="add" value="Add Task">
</div>
<div class="tasks"></div>
</div>
function deleteBtn({id}) {
let taskArray = JSON.parse(localStorage.getItem("task")); // get the array
taskArray = taskArray.filter(ob=> ob.id != id ) // remove the id
localStorage.setItem("task", JSON.stringify(taskArray));
show()
}
but since you are using tasks.appendChild(paragraph)
you will have to change show function to
//show tasks
function show() {
if (window.localStorage.task) {
let storedTaskes = JSON.parse(localStorage.getItem("task"));
tasks.innerHTML = "" // here
storedTaskes.forEach((item) => {
let paragraph = document.createElement('p');
let deleteBtn = document.createElement('button');
deleteBtn.className = "delete";
deleteBtn.innerHTML = "Delete";
deleteBtn.id = item;
deleteBtn.setAttribute("onclick","deleteBtn(this)");
console.log(deleteBtn.value);
paragraph.innerHTML = item;
paragraph.appendChild(deleteBtn);
tasks.appendChild(paragraph)
});
}
}

Why can't I add a count to my onclick function?

I wanted to try using a count to change the behavior of a click. All my other conditions worked but I don't understand why my count condition doesn't. Does anyone know what I can do to make it work?
For the count I tried -- (this.count == 2), (count == 2), and (uh.count == 2)
function uh() {
var words;
var conf = confirm("ooh that felt goood");
var button = document.querySelector("#selector");
var box =
document.querySelector("#box");
var count = 0;
if (this.count == 5) {
button.classname = "button3";
words = " ";
} else if (this.count == 4) {
button.classname = "button3";
words = "I give up. This is all you get.";
count++;
} else if (this.count == 3) {
button.classname = "button3";
words = "...";
count++;
} else if (this.count == 2) {
button.className = "button2";
words = "the power?";
count++;
} else if (button.className == "button3") {
button.className = "button2";
words = "ahahaha... ha.. uh..";
count++;
} else if (button.className == "button2") {
button.className = "button3";
box.className = "box";
words = "THE POWER";
} else if (conf == true) {
words = "AHAHAHA I HAVE YOU NOW";
button.className = "button2";
} else {
words = "...";
button.className = "button";
}
document.querySelector(".header").innerHTML = words;
}
body {
background-color: black;
}
#header {
text-align: center;
}
.header {
background-color: #000099;
color: white;
display: inline-block;
border: 5px solid white;
padding: 20px;
width: 90%;
}
#box {
text-align: center;
background-color: green;
height: 500px;
}
.box {
text-align: center;
height: 500px;
}
.button {
background-color: grey;
color: white;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 20px;
}
.button2 {
background-color: #ff0000;
border: none;
color: white;
padding: 15px 32px;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 40px;
box-shadow: 0px 0px 10px white;
}
.button3 {
background-color: black;
border: none;
color: red;
padding: 30px 60px;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 60px;
box-shadow: 0px 0px 20px 5px gold;
}
<div id=h eader>
<h1 class="header"> I feel an itch...
<h1>
</div>
<div id="box">
<input type="button" id="selector" class="button" value="CLICK ME" onclick="uh()">
</div>
count is declared and initialized anew each time uh() is called. The variable lifetime ends when the function ends so there is no way to preserve its value across multiple calls to uh().
What you could do, is declare an object called count with a same name property and call() uh on the object. Then this will refer to the object uh() gets called on and thus this.count will have a transferable value across multiple calls on the same object.
var count = {count: 0};
console.log(count.count);//0
up.call(count);
function up() {
this.count++;
//... here add any kind of check on the value of count
}
console.log(count.count);//1

Inserting input field to chat popup

I am trying to learn by creating a chat bar. I have created a side nav bar with users and once I click the chat pop up box will open at the bottom. I want to add input field to that chatbox.
I tried to add the input field but I just got half success; it just gets added to the body not at the bottom of the chat box.
chat.html
<script>
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
var total_popups = 0;
//arrays of popups ids
var popups = [];
function close_popup(id)
{
for(var iii = 0; iii < popups.length; iii++)
{
if(id == popups[iii])
{
Array.remove(popups, iii);
document.getElementById(id).style.display = "none";
calculate_popups();
return;
}
}
}
function display_popups()
{
var right = 220;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
var element = document.getElementById(popups[iii]);
element.style.right = right + "px";
right = right + 320;
element.style.display = "block";
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
var element = document.getElementById(popups[jjj]);
element.style.display = "none";
}
}
function register_popup(id, name)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '<div class="popup-box chat-popup" id="'+ id +'">';
element = element + '<div class="popup-head">';
element = element + '<div class="popup-head-left">'+ name +'</div>';
element = element + '<div class="popup-head-right">✕</div>';
element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
element = element + '<div class="popup-bottom"><div class="popup-bottom"><div id="'+ id +'"></div><input id="field"></div>';
document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
popups.unshift(id);
calculate_popups();
}
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups()
{
var width = window.innerWidth;
if(width < 540)
{
total_popups = 0;
}
else
{
width = width - 200;
//320 is width of a single popup box
total_popups = parseInt(width/320);
}
display_popups();
}
//recalculate when window is loaded and also when window is resized.
window.addEventListener("resize", calculate_popups);
window.addEventListener("load", calculate_popups);
</script>
style.css
<style>
#media only screen and (max-width : 540px)
{
.chat-sidebar
{
display: none !important;
}
.chat-popup
{
display: none !important;
}
}
body
{
background-color: #e9eaed;
}
.chat-sidebar
{
width: 200px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid rgba(29, 49, 91, .3);
}
.sidebar-name
{
padding-left: 10px;
padding-right: 10px;
margin-bottom: 4px;
font-size: 12px;
}
.sidebar-name span
{
padding-left: 5px;
}
.sidebar-name a
{
display: block;
height: 100%;
text-decoration: none;
color: inherit;
}
.sidebar-name:hover
{
background-color:#e1e2e5;
}
.sidebar-name img
{
width: 32px;
height: 32px;
vertical-align:middle;
}
.popup-box
{
display: none;
position: absolute;
bottom: 0px;
right: 220px;
height: 285px;
background-color: rgb(237, 239, 244);
width: 300px;
border: 1px solid rgba(29, 49, 91, .3);
}
.popup-box .popup-head
{
background-color: #009688;
padding: 5px;
color: white;
font-weight: bold;
font-size: 14px;
clear: both;
}
.popup-box .popup-head .popup-head-left
{
float: left;
}
.popup-box .popup-head .popup-head-right
{
float: right;
opacity: 0.5;
}
.popup-box .popup-head .popup-head-right a
{
text-decoration: none;
color: inherit;
}
.popup-box .popup-bottom .popup-head-left
{
position:absolute;
left: 0px;
bottom: 0px
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 100%;
overflow-y: scroll;
}
</style>
posting relevant parts hopw you can make sense of it.
HTML
<div class="popup-box chat-popup">
<div class="popup-head">
<div class="popup-head-left">name</div>
<div class="popup-head-right">✕</div>
<div style="clear: both"></div>
</div>
<div class="popup-messages"></div>
<div class="popup-bottom-container">
<div class="popup-bottom">
<div id="'+ id +'"></div>
<input type="text" id="field">
</div>
</div>
</div>
CSS
.popup-bottom
{
position:absolute;
left: 0px;
bottom: 10px;
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 200px;
overflow-y: scroll;
}
It is always better to try out your layout in plain html before testing with js

Categories