https://codepen.io/TBD007/pen/zYxgWbv
Trying to avoid having to write a function for each button's onclick event. Currently i am using a separate function for each onclick. I am pretty sure there is a way to put all that into one single function but i just can't figure it out on my own.. Any idea to simplify the js code in order to calculate the values? Help is very much appreciated!
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
Here's a the full snippet:
var result = document.getElementById("txtResult").innerHTML;
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test4() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test4").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test5() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test5").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test6() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test6").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test7() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test7").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test8() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test8").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test9() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test9").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test10() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test10").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test11() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test11").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test12() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test12").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test13() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test13").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test14() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test14").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
background-image: url("http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png");
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tr>
<td id="test" value="475"><button onclick="test()" id="btn1" aria-label="Happy Meal"></button></td>
<td id="test2" value="540">
<button onclick="test2()" id="btn2" aria-label="Big Mac"></button>
</td>
<td><button aria-label="All Products" id="logo" ></button></td>
<td><button id="btnClearEntry" onclick="clearentry()">CE</button></td>
</tr>
<tr>
<td id="test3" value="200"><button onclick="test3()" id="btn3" aria-label="Hamburger"></button></td>
<td id="test4" value="250"><button onclick="test4()" id="btn4" aria-label="6 Chicken Nuggets"></button></td>
<td id="test5" value="570"><button onclick="test5()" id="btn5" aria-label="Crispy Chicken Wrap"></button></td>
<td><button id="btnplus" onclick="add()"><b>+</b></button></td>
</tr>
<tr>
<td id="test6" value="350"><button onclick="test6()" id="btn6" aria-label="Big Fries"></button></td>
<td id="test7" value="430"><button onclick="test7()" id="btn7" aria-label="Blueberry Muffin"></button></td>
<td id="test8" value="190"><button onclick="test8()" id="btn8" aria-label="Coke"></button></td>
<td><button id="btnminus" onclick="sub()"><b>-</b></button></td>
</tr>
<tr>
<td id="test9" value="360"><button onclick="test9()" id="btn9" aria-label="Cesars salad"></button></td>
<td id="test10" value="290"><button onclick="test10()" id="btn10" aria-label="Egg McMuffin"></button></td>
<td id="test11" value="360"><button onclick="test11()" id="btn11" aria-label="Fish Mac"></button></td>
<td id="test12" value="490"><button onclick="test12()" id="btn12" aria-label="Royal with Cheese"></button></td>
</tr>
<tr>
<td></td>
<td id="test13" value="270"><button onclick="test13()" id="btn13" aria-label="Baked Apple Pie"></button></td>
<td id="test14" value="340"><button onclick="test14()" id="btn14" aria-label="Mc Sundae"></button></td>
<td></td>
</tr>
</table>
</div>
</div>
</body>
Here is a shorter version
I use the following techniques
unobtrusive event handler
object to hold the names and values
DOM manipulation (sorry I got lazy on the operators)
removed the button from the link and used an image instead for the logo
const buttons = {
"Happy Meal": 475,
"Big Mac": 540,
"Hamburger": 200,
"6 Chicken Nuggets": 250,
"Crispy Chicken Wrap": 570,
"Big Fries": 350,
"Blueberry Muffin": 430,
"Coke": 190,
"Cesars salad": 360,
"Egg McMuffin": 290,
"Fish Mac": 360,
"Royal with Cheese": 490,
"Baked Apple Pie": 270,
"Mc Sundae": 340
}
const operators = [
'<img src="http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png" aria-label="All Products" id="logo" ></img>',
'<button id="btnClearEntry" onclick="clearentry()">CE</button>',
'<button id="btnplus" onclick="add()"><b>+</b></button>',
'<button id="btnminus" onclick="sub()"><b>-</b></button>'
]
const tb = document.querySelector(".calculator table tbody");
let cnt = 0;
let tr = document.createElement("tr");
for (let but in buttons) {
cnt++;
td = document.createElement("td");
td.innerHTML = '<button type="button" id="btn' + cnt + '" aria-label="' + but + '" value="' + buttons[but] + '"></button>';
tr.appendChild(td)
if (cnt % 3 === 0) {
if (operators.length > 0) {
td = document.createElement("td");
td.innerHTML = operators.shift()
}
tr.appendChild(td);
tb.appendChild(tr);
tr = document.createElement("tr");
}
}
tb.appendChild(tr);
tb.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "button") {
document.getElementById("txtResultItem").innerHTML = tgt.value;
}
});
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link rel="stylesheet" type="text/css" href="default.css">
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script type="text/javascript" src="calc.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
You can replace all of these functions with this;
function test(elementId){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(elementId).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
and then in your onClick handlers do something like
test('test')
test('test2')
test('test3')
and just pass in the id of the element as a string value to the function.
So, only variable among your functions is the id of the element from which you are getting x, you can write a function that accepts this variable as parameter and pass it to the function when calling it
function test(id){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(id).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
<button onclick="test('test')">
Try this , add an argument for a function with numerics as 1,2,3..etc and pass that value and append the same in the document.getElementById("test"+itemValue).getAttribute("value") value.
Dynamically pass the inputs from the click event.
function test(itemValue){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById("test"+itemValue).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
Check below snipet
function test(){
thisObj=event.target;
var summe = document.getElementById("txtResult").innerHTML ;
var x=thisObj.getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
<div id="txtResult"></div>
<input type="button" value="1" onclick="test()" />
<input type="button" value="2" onclick="test()" />
<input type="button" value="3" onclick="test()" />
<div id="txtResultItem"></div>
You can use this reference at onclick event handler (without passing extra arguments like test3 etc)
function test(item){
console.log(item.value)
}
<div><button value="1" onclick="test(this)">1</button></div>
<div><button value="2" onclick="test(this)">2</button></div>
<div><button value="3" onclick="test(this)">3</button></div>
Or you can use event.target:
function test(){
var item = event.target;
console.log(item.value)
}
<div><button value="1" onclick="test()">1</button></div>
<div><button value="2" onclick="test()">2</button></div>
<div><button value="3" onclick="test()">3</button></div>
You can use a single function that passes in the id of the element you want to use as var x.
Javascript
function test_reuse(elid){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById(elid).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
Sample HTML element
<td id="test3" value="200"><button onclick="test_reuse('test3')" id="btn3" aria-label="Hamburger"></button></td>
You could have your buttons fire an event upon click, and given the event you can get the ID of the corresponding button and update the UI accordingly.
<td id="test3" value="200"><button onclick="test_general(event)" id="btn3" aria-label="Hamburger"></button></td>
....
//JS
function test_general(event){
var button_id = event.target.id
// DO SOMETHING NOW THAT YOU HAVE THE ID OF BUTTON
console.log(button_id)
}
Few pointers:
Having id on element can help you uniquely identify but the it becomes huge to keep track of. Use classes or composite selectors to achieve this.
Adding onClick on markup will pose a security threat as anyone can inspect your element and see whats going on. Using .addEventListener will encapsulate the code and keeps markup clean.
Having 1-1 mapping of button/ handler is an overkill. You can add any meta information as a part of data- tag and can be retrieved to process.
Following is the updated code: https://codepen.io/TBD007/pen/zYxgWbv which addresses above pointers.
Please note, I added data-number attribute in HTML
Related
its an image slider when I click the next I needs to change the image in the thumbnails also but its not working. also not showing main picture when I click in the the first picture and the second is working but third also not working...
thumbnail's are not change through next and previous...
in slider images are change through next and previous but the thumbnails are not change with image...
Code.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
</head>
<body>
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="img5.png" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="img2.png"></li>
<li class="img12" onclick="thumbchange(3)"><img src="img4.png"></li>
</ul>
</div>
<script>
var newsArr = ['<img src="img5.png"width = 30%; height=400px;>',
'<img src="img2.png"width = 30%; height=400px; >',
'<img src="img4.png" width = 30%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
}
function thumbchange(num) {
var thumb = 'img' + num + '.png';
document.getElementById("demo1").src = thumb;
}
</script>
</body>
</html>
you problem solved ... please try it.
var newsArr = ['<img src="https://www.w3schools.com/bootstrap4/la.jpg"width = 100%; height=400px;>',
'<img src="https://www.w3schools.com/bootstrap4/chicago.jpg"width = 100%; height=400px; >',
'<img src="https://www.w3schools.com/bootstrap4/ny.jpg" width = 100%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
setThumbnailFocus(i)
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
setThumbnailFocus(i)
}
function thumbchange(num) {
x.innerHTML = newsArr[num-1];
y.innerHTML = newsArr1[num-1];
setThumbnailFocus(num-1)
}
function setThumbnailFocus(num){
var elems = document.querySelectorAll(".thumbs .selected");
[].forEach.call(elems, function(el) {
el.classList.remove("selected");
});
document.getElementsByClassName("img12")[num].classList.add("selected");
}
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
.selected{
border:solid 2px red
}
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="https://www.w3schools.com/bootstrap4/la.jpg" width=100%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12 selected" onclick="thumbchange(1)"><img src="https://www.w3schools.com/bootstrap4/la.jpg" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="https://www.w3schools.com/bootstrap4/chicago.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="https://www.w3schools.com/bootstrap4/ny.jpg"></li>
</ul>
</div>
The first issue I found is that you have this code:
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
And here you didn't use part with setting id:
var newsArr = ['<img //here is no id// src="img5.png"width = 30%; height=400px;>',
'<img //here is no id// src="img2.png"width = 30%; height=400px; >',
'<img //here is no id// src="img4.png" width = 30%; height=400px;>'];
And when you are clicking on next and prev button, you are removing your id unconsciously, so your thumbchange() function stop working, because it is based on id.
I have a script which shows a "hover element" (like a zoom) when my mouse is over it. I know it's a bit messy but here's an example:
function showOverflow2(e) {
let cell = e.currentTarget;
let clone = cell.cloneNode(true);
if (cell.children[0].scrollWidth <= cell.children[0].clientWidth) {
return false;
};
clone.innerHTML = clone.children[0].innerHTML;
clone.style.position = 'absolute';
clone.style.backgroundColor = 'white';
clone.style.borderWidth = '2px';
clone.style.lineHeight = cell.scrollHeight + 'px';
clone.style.whiteSpace = 'nowrap';
x0 = (
cell.offsetLeft +
parseFloat(
getComputedStyle(
cell.parentElement.parentElement.parentElement.parentElement
)["padding-left"].slice(0, -2)
) + 2
);
y0 = (
cell.offsetTop +
parseFloat(
getComputedStyle(
cell.parentElement.parentElement.parentElement.parentElement
)["padding-top"].slice(0, -2)
) + 2
);
xmid = x0 + (cell.clientWidth / 2);
ymid = y0 + (cell.clientHeight / 2);
let body = document.getElementsByTagName('body')[0];
body.appendChild(clone);
clone.style.height = cell.scrollHeight + 'px';
clone.style.width = clone.scrollWidth + 'px';
xf = xmid - (clone.clientWidth / 2);
yf = ymid - (clone.clientHeight / 2);
clone.style.top = yf + 'px';
clone.style.left = xf + 'px';
// FOCUS ON THIS PART
clone.addEventListener("mouseout", function() {
clone.remove();
});
// END OF FOCUS
};
let all_cells = document.getElementsByTagName('td');
for (let i = 0; i < all_cells.length; i++) {
let current_cell = all_cells[i];
if (current_cell.className !== 'buttons') {
current_cell.addEventListener("mouseover", showOverflow2);
}
}
body {
margin: 0;
}
#container {
background-color: gainsboro;
border: 2px solid black;
border-radius: 2px;
padding: 1.2%;
max-width: 50%;
}
table {
border-collapse: separate;
border-spacing: 0 0.5rem;
table-layout: fixed;
width: 100%;
}
tr {
background-color: white;
}
td {
width: calc(100%/3);
border: solid gray;
border-width: 2px 1px 2px 0;
padding: 0.7% 1%;
text-align: center;
white-space: nowrap;
}
span {
display: block;
overflow: hidden;
}
td:first-child {
border-left-width: 2px;
border-radius: 3px 0 0 3px;
}
td:last-child {
border-right-width: 2px;
border-radius: 0 3px 3px 0;
}
<div id="container">
<table id="table">
<tr>
<td class="cell1"><span>AAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
</table>
</div>
To remove the "zoom" and return things to normal, I'm simply using:
clone.addEventListener("mouseout", function() {
clone.remove();
This works fine if you are smoothly moving your mouse over the elements, but with a bigger table and faster movements, you can see for yourselves that some elements don't return to normal:
function showOverflow2(e) {
let cell = e.currentTarget;
let clone = cell.cloneNode(true);
if (cell.children[0].scrollWidth <= cell.children[0].clientWidth) {
return false;
};
clone.innerHTML = clone.children[0].innerHTML;
clone.style.position = 'absolute';
clone.style.backgroundColor = 'white';
clone.style.borderWidth = '2px';
clone.style.lineHeight = cell.scrollHeight + 'px';
clone.style.whiteSpace = 'nowrap';
x0 = (
cell.offsetLeft +
parseFloat(
getComputedStyle(
cell.parentElement.parentElement.parentElement.parentElement
)["padding-left"].slice(0, -2)
) + 2
);
y0 = (
cell.offsetTop +
parseFloat(
getComputedStyle(
cell.parentElement.parentElement.parentElement.parentElement
)["padding-top"].slice(0, -2)
) + 2
);
xmid = x0 + (cell.clientWidth / 2);
ymid = y0 + (cell.clientHeight / 2);
let body = document.getElementsByTagName('body')[0];
body.appendChild(clone);
clone.style.height = cell.scrollHeight + 'px';
clone.style.width = clone.scrollWidth + 'px';
xf = xmid - (clone.clientWidth / 2);
yf = ymid - (clone.clientHeight / 2);
clone.style.top = yf + 'px';
clone.style.left = xf + 'px';
// FOCUS ON THIS PART
clone.addEventListener("mouseout", function() {
clone.remove();
});
// END OF FOCUS
};
let all_cells = document.getElementsByTagName('td');
for (let i = 0; i < all_cells.length; i++) {
let current_cell = all_cells[i];
if (current_cell.className !== 'buttons') {
current_cell.addEventListener("mouseover", showOverflow2);
}
}
body {
margin: 0;
}
#container {
background-color: gainsboro;
border: 2px solid black;
border-radius: 2px;
padding: 1.2%;
max-width: 50%;
}
table {
border-collapse: separate;
border-spacing: 0 0.5rem;
table-layout: fixed;
width: 100%;
}
tr {
background-color: white;
}
td {
width: calc(100%/3);
border: solid gray;
border-width: 2px 1px 2px 0;
padding: 0.7% 1%;
text-align: center;
white-space: nowrap;
}
span {
display: block;
overflow: hidden;
}
td:first-child {
border-left-width: 2px;
border-radius: 3px 0 0 3px;
}
td:last-child {
border-right-width: 2px;
border-radius: 0 3px 3px 0;
}
<div id="container">
<table id="table">
<tr>
<td class="cell1"><span>AAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAAaAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAASAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
<tr>
<td class="cell1"><span>AAAAAAAAAABBBCC</span></td>
<td class="cell2"><span>AAAAAAAAAABBBB</span></td>
<td class="cell3"><span>AAAAAAAAAAAAABBBBB</span></td>
</td>
</tr>
</table>
</div>
If I can't trust the mouseout event, what can I do to fix this?
I thought about using a eventListener on mouse movement to test if the mouse is inside the element using absolute coordinates, but probably there's a simpler solution.
You could do something similar using CSS by repeating the content (enlarged) and showing and hiding it on hover. Simple example below.
table {
padding: 30px;
}
td {
position: relative;
padding: 4px;
border: 1px solid blue;
}
.grow {
display: none;
background-color: #fff;
border: 1px solid #000;
padding: 3px;
z-index: 10;
}
td:hover .grow {
display: block;
position: absolute;
top: 0;
left: 0;
transform: scale(1.5);
}
<html>
<head></head>
<body>
<table>
<tr>
<td>asdf<span class="grow">ASDF</span></td>
<td>fasd<span class="grow">FASD</span></td>
</table>
</body>
</html>
I'm answering my own question 'cause I needed to combine some ideas to make it work well.
First I need to point out that, for some reason, the problem I described happens in the browser only when the Developer tab (f12) is open, otherwise all works fine.
But still I wanted to be certain that no cell would freeze that way, so I used css like Ed Lucas. Still, I needed Javascript to get the centering right.
After days trying this I finally found a way to center it using css that worked with absolute positioning and the child element being larger.
I didn't remove the Javascript method because it gives me flexibility of commands to trigger and revert this event.
In the end, my code is looking like this:
function showOverflow(e) {
const div = e;
const cell = div.parentElement;
const span = div.children[0];
if (span.scrollWidth <= span.clientWidth) {
return false;
}
const clone = div.cloneNode(true);
clone.classList.add('hovercell');
cell.appendChild(clone);
let cell_style = getComputedStyle(cell);
function cloneRemove(host) {
clone.remove();
clearInterval(host.id);
}
function isInside(host) {
if (cell_style['z-index'] === '0') {
cloneRemove(host);
}
}
let host = {};
host.id = setInterval(isInside.bind(null, host), 100);
clone.addEventListener("mouseleave", function() {
cloneRemove(host);
});
}
td {
border: 2px solid gray;
padding: 0.7% 1%;
text-align: center;
white-space: nowrap;
z-index: 0;
position: relative;
}
td:hover {
z-index: 2;
}
span {
display: block;
overflow: hidden;
}
.hovercell {
background-color: white;
border: 2px solid gray;
padding: 6px 8px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(1.2);
}
<table>
<tbody>
<tr>
<td>
<div onclick="showOverflow(this)">
<span>A big cell--- 1</span>
</div>
</td>
<td>
<div onclick="showOverflow(this)">
<span>A big cell--- 2</span>
</div>
</td>
</tr>
</tbody>
</table>
Hope it helps someone.
I'm trying to fix this error but if i fix have another error with
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
i got next error
main.js:297 Uncaught TypeError: Cannot set property 'textContent' of null
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
This is code i have problem with (up)
I only want to get after press savebutton all content save.
FULL CODE
function myFunction() {
var x = document.getElementById("Cal");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var queue = []; // store key history
function getHistory() {
var str = ''
for (var i = 0; i < queue.length; i++)
str += queue[i];
return str;
}
// display functions
function runLB() {
document.case.display.value += "("
queue.push('(')
}
function runRB() {
document.case.display.value += ")"
queue.push(')')
}
function run1() {
document.case.display.value += "1"
queue.push('1')
};
function run2() {
document.case.display.value += "2"
queue.push('2')
};
function run3() {
document.case.display.value += "3"
queue.push('3')
};
function run4() {
document.case.display.value += "4"
queue.push('4')
};
function run5() {
document.case.display.value += "5"
queue.push('5')
};
function run6() {
document.case.display.value += "6"
queue.push('6')
};
function run7() {
document.case.display.value += "7"
queue.push('7')
};
function run8() {
document.case.display.value += "8"
queue.push('8')
};
function run9() {
document.case.display.value += "9"
queue.push('9')
};
function run0() {
document.case.display.value += "0"
queue.push('0')
};
function runPlus() {
document.case.display.value += "+"
queue.push('+')
};
function runMinus() {
document.case.display.value += "-"
queue.push('-')
};
function runDivide() {
document.case.display.value += "/"
queue.push('/')
};
function runMultiply() {
document.case.display.value += "*"
queue.push('*')
};
function runComma() {
document.case.display.value += "."
queue.push('.')
};
function runBack() {
var val = document.case.display.value.slice(0, -1);
document.case.display.value = val;
if (queue.length > 1) {
// pop last element from the array
let last = queue.pop();
// check if element length is more than 1
if (last.length > 1) {
// remove last character from string and push to the array again
queue.push(last.slice(0, -1))
}
}
};
function testLength() {
if (document.case.display.value.length > 16 && document.case.display.value.length < 21) {
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length == 16 || document.case.display.value.length == 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
} else if (document.case.display.value.length > 25) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 28 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
} else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, #back")
numbers.forEach(el => el.addEventListener('click', testLength))
});
function runEquals() {
if (document.case.display.value.length < 3) {
Notiflix.Notify.Info('Enter charatchers !');
countBell();
} else if (isNaN(document.case.display.value)) {
var equals = Math.round(eval(document.case.display.value) * 1000) / 1000;
document.case.display.value = equals;
document.getElementById("result").innerHTML += queue.join("") + "=" + equals + "\n";
queue = [equals.toString()];
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Success('Success');
} else if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
Notiflix.Notify.Warning(' Can not be calculated ! ');
countBell();
}
}
function testNum() {
if (document.case.display.value == "Infinity") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Infinity ! ');
countBell();
} else if (document.case.display.value == "NaN") {
document.getElementById('back').value = "AC";
document.getElementById('back').onclick = DeleteAll;
Notiflix.Notify.Warning(' Not a Number ! ');
countBell();
} else if (!document.case.display.value.includes("")) {} else if (document.case.display.value.includes("/0")) {
Notiflix.Notify.Failure(' You cannot divide by 0 ! ');
countBell();
} else if (document.case.display.value.includes("..") || document.case.display.value.includes("//") || document.case.display.value.includes("**") || document.case.display.value.includes("--") || document.case.display.value.includes("++")) {
runBack();
Notiflix.Notify.Failure('Enter number ! ');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")")) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([123456789])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value)) {
Notiflix.Notify.Failure('U cannot end bracket now !');
countBell();
} else if (!document.case.display.value.includes("(") && document.case.display.value.includes(")") && !/([+/*-])/.test(document.case.display.value) && !/([123456789])/.test(document.case.display.value)) {} else {
document.getElementById('back').value = "CE";
document.getElementById('back').onclick = runBack;
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit, .oper")
numbers.forEach(el => el.addEventListener('click', testNum))
});
Notiflix.Confirm.Init({
timeout: 3000,
okButtonBackground: "#C46600",
titleColor: "#C46600",
});
function DeleteAll() {
document.case.display.value = "";
}
function Del() {
Notiflix.Confirm.Show(' Confirm',
'Are you sure you want to delete text?', 'Yes', 'No',
function() {
Notiflix.Notify.Success('Text is Deleted');
document.getElementById("result").innerHTML = "";
},
function() {
Notiflix.Notify.Info('Text is not Deleted');
countBell();
});
}
//print
function printTextArea() {
childWindow = window.open('', 'childWindow', 'location=yes, menubar=yes, toolbar=yes');
childWindow.document.open();
childWindow.document.write('<html><head></head><body>');
childWindow.document.write(document.getElementById('result').value.replace(/\n/gi, '<br>'));
childWindow.document.write('</body></html>');
childWindow.print();
childWindow.document.close();
childWindow.close();
}
//Font ++ and --
function FontM() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize <= 10) {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Smallest font size');
} else {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Font size -5px');
}
}
//print
function FontP() {
txt = document.getElementById('result');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
if (currentSize >= 50) {
txt.style.fontSize = (currentSize - 5) + 'px';
Notiflix.Notify.Info('Biggest font size');
} else {
txt.style.fontSize = (currentSize + 5) + 'px';
Notiflix.Notify.Info('Font size +5px');
}
}
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
function updateOutput() {
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
window.onload = function() {
const myInput = document.getElementById('display');
myInput.onpaste = function(e) {
e.preventDefault();
}
}
function Git() {
window.open("https://github.com/TheLexa", "_blank");
countBell()
};
var count = 0;
function countBell() {
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = x;
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '๐' + x;
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 3000);
}, 2000);
document.getElementById('notification').style.border = "thick solid red ";
count += 1;
notifNote();
}
var x = -1;
function notifNote() {
x++;
if(x==0){
}else{
localStorage.setItem('display_notification' + x, display.value);
localStorage.setItem('x' ,x);
}
}
window.onload = function() {
countBell();
x =+ localStorage.getItem('x');
}
function notif() {
Notiflix.Confirm.Show('Answer', 'Do you want to delete' + ' ' + '(' + x + ')' + ' ' + 'notification', 'Show Notification', 'Yes Delete Notification',
function() {
Notiflix.Report.Success(
' Success', 'We put notification in Note', 'Click');
var note_textarea = document.querySelector('#TE');
var y = 0;
if (x == 0) {
Notiflix.Report.Warning('INFO', 'No notification', 'Click');
} else {
for (y = 1; x > y; y++) {
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
note_textarea.textContent += '\n' + localStorage.getItem('display_notification' + y) + ' ' + 'Cannot be calculated';
}
},
function() {
count = 1;
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '25px';
setTimeout(function(){
document.getElementById('notification').innerText = '0';
document.getElementById('notification').style.fontSize = '33px';
setTimeout(function(){
document.getElementById('notification').innerText = '๐';
document.getElementById('notification').style.fontSize = '22px';
}, 2000);
}, 1000);
}, 2000);
var z;
for (z = 0; x > z; z++) {
localStorage.removeItem('display_notification' + z);
}
localStorage.removeItem('display_notification' + z);
x = 0;
Notiflix.Report.Success(
' Success', 'Notification success deleted', 'Click');
});
};
// NUMBERS
/*
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ( (charCode < 40 || charCode > 57)) {
return false;
}
return true;
}
var equal = document.getElementById("equal");
wage.addEventListener("keydown", function (e) {
if (e.keyCode === 13) { //checks whether the pressed key is "Enter"
runEquals();
}
});
*/
#media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
#wrapper {
display: flex;
}
html {
background:
linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
}
ul {
list-style: none;
}
body {
width: 500px;
overflow: hidden;
}
#Print {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 85px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 85px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
}
#Del {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 5px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#Git {
position: absolute;
color: #fff;
background: rgba(255, 110, 0, 0.5);
left: 94.5%;
font-size: 20px;
border-radius: 30px;
width: 80px;
height: 60px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border: 2px solid rgba(255, 110, 0, 0.1);
}
#Note {
border: 3px solid rgba(155, 89, 182, 1);
margin-bottom: 25px;
transform: translate(0, 50%);
width: 401px;
height: 50px;
color: #fff;
font-family: 'Inconsolata', monospace;
font-size: 25px;
text-transform: uppercase;
text-decoration: none;
font-family: sans-serif;
box-sizing: border-box;
background: rgba(155, 89, 182, 1);
background-size: 400%;
border-radius: 0px 0px 7px 7px;
z-index: 1;
}
#Note:hover {
animation: animate 5s linear infinite;
}
#keyframes animate {
0% {
background-position: 0%;
}
100% {
background-position: 500%;
}
}
#Note:before {
content: '';
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
z-index: -1;
background: linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);
background-size: 400%;
border-radius: 40px;
opacity: 0;
transition: 0.5s;
}
#Note:hover:before {
filter: blur(20px);
opacity: 1;
animation: animate 5s linear infinite;
}
{}
form {
background: linear-gradient(rgba(196, 102, 0, 0.6), rgba(155, 89, 182, 0.6));
text-align: center;
align-content: center;
border-radius: 10px;
border: 3px solid rgba(196, 102, 0, 0.6);
}
#display {
font-family: 'Roboto', sans-serif;
width: 98%;
height: 60px;
text-align: right;
margin: 5px;
border: 5px solid rgba(196, 102, 0, 0.9);
font-size: 2.5em;
font-weight: 500px;
}
.digit {
font-size: 2rem;
background-color: #f8f8f8;
height: 55px;
width: 22%;
border: 1px solid #c6c6c6;
display: inline-block;
box-shadow: 1px 1px 1px;
color: #222;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
margin: 1.5px;
opacity: 0.9;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
.oper {
font-size: 2rem;
background-color: #d6d6d6;
height: 55px;
width: 22%;
color: #444;
display: inline-block;
margin: 1.5px;
box-shadow: 0 1px 1px;
font-family: Roboto-Regular, helvetica, arial, sans-serif;
opacity: 0.9;
border: 1px solid #b6b6b6;
box-shadow: 0 1px 1px rgba(0, 0, 0, .1)
}
#equal {
background-color: rgba(196, 102, 0, 0.6);
color: white;
width: 183px;
border: none;
}
#TE {
display: block;
resize: none;
width: 386px;
height: 300px;
margin-top: 5px;
margin-left: 7px;
font-size: 20px;
border: 1px solid rgba(196, 102, 0, 0.9);
border-radius: 0px 0px 10px 10px;
font-family: 'Inconsolata', monospace;
}
#result {
margin-left: 5px;
display: block;
resize: none;
width: 400px;
height: 430px;
max-width: 400px;
max-height: 600px;
font-size: 20px;
border-radius: 10px 10px 1px 1px;
border: 1px solid rgba(196, 102, 0, 0.9);
}
button, input[type=button] {
cursor: pointer;
}
.digit:hover, .oper:hover {
border: 1px solid rgba(0, 0, 0, .1);
box-shadow: 0px 1px 1px rgba(0, 0, 0, .1);
opacity: 1;
}
#Del:hover, #Print:hover, #Git:hover, #FP:hover, #FM:hover, #SaveBtn:hover {
opacity: 0.8;
font-size: 20px;
}
#display:hover {
border: 4px solid rgba(196, 102, 0, 0.9);
}
#FP {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 170px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#FM {
border: 1px solid rgba(255, 110, 0, 0.7);
margin-left: 250px;
position: absolute;
color: white;
background: rgba(196, 102, 0, 0.6);
font-size: 19px;
width: 80px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
}
#SaveBtn {
border: 1px solid rgba(255, 110, 0, 0.7);
background: rgba(200, 102, 0, 0.75);
margin-left: 330px;
position: absolute;
color: white;
font-size: 21px;
width: 75px;
height: 30px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 0px 0px 10px 0px;
}
#notification {
border: 3px solid rgba(155, 89, 182, 1);
background: white;
margin-left: 1470px;
margin-top: 730px;
position: absolute;
color: black;
font-size: 22px;
width: 56.5px;
height: 56.5px;
font-family: sans-serif;
text-decoration: none;
box-sizing: border-box;
background-size: 400%;
border-radius: 1px;
border-radius: 60px 60px 60px 60px;
animation-name: example;
animation-duration: 30s;
}
#keyframes example {
0% {
border-color: red;
}
5% {
border-color: yellow;
}
10% {
border-color: blue;
}
15% {
border-color: green;
}
20% {
border-color: red;
}
25% {
border-color: yellow;
}
30% {
border-color: blue;
}
35% {
border-color: green;
}
40% {
border-color: red;
}
45% {
border-color: yellow;
}
50% {
border-color: blue;
}
55% {
border-color: green;
}
60% {
border-color: red;
}
65% {
border-color: yellow;
}
70% {
border-color: blue;
}
75% {
border-color: green;
}
80% {
border-color: red;
}
85% {
border-color: yellow;
}
90% {
border-color: blue;
}
95% {
border-color: green;
}
100% {
border-color: red;
}
}
<html>
<head>
<!--Copyright 2019, Aleksa Kovacevic, All rights reserved.-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Online calculators for everything. Some solve problems, some satisfy curiosity." />
<meta name="keywords" content="calculator, mortgage, loan,lease, cooking, math, college tuition, agriculture, finance,fractions,love,scientific, design, health, unit converter, pocket, running, calculators" />
<link rel="icon" href="https://www.apkmirror.com/wp-content/uploads/2017/11/5a0aad10ea5ec.png">
<title id="Title">Calculator </title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="main.css" type="text/css">
<link rel="stylesheet" href="Notiflix\node_modules\notiflix\dist\notiflix-1.8.0.min.css" />
<script src="Notiflix\node_modules\notiflix\dist\notiflix-aio-1.8.0.js""></script>
<script src=" main.js" type="text/javascript"></script>
</head>
<body>
<button type="button" id="notification" onclick="notif()"> ๐</button>
<button type="button" id="Git" onclick="Git()"> GitHub</button>
<div id="wrapper">
<form name="case">
<!--Buttons -->
<input name="display" id="display" placeholder "0" onkeypress="" autofocus readonly>
<input type="button" class="oper" value="(" onclick="runLB()">
<input type="button" class="oper" value=")" onclick="runRB()">
<input type="button" id="back" class="oper" value="CE" onclick="runBack()">
<input type="button" id="divide" class="oper" value="รท" onclick="runDivide()">
<input type="button" class="digit" value="1" onclick="run1()">
<input type="button" class="digit" value="2" onclick="run2()">
<input type="button" class="digit" value="3" onclick="run3()">
<input type="button" id="multiply" class="oper" value="ร" onclick="runMultiply()">
<input type="button" class="digit" value="4" onclick="run4()">
<input type="button" class="digit" value="5" onclick="run5()">
<input type="button" class="digit" value="6" onclick="run6()">
<input type="button" id="minus" class="oper" value="-" onclick="runMinus()">
<input type="button" class="digit" value="7" onclick="run7()">
<input type="button" class="digit" value="8" onclick="run8()">
<input type="button" class="digit" value="9" onclick="run9()">
<input type="button" id="plus" class="oper" value="+" onclick="runPlus()">
<input type="button" class="digit" value="0" onclick="run0()">
<input type="button" id="comma" class="digit" value="." onclick="runComma()">
<input type="button" id="equal" class="oper" value="=" onclick="runEquals()">
<div id="Cal">
<textarea id="TE" placeholder="Note"></textarea>
</div>
<div id="newpos">
<!-- button rainbow -->
<button type="button" id="Note" onclick="myFunction()"> Note</button></div>
</form>
<div id="new">
<!--result textarea-->
<textarea id="result" placeholder="History" readonly></textarea>
<button type="button" id="Del" onclick="Del()"> Delete</button>
<button type="button" id="Print" onclick="printTextArea()"> Print</button>
<button type="button" id="FP" onclick="FontP()">Font +</button>
<button type="button" id="FM" onclick="FontM()">Font -</button>
<button type="button" id="SaveBtn"> Save </button>
</div>
</div>
</body>
NOTIFLIX IS library for client-side non-blocking notifications, popup boxes, loading indicators, and more to that makes your web projects much better.
THIS is my portofolio if you have any good information tell me THANKS :)
The problem here is the dom is not loaded so the textarea is not available until the dom is not loaded. adding a window load listener for it will solve it.
window.addEventListener('load', function(){
//local storage savebtn
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
var save_button = document.getElementById('overlayBtn');
if(save_button){
save_button.addEventListener('click', updateOutput);
}
result_textarea.textContent = localStorage.getItem('content_result');
note_textarea.textContent = localStorage.getItem('content_textarea');
display.value = localStorage.getItem('content_display');
bell.textContent = localStorage.getItem('bell_count');
})
The function does not see the bell variable because a javascript scope does not allow it to be seen. You need to get your dom elements in the inside of the updateOutput function.
function updateOutput() {
var note_textarea = document.querySelector('#TE');
var result_textarea = document.querySelector('#result');
var save_button = document.getElementById('SaveBtn');
var display = document.querySelector('#display');
var bell = document.getElementById('notification');
Notiflix.Notify.Success('Text has been saved ');
localStorage.setItem('content_textarea', note_textarea.value);
localStorage.setItem('content_result', result_textarea.value);
localStorage.setItem('content_display', display.value);
localStorage.setItem('bell_count', bell.textContent);
}
I have the following form for lyrics upload. I've changed the design of the form a little bit, and now facing a weird problem.
I've created a fake-datalist using JS. On input focus, a fake-datalist (an ul element) is appended next to the input element. Its position is set to absolute so it shouldn't disrupt the flow of the document when it appears. However, it does. I can't seem to identify the problem. Once the datalist appears, the div next to the table gets pushed down. Table width isn't changing when the datalist appears, so it's not squizing the div and pushing it down.
Code Pen
var artists = [{"artist":"3 Doors Down"},{"artist":"5 Seconds of Summer"},{"artist":"Adele"},{"artist":"Alicia Keys"},{"artist":"Amanda Abizaid"},{"artist":"Avril Lavigne"}];
var albums = [{"album":"The Better Life","year":"2000","cover":"3_doors_down_2000_the_better_life.jpg"},{"album":"Away from the Sun","year":"2002","cover":"3_doors_down_2002_away_from_the_sun.jpg"},{"album":"Seventeen Days","year":"2005","cover":"3_doors_down_2005_seventeen_days.jpg"},{"album":"3 Doors Down","year":"2008","cover":"3_doors_down_2008_3_doors_down.jpg"},{"album":"Time of My Life","year":"2011","cover":"3_doors_down_2011_time_of_my_life.jpg"}];
var songs = [{"song":"Kryptonite","track_no":"1"},{"song":"Duck and Run","track_no":"3"},{"song":"Be Like That","track_no":"5"},{"song":"So I Need You","track_no":"11"}];
function datalist(element) {
return new datalist.prototype.init(element);
}
datalist.prototype = {
init: function(element) {
if (!element) {
this.element = document.createElement("ul");
this.element.classList.add("datalist");;
this.hide();
} else {
this.element = element;
}
},
update: function(queryElement) {
this.clear();
var lookUpArray = queryElement.name + "s";
var results = this.search(window[lookUpArray], queryElement.value, queryElement.name);
for (var i = 0; i < results.length; i++) {
var li = document.createElement("li");
var value = results[i][queryElement.name];
switch (queryElement.name) {
case "album":
li.setAttribute("data-year", results[i].year);
break;
case "song":
li.setAttribute("data-track_no", results[i].track_no);
break;
}
if (queryElement.value != "") {
var re = new RegExp(queryElement.value, "gi");
value = value.replace(re, "<span class=\"highlight\">" + "$&" + "</span>");
}
li.innerHTML = value;
this.element.appendChild(li);
}
return results.length;
},
search: function(lookUpArray, string, queryType) {
var results = [];
for (var i = 0; i < lookUpArray.length; i++) {
if (lookUpArray[i][queryType].toLowerCase().search(string.toLowerCase()) != -1) {
results.push(lookUpArray[i]);
}
}
return results;
},
clear: function() {
this.element.innerHTML = "";
},
hide: function() {
this.element.style.display = "none";
},
show: function() {
this.element.style.display = "";
},
remove: function() {
this.element.parentElement.removeChild(this.element);
},
for: function(sibling) {
sibling.parentElement.appendChild(this.element);
this.hide();
},
};
datalist.prototype.init.prototype = datalist.prototype;
var lastVisitedInput = null;
$("#lyrics-form").on("focus", "input.datalist-input", function() {
if (this.parentElement.children.length == 1) {
this.parentElement.appendChild(datalist().element);
}
if (lastVisitedInput) {
datalist(lastVisitedInput.nextElementSibling).hide();
}
lastVisitedInput = this;
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$(document).on("click", function(e) {
if (lastVisitedInput) {
var exceptions = getExceptions(lastVisitedInput);
if (!contains(exceptions, e.target)) {
datalist(lastVisitedInput.nextElementSibling).remove();
lastVisitedInput = null;
}
}
});
$("#lyrics-form").on("input", "input.datalist-input", function() {
if (datalist(this.nextElementSibling).update(this)) {
datalist(this.nextElementSibling).show();
} else {
datalist(this.nextElementSibling).hide();
}
});
$("#lyrics-form").on("click", "li", function() {
this.parentElement.previousElementSibling.value = this.innerText;
$(this.parentElement.previousElementSibling).trigger("input");
});
function getRecord(input) {
var lookUpArray = window[input.name + "s"];
for (var i = 0; i < lookUpArray.length; i++) {
if (input.value == lookUpArray[i][input.name]) {
return lookUpArray[i];
}
}
return false;
}
function getExceptions(input) {
var exceptions = [
input,
input.nextElementSibling,
];
for (var i = 0; i < input.nextElementSibling.children.length; i++) {
exceptions.push(input.nextElementSibling.children[i]);
}
return exceptions;
}
function contains(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return true;
}
}
return false;
}
* { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } *, *:before, *:after { box-sizing: inherit; } body { line-height: 1.5; font-family: sans-serif; } input[type="button"], input[type="submit"] { cursor: pointer; } textarea, input[type="text"], input[type="search"], input[type="number"], input[type="password"] { border: 1px solid rgba(0,0,0,.2); padding: 4px; margin: 1px; } table { border-collapse: collapse; border-spacing: 0; }
body {
background-color: rgb(230, 230, 230);
font-family: Arial, sans-serif;
font-size: 14px;
color: rgba(0, 0, 0, .8);
box-sizing: border-box;
}
#main {
height: 500px;
background: white;
box-shadow: 0 0 2px rgba(0, 0, 0, .1), 0 2px 2px rgba(0, 0, 0, .1);
margin: 20px auto;
display: table;
padding: 20px;
}
#songInput {
overflow: auto;
}
#songTable td {
position: relative;
}
#songTable,
#coverDiv {
float: left;
}
#coverDiv {
margin-left: 20px;
}
#artist,
#album,
#song {
width: 250px;
}
#artist {
width: 300px;
width: 100%;
}
#year,
#track_no {
width: 70px;
}
#songTable td {
padding-bottom: 20px;
}
#songTable td:first-child {
padding-right: 10px;
}
#songTable .int-input {
padding-left: 20px;
padding-right: 10px;
}
#coverDiv > * {
display: block;
}
#coverDiv img {
width: 137px;
height: 137px;
border: 1px solid rgba(0, 0, 0, .2);
margin: 1px;
}
#coverUpload {
margin: 1px;
margin-top: 10px;
width: 250px;
}
#lyricsBox {
width: 100%;
height: 400px;
margin-top: 15px;
}
#submit {
width: 100%;
margin-top: 15px;
}
.datalist {
border: 1px solid silver;
box-shadow: 0 2px 5px rgba(0, 0, 0, .5);
position: absolute;
top: 32px;
left: 1px;
background: white;
padding: 5px;
max-height: 195px;
width: 180px;
width: 100%;
overflow-y: scroll;
z-index: 1000;
}
.datalist li {
padding: 2px 5px;
cursor: default;
}
.datalist li:hover {
background: rgba(0, 0, 0, .05);
color: black;
}
.datalist .highlight {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<form action="addlyrics.php" id="lyrics-form" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="songInput">
<table id="songTable">
<tr>
<td>Artist</td>
<td colspan="3">
<input type="search" name="artist" id="artist" class="datalist-input" placeholder="Artist" required />
</td>
</tr>
<tr>
<td>Album</td>
<td>
<input type="search" name="album" id="album" class="datalist-input" placeholder="Album" required />
</td>
<td class="int-input">Year</td>
<td>
<input type="number" name="year" id="year" class="input-num" placeholder="Year" required />
</td>
</tr>
<tr>
<td>Song</td>
<td>
<input type="search" name="song" id="song" class="datalist-input" placeholder="Name" required />
</td>
<td class="int-input">#</td>
<td>
<input type="number" name="track_no" id="track_no" class="input-num" placeholder="ID" required />
</td>
</tr>
</table>
<div id="coverDiv">
<img src="covers/blank.gif" id="cover" />
<input type="file" name="cover" id="coverUpload" accept="image/*" />
</div>
</div>
<textarea name="lyrics" placeholder="Lyrics" id="lyricsBox" /></textarea>
<input type="submit" id="submit" class="button" />
</form>
</div>
Removing overflow: auto; from #songInput, the parent element of the table and the div, solved the problem. Although, I don't understand why overflow: auto; on the parent would push the div down. Dynamically added ul.datalist's position is set to absolute, and when it appears, the only thing it might do is extend the height of the table, which shouldn't effect the div at the right.
I am using the following css code:
html {
background: #2B2B2B url(images/bg.gif) repeat;
}
body {
max-width: 1000px;
margin: 0px auto;
font-family: sans-serif;
margin: 0 auto;
}
header,
footer,
aside {
display: block;
}
h1 {
text-align: center;
color: rgba(0, 0, 0, 0.6);
text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
text-decoration: underline;
}
label {
display: block;
}
fieldset {
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
input,
select {
width: 400px;
height: 30px;
border-radius: 5px;
padding-left: 10px;
font-size: 14px;
}
select {
line-height: 30px;
background: #f4f4f4;
}
button {
font-size: 14px;
padding: 5px;
background: #333333;
color: #FFFCEC;
float: right;
width: 100px;
}
button:hover {
font-size: 16px;
}
#edit {
background: #DC5B21;
}
#delete {} #course,
#name,
#profesor,
#subject {
background: #ABDCD6;
}
label {
font-size: 15px;
font-weight: bold;
color: #282827;
}
table {
border-spacing: 0.5rem;
border-collapse: collapse;
margin: 0 auto;
background: #ABDCD6;
}
th {
background: #E9633B;
}
th,
td {
border: 2px solid black;
padding: 10px;
}
td {
font-weight: bold;
font-style: oblique;
}
tr:nth-child(even) {
background: #ABDCD6
}
tr:nth-child(odd) {
background: #DCD8CF
}
.container {
width: 1000px;
margin: 0 auto;
}
.headerbar {
width: 988px;
float: left;
}
.headerbar.top {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 100px;
border-radius: 19px 30px 0px 0px;
box-shadow: #938D94 7px 7px 5px;
}
.headerbar.bottom {
background: linear-gradient(45deg, rgba(255, 102, 13, 1) 3%, rgba(255, 109, 22, 1) 32%, rgba(255, 121, 38, 1) 77%, rgba(255, 121, 38, 1) 100%);
min-height: 60px;
border-radius: 25px;
border-radius: 0px 0px 37px 34px;
box-shadow: #938D94 7px 1px 5px;
}
.leftbar {
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
.rightbar {
width: 47%;
background: #221E1D;
min-height: 595px;
float: left;
padding: 5px;
border: 2px solid #EB593C;
box-shadow: #938D94 5px 5px 5px;
}
#submit,
#clear {
border-radius: 25px;
}
input:focus {
border: 1px solid #FF9933;
}
#media screen and (max-width: 700px) {
.leftbar,
.rightbar {
float: none;
}
.headerbar.top h1 {
margin-left: 50px;
text-align: center;
float: left;
}
and here is my HTML page very simple
<!DOCTYPE html>
<html>
<head>
<title>My web app</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="mystyle2.css" rel="stylesheet"/>
<script>
var studentsArray = [];
var selectedIndex = -1;
function init() {
document.getElementById("tablerows").innerHTML = "";
if (localStorage.studentsRecord) {
studentsArray = JSON.parse(localStorage.studentsRecord);
for (var i = 0; i < studentsArray.length; i++) {
prepareTableCell(i, studentsArray[i].course, studentsArray[i].name, studentsArray[i].profesor, studentsArray[i].subject);
}
}
}
function onRegisterPressed() {
if(validate()){
var course = document.getElementById("course").value;
var name = document.getElementById("name").value;
var profesor = document.getElementById("profesor").value;
var subject = document.getElementById("subject").value;
var stuObj = {course: course, name: name, profesor: profesor, subject: subject};
if (selectedIndex === -1) {
studentsArray.push(stuObj);
} else {
studentsArray.splice(selectedIndex, 1, stuObj);
}
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
onClarPressed();
}else{
}
}
function prepareTableCell(index, course, name, profesor, subject) {
var table = document.getElementById("tablerows");
var row = table.insertRow();
var courseCell = row.insertCell(0);
var nameCell = row.insertCell(1);
var profesorCell = row.insertCell(2);
var subjectCell = row.insertCell(3);
var actionCell = row.insertCell(4);
courseCell.innerHTML = course;
nameCell.innerHTML = name;
profesorCell.innerHTML = profesor;
subjectCell.innerHTML = subject;
actionCell.innerHTML = '<button id="edit" onclick="onEditPressed(' + index + ')">Edit</button><br/><button id="delete" onclick="deleteTableRow(' + index + ')">Delete</button>';
}
function deleteTableRow(index) {
studentsArray.splice(index, 1);
localStorage.studentsRecord = JSON.stringify(studentsArray);
init();
}
function onClarPressed() {
selectedIndex = -1;
document.getElementById("course").value = "";
document.getElementById("name").value = "";
document.getElementById("profesor").value = "";
document.getElementById("subject").value = "Math";
document.getElementById("submit").innerHTML = "Register";
}
function onEditPressed(index) {
selectedIndex = index;
var stuObj = studentsArray[index];
document.getElementById("course").value = stuObj.course;
document.getElementById("name").value = stuObj.name;
document.getElementById("profesor").value = stuObj.profesor;
document.getElementById("subject").value = stuObj.subject;
document.getElementById("submit").innerHTML = "Update";
}
function validate(){
var errors = [];
var re = /^[\w]+$/;
var id = document.getElementById("course");
if(id.value==="" ){
errors.push("Course name is empty");
}else if(id.value.length<3){
errors.push("Course name is to shoort");
}else if(!re.test(id.value)){
errors.push("Input contains invalid characters");
}
var name = document.getElementById("name");
var regEx = /^[a-zA-Z ]+$/;
if(name.value===""){
errors.push("Name cannot be empty");
}else if(!regEx.test(name.value)){
errors.push("Name contains invalid characters");
}
var profesor = document.getElementById("profesor");
if(profesor.value===""){
errors.push("Professor field cannot be empty");
}else if(!regEx.test(profesor.value)){
errors.push("Professor field contains invalid characters");
}
if(errors.length>0){
var message = "ERRORS:\n\n";
for(var i = 0;i<errors.length;i++){
message+=errors[i]+"\n";
}
alert(message);
return false;
}
return true;
}
</script>
</head>
<body onload="init()">
<header class="headerbar top"><h1>ITEC3506: Assignment#2</h1></header>
<aside class="leftbar">
<div>
<fieldset>
<label for="course"><span>Course Name</span></label>
<input type="text" placeholder="enter name of course" id="course">
</fieldset>
<fieldset>
<label for="name">Your Name</label>
<input type="text" placeholder="enter your name" id="name">
</fieldset>
<fieldset>
<label for="profesor">Course Professor</label>
<input type="text" placeholder="enter course Professor" id="profesor">
</fieldset>
<fieldset>
<label for="subject">Subject</label>
<select id="subject">
<option value="Math">Math</option>
<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
<option value="English">English</option>
<option value="CS">CS</option>
</select>
</fieldset>
<fieldset>
<label for="submit"> </label>
<button id="submit" onclick="onRegisterPressed()">Submit</button>
<button id="clear" onclick="onClarPressed()">Clear</button>
</fieldset>
</div>
</aside>
<aside class="rightbar">
<table id="regtable">
<thead>
<tr>
<th>Course</th>
<th>Student</th>
<th>Professor</th>
<th>Subject</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tablerows">
</tbody>
</table>
</aside>
<footer class="headerbar bottom"></footer>
</div>
</body>
</html>
My question is how can I transform this code into a responsive site.
Everything is resizing normally, except I cannot seem to resize my table and form. Could somebody help me?
A few things going on here.
First, you don't have a set width on a few of your fields, so change:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
}
to:
fieldset{
border: 0px dotted red;
width: 400px;
margin: 0 auto;
max-width: 100%;
}
Also change .headerbar from width: 988px; to width: 100%;.
For responsive frameworks, you need to ensure that you never have a set a fixed width without ensuring there is a max-width attached to it, otherwise your content size will never drop below the size of your fixed width.
Second, I noticed the following:
.leftbar{
width: 50%;
background: #EB593C;
min-height: 605px;
float: left;
border-radius: 4px;
border: 3px dashed #282827;
}
You didn't specifically call this out, but when I check your code in a smaller view, I notice that your width: 50%; is causing the backgrounds to look off, which does not seem to be your intention. I would recommend adding .leftbar { width: 100%; } as well as .rightbar { width: 100%; } inside of #media screen and (max-width:700px){
That just leaves the table. Tables do not automatically break down, so are generally not something we want to use when developing a responsive site, but of course sometimes there is no getting around this.
There are a few ways to tackle the issue with the table. One is to set the table to display:block; and apply overflow-x: scroll; to it inside of your #media screen and (max-width:700px){, which will allow the user to scroll left/right when viewing it from smaller screens. Another is to use one of the various Javascript plugins that can achieve this.
Hope this helps get you on the right track. Best of luck!
Do not set width for these
input,select{/*width: 400px;*/}
fieldset{/*width: 400px;*/}
If you are setting width obviously you cannot obtain a responsive layout