I am working on an assignment where I need to make the cloud that appears at the top change to either a freezing face emoji or a sun depending on the temperature. I have the Java set up so when the prompts pop up, the city and temperature change based on the user's responses.
How do I change the existing emoji to the new ones?
The new h1 shows the entries for the prompt but they are not spaced. How do I create spacing between the words?
Weather App
h1,
h2,
h3 {
text-align: center;
font-family: Helvetica, Arial, sans-serif;
}
h1 {
color: #1a64d6;
font-size: 34px;
line-height: 48px;
margin: 0;
}
h2 {
margin: 0;
font-size: 34px;
line-height: 48px;
font-weight: 400;
}
ul {
padding: 0;
}
li {
list-style: none;
text-align: center;
padding: 10px 0;
border-radius: 10px;
transition: all 200ms ease-in-out;
max-width: 400px;
margin: 0 auto;
}
li:hover {
background: #fffbef;
}
p {
font-size: 18px;
opacity: 0.7;
text-align: center;
font-family: monospace;
}
button {
display: block;
margin: 20px auto;
border: 1px solid #1a64d6;
background: #1a64d6;
color: #fff;
font-size: 16px;
line-height: 22px;
padding: 16px 24px;
border-radius: 30px;
transition: all 200ms ease;
box-shadow: rgba(37, 39, 89, 0.08) 0px 8px 8px 0;
cursor: pointer;
}
button:hover {
background: white;
color: #1a64d6;
border: 1px solid #1a64d6;
}
</style>
🌤
Currently 21° in Tokyo
13° / 23°
🌧Tomorrow
10° / 22°
🌥 Saturday
15° / 17°
☀️ Sunday
25° / 28°
<button>Change city</button>
<p>Coded by Matt Delac</p>
<script>
function city() {
let cityName = prompt("What city do you live in?");
let temp = prompt("What temperature is it?");
let heading = document.querySelector("h1");
if (temp <= 0) {
heading.innerHTML = "Currently" + temp + "in" + cityName;
} else {
heading.innerHTML = "Currently" + temp + "in" + cityName;
}
}
let changeCityButton = document.querySelector("button");
changeCityButton.addEventListener("click", city);
</script>
Solution to Question 1
To change the emoji just change the alt and src attribute on an img tag.
Here is the code
function city() {
let cityName = prompt("What city do you live in?");
let temp = prompt("What temperature is it?");
let heading = document.querySelector("h1");
let img = document.querySelector('img');
if (temp <= 0) {
heading.innerHTML = "Currently " + temp + "in" + cityName;
img.setAttribute('alt', 'freezing emoji');
img.setAttribute('src', 'path/to.emoji');
} else {
heading.innerHTML = "Currently" + temp + "in" + cityName;
img.setAttribute('alt', 'not freezing emoji');
img.setAttribute('src', 'path/to.emoji');
}
}
let changeCityButton = document.querySelector("button");
changeCityButton.addEventListener("click", city);
Solution to Question 2
All you need to do to add spacing is to add spaces to the end of the strings.
The JS would look like this
function city() {
let cityName = prompt("What city do you live in?");
let temp = prompt("What temperature is it?");
let heading = document.querySelector("h1");
let img = document.querySelector('img');
if (temp <= 0) {
heading.innerHTML = "Currently " + temp + " in " + cityName;
img.setAttribute('alt', 'freezing emoji');
img.setAttribute('src', 'path/to.emoji');
} else {
heading.innerHTML = "Currently " + temp + " in " + cityName;
img.setAttribute('alt', 'not freezing emoji');
img.setAttribute('src', 'path/to.emoji');
}
}
let changeCityButton = document.querySelector("button");
changeCityButton.addEventListener("click", city);
Here is the link to the codepen.
Related
I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)
I am creating a "Keep Lines containing" project. I almost completed this task. But "Search Lines for" is working only 1 line. Multiple "Search
Lines for" is not working. I need "Search Lines for" in multiple lines.
All used HTML, CSS & javascript codes are here
I created a Codepen page for it. Please check : https://codepen.io/coderco/pen/LYGQyqr
function loadfile(fileid, loadid) {
document.getElementById(loadid).value = 'Loading...';
setTimeout(function() {
loadfile2(fileid, loadid)
}, 1000);
}
function loadfile2(fileid, loadid) {
if (!window.FileReader) {
document.getElementById(loadid).value = 'Your browser does not support HTML5 "FileReader" function required to open a file.';
} else {
fileis = document.getElementById(fileid).files[0];
var fileredr = new FileReader();
fileredr.onload = function(fle) {
var filecont = fle.target.result;
document.getElementById(loadid).value = filecont;
}
fileredr.readAsText(fileis);
}
}
function savefile(saveasid, saveid) {
if (!window.Blob) {
alert('Your browser does not support HTML5 "Blob" function required to save a file.');
} else {
var txtwrt = document.getElementById(saveid).value;
if (document.getElementById('dos').checked == true) txtwrt = txtwrt.replace(/\n/g, '\r\n');
var textblob = new Blob([txtwrt], {
type: 'text/plain'
});
var saveas = document.getElementById(saveasid).value;
var dwnlnk = document.createElement('a');
dwnlnk.download = saveas;
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
} else {
dwnlnk.href = window.URL.createObjectURL(textblob);
dwnlnk.onclick = destce;
dwnlnk.style.display = 'none';
document.body.appendChild(dwnlnk);
}
dwnlnk.click();
}
}
function destce(event) {
document.body.removeChild(event.target);
}
function cleartext() {
document.getElementById('input_output').value = '';
document.getElementById('removed').innerHTML = '';
document.getElementById('removed_box').value = '';
}
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
var fieldnum = 0;
var fieldtype = '';
var cacherem = 'no';
var enableregex = 'no';
function makeregexp() {
var regexpoutarr = new Array();
for (var x = 0; x < (fieldnum + 1); x++) {
regexpoutarr[x] = document.getElementById('addfield' + x).value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
var regexpout = '';
if (fieldtype == 'AND') regexpout = '((?=.*' + regexpoutarr.join(')(?=.*') + ').*)';
if (fieldtype == 'OR') regexpout = '(' + regexpoutarr.join('|') + ')';
if (fieldtype == '') regexpout = document.getElementById('addfield0').value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
return regexpout;
}
function removelines(whatlines) {
var textin = document.getElementById('input_output').value.replace(/\r/g, '');
var toremove = makeregexp();
var textinarr = textin.split('\n');
var textinarrcnt = textinarr.length;
var textoutarr = new Array();
var textoutarrcnt = 0;
var linesremovedcnt = 0;
var casen = 'i';
if (document.getElementById('case_sen').checked == true) casen = '';
if (enableregex == 'yes') toremove = document.getElementById('addfield0').value;
else toremove = makeregexp();
var killfun = 'no';
try {
var toremoveregx = new RegExp(toremove, casen);
} catch (err) {
alert('Something is incorrect (' + err + ') within your regular expression.\nBe sure special characters .*+?^=!:${}()|\\ used as literals have been escaped with a backslash.');
killfun = 'yes';
}
if (killfun == 'no') {
if (whatlines == 'containing' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
if (whatlines == 'notcontaining' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
var removedcachearr = new Array();
if (whatlines == 'containing' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
if (whatlines == 'notcontaining' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
var textout = textoutarr.join('\n');
document.getElementById('input_output').value = textout;
if (cacherem == 'yes') {
var removedcache = removedcachearr.join('\n');
document.getElementById('removed_box').value = removedcache;
}
document.getElementById('removed').innerHTML = '' + linesremovedcnt + ' removed / ' + textoutarrcnt + ' remain.';
}
}
function addfield(field) {
if (field == 'reset') {
document.getElementById('inputfields').innerHTML = '<input type="text" id="addfield0" value="" style="width:100%;" />'
document.getElementById('andbttn').style.display = 'inline-block';
document.getElementById('orbttn').style.display = 'inline-block';
fieldnum = 0;
fieldtype = '';
} else {
fieldnum++;
if (fieldnum == 1) {
if (field == 'andfield') {
document.getElementById('orbttn').style.display = 'none';
fieldtype = 'AND';
} else {
fieldtype = 'OR';
document.getElementById('andbttn').style.display = 'none';
}
}
var newfield = fieldtype + '<input type="text" id="addfield' + fieldnum + '" value="" style="width:100%;" />';
var newdiv = document.createElement('div');
newdiv.innerHTML = newfield;
document.getElementById('inputfields').appendChild(newdiv);
}
resizepage();
}
function disrem() {
var chkedstate = document.getElementById('dremoved').checked;
if (chkedstate == true) {
document.getElementById('removed_box').style.display = 'inline-block';
cacherem = 'yes';
} else {
cacherem = 'no';
document.getElementById('removed_box').value = '';
document.getElementById('removed_box').style.display = 'none';
}
resizepage();
}
function selectele(eleid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(eleid));
range.select();
} else {
var range = document.createRange();
range.selectNode(document.getElementById(eleid));
window.getSelection().addRange(range);
}
}
function regexsrch() {
var chkedstate = document.getElementById('regex_srch').checked;
if (chkedstate == true) {
addfield('reset');
enableregex = 'yes';
document.getElementById('addfielddiv').innerHTML =
'<div style="padding:3px 0px 3px 0px;"><input type="checkbox" id="regex_srch" onclick="regexsrch();" CHECKED />Enable regular expression search. ' +
'Use <span id="catordog" style="color:#990000;" onclick="selectele(this.id)">(cat|dog|bird)</span> for cat OR dog OR bird. Use <span id="catanddog" style="color:#990000;" onclick="selectele(this.id)">((?=.*cat)(?=.*dog)(?=.*bird).*)</span> for cat AND dog AND bird. ' +
'Remember to escape special characters .*+?^=!:${}()|\\ with a backslash when used as literals within a regular expression. Use the <a target="_blank" href="" style="color:#0000FF;">Escape Literal Characters</a> tool. ' +
'Learn more about regular expressions visit <a rel="nofollow" target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" style="color:#0000FF;">developer.mozilla.org</a>.</div>';
} else {
document.getElementById('addfield0').value = '';
enableregex = 'no';
document.getElementById('addfielddiv').innerHTML =
'Add <input type="button" id="andbttn" value="AND" onClick="addfield(\'andfield\');" /> ' +
'<input type="button" id="orbttn" value="OR" onClick="addfield(\'orfield\');" /> search field. ' +
'<input type="button" value="Reset" onClick="addfield(\'reset\');" /> ' +
'<input type="checkbox" id="regex_srch" onclick="regexsrch();" />Enable regular expression search.';
}
resizepage();
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family: arial;
font-size: 16px;
line-height: 1.7;
}
h1 {
display: block;
font-size: 18px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.se-for {
font-size: 27px;
font-weight: bold;
color: #b93207;
padding-top: 54px;
}
.contentt,
.wordd {
display: block;
margin: 0px;
padding: 8px 10px 8px 10px;
overflow: scroll;
font-family: arial;
font-size: 16px;
line-height: 1.7;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border-radius: 4px 4px 4px 4px;
width: 100%;
font-size: 18px;
}
.contentt {
height: 400px;
overflow: auto;
}
.wordd {
height: 99px;
overflow: auto;
}
input {
display: inline-block;
height: 33px;
line-height: 1;
vertical-align: middle;
font-size: 16px;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input::-moz-focus-inner {
border: 0;
padding: 0
}
input[type='radio'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='checkbox'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='text'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
border-radius: 12px;
}
input[type='button'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
font-weight: bold;
color: #000000;
border: 1px solid #000000;
background-color: #FFFFFF;
cursor: pointer;
border-radius: 5px;
background: #b93207;
color: #fff;
border: #b93207;
}
input[type='button']:hover {
color: #f9f900;
}
input[type='button']:hover {}
input[type='file'] {
width: 92px;
border-radius: 12px;
overflow: hidden;
padding: 0px;
margin: 0px 0px 0px -92px;
-moz-opacity: 0;
opacity: 0;
cursor: pointer;
}
input[type='file']::-webkit-file-upload-button {
cursor: pointer;
}
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table,
td {
padding: 0px;
}
.buttonz {
width: 100%;
display: inline-block;
}
#menu {
position: absolute;
z-index: -1;
left: 0px;
top: 0px;
width: 0px;
height: 0%;
margin: 0px;
overflow: auto;
background-color: #E1E1D2;
border-right: 1px solid #000000;
}
div.navcat {
padding: 10px 0px 5px 12px;
font-size: 18px;
font-weight: bold;
font-style: italic;
}
div.navdiv {
height: 2px;
padding: 0px;
margin: 18px 10px 13px 10px;
background-color: #000000;
}
a.nav {
display: inline-block;
padding: 0px;
margin: 10px 0px 10px 10px;
text-decoration: underline;
color: #000000;
}
#toolpadding {
padding: 10px 10px 10px 10px;
}
#tool {
width: 1100px;
margin: 0px;
padding: 0px;
background-color: #fff;
margin: 0 auto;
}
<div id="tool">
<div id="toolpadding">
<div id="topdiv">
<div class="se-for">Search lines for:</div>
<div id="inputfields" style="padding-top:4px;">
<textarea type="text" id="addfield0" class="wordd">Three</textarea>
</div>
<div class="buttonz">
<input type="button" value="Keep Lines Containing" onClick="if(document.getElementById('addfield0').value!='') {removelines('notcontaining');}" />
<input type="checkbox" id="case_sen" />Case sensitive.
</div>
</div>
<div id="middiv" style="height:120px;">
<textarea id="input_output" class="contentt" wrap="off">
One One One One One One One One One One One One One One One
Three Three Three Three Three Three Three Three Three Three
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Three Three Three Three Three Three Three Three Three Three
Three Three Three Three Three Three Three Three Three Three
Four Four Four Four Four Four Four Four Four Four Four Four
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
</textarea>
</div>
<div id="btmdiv">
<textarea id="removed_box" rows="4" style="display:none; width:100%; margin-top:10px;" wrap="off">
Removed Line Box - Removed/extracted lines will display here.</textarea>
</div>
</div>
</div>
I am trying to dynamically change width of a span based on the content of the span, So my app has a lot of span row-wise and the use modify content of the spans. On change of content I am trying to uniform the width of each span to be equal to the maxWidth of all the spans combined.
i.e spanWidths = [ '50px', '34px', '56px', '87px' ]
I need to convert all these spans into -> [ '87px', '87px', '87px', '87px' ]
The box model for the span :
As you can see the width is set to 87px on the span yet, on inspecting it is weirdly 57.98px which is inclusive of the border, padding and content.
The css for the span : (I am using box-sizing: border-box throughout)
.annotation-speaker {
display: inline-block;
font-size: 14px;
line-height: 25px;
background-color: rgb(224, 239, 241, 0.5);
height: 25px;
padding: 0px 5px 6px 5px;
margin-top: 5px;
border-radius: 4px;
font-weight: 500;
letter-spacing: 0.7px;
overflow: hidden;
text-align: center;
}
I am confused as to how should I be calculating the spanWidths array having the widths of all the spans after on modifies the content in the span.
This is what I am currently doing :
const css = getComputedStyle($speakerBox); // $speakerBox is my span
const r = $speakerBox.getBoundingClientRect();
const w = $speakerBox.scrollWidth + parseInt(css.paddingLeft) + parseInt(css.paddingRight);
maxSpeakerTagWidth = Math.max(maxSpeakerTagWidth, w);
Here r.width and $speakerBox.scrollWidth are different too! Am confused as to which one should I even consider!
And to make all span's the same width as maxSpeakerTagWidth :
$speakerBox.style.width = maxSpeakerTagWidth + 'px';
This isn't working though!
I fiddled a bit on JSFiddle (:P), seem to have found myself a solution, but am still not able to see it work on my project, but work's just fine on JSFiddle!
https://jsfiddle.net/a5kurstv/
<html>
<head>
<style>
.spanBox {
font-size: 14px;
line-height: 25px;
background-color: rgb(224, 239, 241, 0.5);
height: 25px;
padding: 0px 5px;
margin-top: 5px;
border-radius: 4px;
font-weight: 500;
letter-spacing: 0.7px;
text-align: center;
display: inline-block;
margin-left: 1em;
box-sizing: content-box;
}
.input {
display: block;
margin-left: 1em;
}
</style>
</head>
<body>
<!-- Just type in the input box press enter -->
<span id="span1" class="spanBox">gg</span>
<span id="span2" class="spanBox">gg</span>
<span id="span3" class="spanBox">gg</span>
<span id="span4" class="spanBox">gg</span>
<span id="span5" class="spanBox">gg</span>
<input onkeypress="change(event)" class="input" />
</body>
<script>
let maxW = -1;
const change = (e) => {
if(e.keyCode === 13) {
const val = e.target.value;
const $span1 = document.getElementById('span1');
$span1.textContent = `${val}`;
calcMax();
}
}
const calcMax = () => {
maxW = -1;
for(let i = 1; i <= 5; i++) {
const $span = document.getElementById(`span${i}`);
if($span.style.width === '') {
const r = $span.getBoundingClientRect();
maxW = Math.max(maxW, r.width);
}
else {
$span.style.width = '1px';
maxW = Math.max(maxW, $span.scrollWidth);
}
}
setTimeout(() => update(), 100);
}
const update = () => {
console.log("MAX ", maxW);
for(let i = 1; i <= 5; i++) {
const $span = document.getElementById(`span${i}`);
$span.style.width = maxW + 'px';
}
}
calcMax();
</script>
<html>
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
I am relatively new to Javascript, but have decided to make a library website as my first project. While making said project, I came across an error when i tried to set innerHTML via values from an array. Here is my (messy) code:
var catalog = [];
function book (title, firstName, lastName, number, publisher, image, checkedOut) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.publisher = publisher;
this.image = image;
this.isCheckedOut = checkedOut;
}
function addToCatalog (entry){
entry.number = catalog.length ;
catalog[entry.number] = entry;
}
$newbook = new book("Lost in the Woods", "Hubert", "Holmes", "3", "Junior Scholastic", "https://marketplace.canva.com/MAB5W63LDsw/1/0/thumbnail_large/canva-woods-thriller-e-book-cover-MAB5W63LDsw.jpg", false);
addToCatalog($newbook);
$newbook = new book("To Kill A Mockingbird", "Harper", "Lee", "1", "Junior Scholastic", "https://s-media-cache-ak0.pinimg.com/736x/a0/96/ff/a096ff3bafb7786b59ef9ba9d3e7ddf2.jpg", false);
addToCatalog($newbook);
var address = document.createElement("DIV");
address.setAttribute("class", "eachBook");
var picture = document.createElement("img");
picture.setAttribute("src", "http://www.iconsdb.com/icons/preview/gray/literature-xxl.png" );
picture.setAttribute("class", "bookImg");
picture.setAttribute("alt", "Auburn Library Book");
var gtitle = document.createElement("h4");
gtitle.setAttribute("class", "bTitle");
var dname = document.createElement("p");
dname.setAttribute("class", "bName");
var button = document.createElement("button");
button.setAttribute("class", "checkout");
checkout = document.createTextNode("Checkout");
button.appendChild(checkout);
//Text in button
var available = document.createElement("p");
available.setAttribute("class", "available");
avail = document.createTextNode("Available");
available.appendChild(avail);
//text in available
function createBooks(){
document.getElementById("displayBooks").appendChild(address);
address.appendChild(picture);
address.appendChild(gtitle);
address.appendChild(dname);
address.appendChild(button);
address.appendChild(available);
}
function write(){
var x = 0;
var arr;
while (x < catalog.length){
createBooks();
arr = document.getElementsByClassName("bTitle");
arr[x].innerHTML = catalog[x].title; //Part A
arr = document.getElementsByClassName("bName");
arr[x].innerHTML = catalog[x].firstName +" "+ catalog[x].lastName;//Part B
arr = document.getElementsByTagName("img");
arr[x].src = catalog[x].image;
x++;
}
}
window.onload = function(){
write();
};
At part A is where I get my error stating "TypeError: Cannot set property 'innerHTML' of undefined". However, I used the alert function and got a value for catalog[0] (Lost in the Woods). It also seems like the code may only fail after the first time through the loop, as I only get it to properly work the first time through. I think it may be innerHTML causing the problem entirely, as when i comment out part A, part B appears to have the same error.
Please help me figure out this mistake, and also (since I am a beginner, both to this site and Javascript), tell me how to approach this problem from a better angle. And please keep the answer beginner-friendly as well (If you can)
You are creating the 'address' element in the parent scope so in createBooks you are appending the same element. Appending the same element removes it then appends it so you cannot have the second div there. That's why your array length is 2 but the number of 'address' DIVs you have is only 1.
Just move your code block starts with
var address = document.createElement("DIV");
inside the createBooks(), before
document.getElementById("displayBooks").appendChild(address);
Here is the runnable snippet:
var catalog = [];
function book (title, firstName, lastName, number, publisher, image, checkedOut) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.publisher = publisher;
this.image = image;
this.isCheckedOut = checkedOut;
}
function addToCatalog (entry){
entry.number = catalog.length ;
catalog[entry.number] = entry;
}
$newbook = new book("Lost in the Woods", "Hubert", "Holmes", "3", "Junior Scholastic", "https://marketplace.canva.com/MAB5W63LDsw/1/0/thumbnail_large/canva-woods-thriller-e-book-cover-MAB5W63LDsw.jpg", false);
addToCatalog($newbook);
$newbook = new book("To Kill A Mockingbird", "Harper", "Lee", "1", "Junior Scholastic", "https://s-media-cache-ak0.pinimg.com/736x/a0/96/ff/a096ff3bafb7786b59ef9ba9d3e7ddf2.jpg", false);
addToCatalog($newbook);
function createBooks(){
var address = document.createElement("DIV");
address.setAttribute("class", "eachBook");
var picture = document.createElement("img");
picture.setAttribute("src", "http://www.iconsdb.com/icons/preview/gray/literature-xxl.png" );
picture.setAttribute("class", "bookImg");
picture.setAttribute("alt", "Auburn Library Book");
var gtitle = document.createElement("h4");
gtitle.setAttribute("class", "bTitle");
var dname = document.createElement("p");
dname.setAttribute("class", "bName");
var button = document.createElement("button");
button.setAttribute("class", "checkout");
checkout = document.createTextNode("Checkout");
button.appendChild(checkout);
//Text in button
var available = document.createElement("p");
available.setAttribute("class", "available");
avail = document.createTextNode("Available");
available.appendChild(avail);
//text in available
document.getElementById("displayBooks").appendChild(address);
address.appendChild(picture);
address.appendChild(gtitle);
address.appendChild(dname);
address.appendChild(button);
address.appendChild(available);
}
function write(){
var x = 0;
var arr;
while (x < catalog.length){
createBooks();
arr = document.getElementsByClassName("bTitle");
arr[x].innerHTML = catalog[x].title;//Part A
arr = document.getElementsByClassName("bName");
arr[x].innerHTML = catalog[x].firstName +" "+ catalog[x].lastName;//Part B
arr = document.getElementsByTagName("img");
arr[x].src = catalog[x].image;
x++;
}
}
window.onload = function(){
write();
};
body {
background-color: #F5EBEB;
}
#header {
background-image: url("http://il2.picdn.net/shutterstock/videos/2990449/thumb/1.jpg") ;
font-family: Rockwell, Tahoma, Arial;
color: #FFFFFF;
display: block;
}
#header p{
font-family: Arial, "Times New Roman";
}
#panel{
background-color: #922724;
font-family: Rockwell, Arial;
padding: 5px 5px 5px 5px;
margin: 5px 5px 5px 5px ;
}
.dropdown{
display: block;
position: relative;
}
.dropbtn{
background-color: #FFFFFF;
border: none;
color: #922724;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
font-family: Rockwell;
font-weight: bold;
}
.dropbtn:hover{
color: #700502;
}
.content{
background-color: #FFFFFF;
border: none;
color: #922724;
padding: 5px 5px;
text-align: center;
text-decoration: none;
font-size: 16px;
font-family: Rockwell;
overflow: auto;
position: relative;
display: none;
}
.content li{
color: black;
display: block;
float: left;
position: relative;
cursor: pointer;
}
.dropdown:hover .content{
display: inline-block;
}
.content li:hover{
background-color: #DDDDDD;
display: block;
}
#displayBooks{
font-family: Rockwell;
border-color: #1B0807;
border-style: solid;
border-width: 3px;
padding: 5px 5px 5px 5px;
margin: 5px 5px 5px 5px ;
}
.eachBook{
font-family: Rockwell;
background-color: #FFFEFF;
border-style: solid none solid none;
border-color: #DDD;
border-width: 2px;
padding: 5px 5px 5px 5px;
margin: 5px 5px 5px 5px ;
overflow: auto;
}
.eachBook h4{
font-size: 20px
}
.bookImg{
width: 150px;
height:225px;
overflow: auto;
float: left;
margin: 5px 5px 5px 5px ;
}
.checkout{
background-color: #DDDDDD;
border: none;
color: #922724;
padding: 5px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
font-family: Rockwell;
font-weight: bold;
}
.checkout:hover{
background-color: #922724;
color: #FFFFFF;
}
.available{
color: #2F2;
font-weight: bold;
}
.unavailable{
color: #F22;
font-weight: bold;
}
<div id="header">
<h1>Welcome to Auburn Library</h1>
<p>Where knowledge is truly power.</p>
</div>
<div id="panel">
<div class="dropdown">
<button class ="dropbtn">Display Books...</button>
<ul class="content">
<li> Alphabeticaly (A - Z) </li>
<li> Alphabeticaly (Z - A)</li>
<li> By Author (A - Z)</li>
<li> By Author (Z - A)</li>
<li> By Number (Low - High)</li>
<li> By Number (High - Low)</li>
</ul>
</div>
<form>
</form>
<!-- Right next to it is a checkbox: only "in" books or all books -->
</div>
<div id="displayBooks">
<h2 style="text-align: center;">Book Catalog </h2>
</div>