how to avoid document.write my below code - javascript

This code is working, but google pagespeed detect avoid document.write.
I've tested various alternatives, lining up my HTML elements prior to the JS, then using getElementById, followed by either innerHTML or appendChild, or even lining up the elements inside the JS, by means of createElement, but to no avail, really. maybe my tested was wrong.
Probably a factor as to why they're doing so poorly. I'm sure I couldn't sort the above codes correctly. I'm basically not experienced in JavaScript.
Here is my CSS/HTML/JS inside this snipet code:
.cat-back {
font-size: 18px;
font-weight: 400;
border-bottom: 1px solid #000;
margin-top: 13px;
margin-bottom: 5px;
padding: 5px;
border-left: 3px solid #000
}
.row:after {
content: "";
display: table;
clear: both
}
.catcol {
float: left;
width: 33.33%;
padding: 10px;
box-sizing: border-box
}
.mbtlist {
list-style-type: none;
overflow: hidden
}
.mbtlist li {
margin: 0px auto 20px auto;
clear: both;
color: #666;
font-family: Helvetica;
font-size: 12px;
border-bottom: 1px dotted #ddd;
padding-bottom: 10px;
}
.mbtlist .mbttitle {
font-family: oswald;
font-size: 16px;
color: #0080ff;
font-weight: normal;
text-decoration: none;
}
.mbtlist .mbttitle:hover {
color: #00A5FF;
}
font-family:georgia;
font-size:15px;
font-weight:bold
}
.mbtlist div span {
margin: 0 10px 0 0;
display: inline-block;
}
.mbtlist span {
display: block;
margin: 5px 0px 0px;
padding-right: 5px;
}
.mbtlist .imore {
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #666;
line-height: 0.7em;
}
.mbtlist img {
float: left;
margin: 0px 10px 10px 0px;
border: 6px solid #fff;
padding: 0px;
width: 80px;
height: 65px;
box-shadow: -1px -1px 4px #777;
}
.mbtlist .icontent {
text-align: justify;
}
<script>
//----------------------------Defaults
var ListBlogLink = window.location.hostname;
var ListCount = 5;
var TitleCount = 70;
var ListLabel = " ";
var ChrCount = 80;
var ImageSize = 100;
//----------------------------Function Start
function mbtlist(json) {
document.write('<ul class="mbtlist">');
for (var i = 0; i < ListCount; i++) {
//-----------------------------Variables Declared
var listing = ListUrl = ListTitle = ListConten = ListContent = ListImage = thumbUrl = sk = "";
//----------------------------- Title URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
ListUrl = "'" + json.feed.entry[i].link[j].href + "'";
//----------------------------------- Title Stirng
if (json.feed.entry[i].title != null) {
ListTitle = json.feed.entry[i].title.$t.substr(0, TitleCount);
}
//----------------------------------- Content Check
ListConten = json.feed.entry[i].content.$t;
ListContent = ListConten.replace(/(<([^>]+)>)/ig, "").substr(0, ChrCount);
//------------------------------------ Thumbnail Check
if (json.feed.entry[i].media$thumbnail) {
thumbUrl = json.feed.entry[i].media$thumbnail.url;
sk = thumbUrl.replace("/s72-c/", "/s" + ImageSize + "/");
ListImage = "'" + sk.replace("?imgmax=800", "") + "'";
}
// Support For 3rd Party Images
else if (json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/) != null) {
ListImage = json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
ListImage = "'http://4.bp.blogspot.com/-HALLtgFeep0/VfryhQ0C5oI/AAAAAAAAPcY/77mSGND4q84/s200/Icon.png'";
}
//----------------------------------- Printing List
var listing = "<li><a href=" +
ListUrl +
"><img src=" +
ListImage +
"/></a><a class='mbttitle' href=" +
ListUrl +
"target='_blank'>" +
ListTitle +
"</a><span class='icontent'>" +
ListContent +
" ... <a href=" +
ListUrl +
" class='imore'>»</a></span></li>";
document.write(listing);
}
document.write("</ul>");
}</script>
<div class='row'>
<div class='catcol'><div class='cat-back'><h3>Seba Top</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "seba-top";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>Lead News</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "lead-news";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>Top News</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "top-news";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
</div>
<div class='row'>
<div class='catcol'><div class='cat-back'><h3>জাতীয়</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "জাতীয়";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>রাজনীতি</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "রাজনীতি";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
<div class='catcol'><div class='cat-back'><h3>বিশ্ব</h3></div></div>
<script>
ListBlogLink = "https://www.sebahotnews.org";
ListCount = 4;
TitleCount = 70;
ListLabel = "বিশ্ব";
ChrCount = 150;
document.write("<script src='" + ListBlogLink + "/feeds/posts/default/-/" + ListLabel + "?alt=json-in-script&callback=mbtlist'></" + "script>");
</script>
</div>
</div>
Would it be possible for anyone to point me to the right direction?
Please solve this problem any one.

So based on new code I suggest this
//----------------------------Defaults
var ListBlogLink = "https://www.sebahotnews.org",
ListCount = 4,
TitleCount = 70,
ChrCount = 150,
ImageSize = 100;
const lists = [{"label":"seba-top" },{"label":"lead-news" },{"label":"top-news" }]
let cnt = 0;
function next() {
if (cnt>=lists.length) return
document.getElementById("container").innerHTML += `<div class='catcol ${lists[cnt].label}'></div>`
const scr = document.createElement("script");
scr.src = ListBlogLink + "/feeds/posts/default/-/" + lists[cnt].label + "?alt=json-in-script&callback=mbtlist";
document.querySelector("head").appendChild(scr);
};
next(); // start
function mbtlist(json) {
let div = document.querySelector("#container ."+lists[cnt].label);
let html = '<ul class="mbtlist">';
for (var i = 0; i < ListCount; i++) {
//-----------------------------Variables Declared
var listing = ListUrl = ListTitle = ListConten = ListContent = ListImage = thumbUrl = sk = "";
//----------------------------- Title URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
ListUrl = "'" + json.feed.entry[i].link[j].href + "'";
//----------------------------------- Title Stirng
if (json.feed.entry[i].title != null) {
ListTitle = json.feed.entry[i].title.$t.substr(0, TitleCount);
}
//----------------------------------- Content Check
ListConten = json.feed.entry[i].content.$t;
ListContent = ListConten.replace(/(<([^>]+)>)/ig, "").substr(0, ChrCount);
//------------------------------------ Thumbnail Check
if (json.feed.entry[i].media$thumbnail) {
thumbUrl = json.feed.entry[i].media$thumbnail.url;
sk = thumbUrl.replace("/s72-c/", "/s" + ImageSize + "/");
ListImage = "'" + sk.replace("?imgmax=800", "") + "'";
}
// Support For 3rd Party Images
else if (json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/) != null) {
ListImage = json.feed.entry[i].content.$t.match(/src=(.+?[\.jpg|\.gif|\.png]")/)[1];
} else {
ListImage = "'http://4.bp.blogspot.com/-HALLtgFeep0/VfryhQ0C5oI/AAAAAAAAPcY/77mSGND4q84/s200/Icon.png'";
}
//----------------------------------- Printing List
var listing = "<li><a href=" +
ListUrl +
"><img src=" +
ListImage +
"/></a><a class='mbttitle' href=" +
ListUrl +
"target='_blank'>" +
ListTitle +
"</a><span class='icontent'>" +
ListContent +
" ... <a href=" +
ListUrl +
" class='imore'>»</a></span></li>";
html += listing;
}
html += "</ul>";
div.innerHTML = html;
cnt++;
next(); // call next
}
.seba-top { background-color:orange;}
.top-news { background-color:tan;}
.lead-news { background-color:yellow;}
.catcol {
float: left;
width: 33.33%;
padding: 10px;
box-sizing: border-box;
border: 1px solid black;
}
.mbtlist {
list-style-type: none;
overflow: hidden
}
.mbtlist li {
margin: 0px auto 20px auto;
clear: both;
color: #666;
font-family: Helvetica;
font-size: 12px;
border-bottom: 1px dotted #ddd;
padding-bottom: 10px;
}
.mbtlist .mbttitle {
font-family: oswald;
font-size: 16px;
color: #0080ff;
font-weight: normal;
text-decoration: none;
}
.mbtlist .mbttitle:hover {
color: #00A5FF;
}
font-family:georgia;
font-size:15px;
font-weight:bold
}
.mbtlist div span {
margin: 0 10px 0 0;
display: inline-block;
}
.mbtlist span {
display: block;
margin: 5px 0px 0px;
padding-right: 5px;
}
.mbtlist .imore {
font-size: 16px;
font-weight: bold;
text-decoration: none;
color: #666;
line-height: 0.7em;
}
.mbtlist img {
float: left;
margin: 0px 10px 10px 0px;
border: 6px solid #fff;
padding: 0px;
width: 80px;
height: 65px;
box-shadow: -1px -1px 4px #777;
}
.mbtlist .icontent {
text-align: justify;
}
<div id="container"></div>

Related

HTML CSS and JAVASCRIPT

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.

Put automatic sub-heading on my table of content

I want automatic sub-headings, can anyone help me?
I just learn DOM property yesterday .I am just familiar with HTML css.
function bttext() {
var btn = document.getElementById("bttext");
if (btn.innerText == "show") {
btn.innerText = "hide";
} else {
btn.innerText = "show";
}
var x = document.getElementById("hide");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var hsub = sub = s = htoc = i = hl = gh = 0;
hl = document.getElementById("p-toc").getElementsByTagName("h2").length;
for (i = 0; i < hl; i++) {
gh = document.getElementById("p-toc").getElementsByTagName("h2")[i].innerText;
document.getElementById("p-toc").getElementsByTagName("h2")[i].setAttribute("id", "point" + i);
htoc = "<li><a href='#point" + i + "'>" + gh + "</a></li>";
document.getElementById("htoc").innerHTML += htoc;
}
hsub = document.getElementById("p-toc").getElementsByTagName("h3").length;
for (s = 0; s < hsub; s++) {
sub = document.getElementById("p-toc").getElementsByTagName("h3")[i].innerText;
document.getElementById("p-toc").getElementsByTagName("h3")[i].setAttribute("id", "sub" + i);
stoc = "<li><a href='#sub" + i + "'>" + sub + "</a></li>";
document.getElementById("stoc").innerHTML += stoc;
}
//*************TOC plugin by MyBloggerTricks.com
function mbtTOC() {
var mbtTOC = i = headlength = gethead = 0;
headlength = document.getElementById("post-toc").getElementsByTagName("h2").length;
for (i = 0; i < headlength; i++) {
gethead = document.getElementById("post-toc").getElementsByTagName("h2")[i].textContent;
document.getElementById("post-toc").getElementsByTagName("h2")[i].setAttribute("id", "point" + i);
mbtTOC = "<li><a href='#point" + i + "'>" + gethead + "</a></li>";
document.getElementById("mbtTOC").innerHTML += mbtTOC;
}
}
function mbtToggle() {
var mbt = document.getElementById('mbtTOC');
if (mbt.style.display === 'none') {
mbt.style.display = 'block';
} else {
mbt.style.display = 'none';
}
}
.toc {
border: 3px solid #A2A9B1;
background-color: #F8F9FA;
display: block;
line-height: 1.4em;
width: 70%;
display: block;
padding: 20px 30px 10px;
border-radius: 5px;
}
.toc button {
background-color: inherit;
font-size: 16px;
outline: none;
border: none;
padding: 0px 0px 10px;
color: blue;
}
.toc span {
font-size: 20px;
}
.toc ol>li {
counter-increment: item;
}
.toc ol>li:first-child {
counter-reset: item;
}
.toc ol ol>li {
display: block;
}
.toc ol ol>li:before {
content: counters(item, ".") ". ";
margin-left: -20px;
}
.e {
height: 500px;
margin: 40px;
}
<div id="p-toc">
<div class="toc">
<span>Contents [ <button id="bttext" onclick="bttext();">hide</button> ] </span>
<div id="hide">
<ol id="htoc">
</ol>
</div>
</div>
<div class="e">
new
</div>
<h2>sameer</h2>
<h3>sameer 111</h3>
<h3>sameer 1big11</h3>
<h3>sameer small</h3>
<div class="e">
new
</div>
<h2>sameer lai susu ayo</h2>
<div class="e">
new
</div>
<h2>sameer ko big ass</h2>
<div class="e">
new
</div>
<h2>sameer ko fly jatro brain</h2>
</div>
Please have a look at querySelectorAll
function bttext() {
var btn = document.getElementById("bttext");
btn.innerText = btn.innerText == "show" ? "hide" : "show";
var x = document.getElementById("hide");
x.style.display = x.style.display === "none" ? "block" : "none";
}
let htoc = [...document.querySelectorAll("#p-toc h2")].map((header, i) => {
const gh = header.innerText;
header.setAttribute("id", "point" + i);
return "<li><a href='#point" + i + "'>" + gh + "</a></li>";
})
document.getElementById("htoc").innerHTML = htoc.join("");
/* no stoc in page
let stoc = [...document.querySelectorAll("#p-toc h3")].map((header, i) => {
const gh = header.textContent;
header.setAttribute("id", "sub" + i);
return "<li><a href='#sub" + i + "'>" + gh + "</a></li>";
})
document.getElementById("stoc").innerHTML = stoc.join("");
*/
.toc {
border: 3px solid #A2A9B1;
background-color: #F8F9FA;
display: block;
line-height: 1.4em;
width: 70%;
display: block;
padding: 20px 30px 10px;
border-radius: 5px;
}
.toc button {
background-color: inherit;
font-size: 16px;
outline: none;
border: none;
padding: 0px 0px 10px;
color: blue;
}
.toc span {
font-size: 20px;
}
.toc ol>li {
counter-increment: item;
}
.toc ol>li:first-child {
counter-reset: item;
}
.toc ol ol>li {
display: block;
}
.toc ol ol>li:before {
content: counters(item, ".") ". ";
margin-left: -20px;
}
.e {
height: 500px;
margin: 40px;
}
<div id="p-toc">
<div class="toc">
<span>Contents [ <button id="bttext" onclick="bttext();">hide</button> ] </span>
<div id="hide">
<ol id="htoc">
</ol>
</div>
</div>
<div class="e">
new
</div>
<h2>sameer</h2>
<h3>sameer 111</h3>
<h3>sameer 1big11</h3>
<h3>sameer small</h3>
<div class="e">
new
</div>
<h2>sameer lai susu ayo</h2>
<div class="e">
new
</div>
<h2>sameer ko big ass</h2>
<div class="e">
new
</div>
<h2>sameer ko fly jatro brain</h2>
</div>

jquery popups instance duplication problem

can someone take a look at the code here is the problem screenshot
enter image description here
when clicking on sidebar user a popup appears after clicking on popup header it will go down and then if someone will click on the same user from sidebar a duplicate instance is created and click on the head will make the first one appear and 2nd one to go down.
I want to stop that duplication when someone clicks on sidebar user again then the already generated popup will toggle.
https://jsfiddle.net/hamzasgd/Lqyajokp/4/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Facebook like chat popup layout</title>
</head>
<body>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>
</body>
</html>
$(document).ready(function(){
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel") ;
$('[rel="'+chatbox+'"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel") ;
$('[rel="'+chatbox+'"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>'+
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox(){
i = 270 ; // start position
j = 260; //next position
$.each( arr, function( index, value ) {
if(index < 4){
$('[rel="'+value+'"]').css("right",i);
$('[rel="'+value+'"]').show();
i = i+j;
}
else{
$('[rel="'+value+'"]').hide();
}
});
}
});
I've added a check that will look if you already have a chatbox with that userID:
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
}
Please note that you have some invalid html. You are not allowed, to have the id on multiple element.
Demo
$(document).ready(function() {
var arr = []; // List of users
$(document).on('click', '.msg_head', function() {
var chatbox = $(this).parents().attr("rel");
$('[rel="' + chatbox + '"] .msg_wrap').slideToggle('slow');
return false;
});
$(document).on('click', '.close', function() {
var chatbox = $(this).parents().parents().attr("rel");
$('[rel="' + chatbox + '"]').hide();
arr.splice($.inArray(chatbox, arr), 1);
displayChatBox();
return false;
});
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text();
if ($.inArray(userID, arr) != -1) {
arr.splice($.inArray(userID, arr), 1);
}
var exist = $('.msg_box[rel="' + userID + '"]').length;
if (exist == 0) {
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="' + userID + '">' +
'<div class="msg_head">' + username +
'<div class="close">x</div> </div>' +
'<div class="msg_wrap"> <div class="msg_body"> <div class="msg_push"></div> </div>' +
'<div class="msg_footer"><textarea class="msg_input" rows="4"></textarea></div> </div> </div>';
$("body").append(chatPopup);
displayChatBox();
} else {
$('.msg_box[rel="' + userID + '"] .msg_wrap').slideToggle('slow');
}
});
$(document).on('keypress', 'textarea', function(e) {
if (e.keyCode == 13) {
var msg = $(this).val();
$(this).val('');
if (msg.trim().length != 0) {
var chatbox = $(this).parents().parents().parents().attr("rel");
$('<div class="msg-right">' + msg + '</div>').insertBefore('[rel="' + chatbox + '"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
}
}
});
function displayChatBox() {
i = 270; // start position
j = 260; //next position
$.each(arr, function(index, value) {
if (index < 4) {
$('[rel="' + value + '"]').css("right", i);
$('[rel="' + value + '"]').show();
i = i + j;
} else {
$('[rel="' + value + '"]').hide();
}
});
}
});
/**** Chat Popup Layout******/
body {
background: #e5e5e5;
font-family: sans-serif;
}
.msg_box {
position: fixed;
bottom: -5px;
width: 250px;
background: white;
border-radius: 5px 5px 0px 0px;
}
.msg_head {
background: black;
color: white;
padding: 8px;
font-weight: bold;
cursor: pointer;
border-radius: 5px 5px 0px 0px;
}
.msg_body {
background: white;
height: 200px;
font-size: 12px;
padding: 15px;
overflow: auto;
overflow-x: hidden;
}
.msg_input {
width: 100%;
height: 55px;
border: 1px solid white;
border-top: 1px solid #DDDDDD;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.close {
float: right;
cursor: pointer;
}
.minimize {
float: right;
cursor: pointer;
padding-right: 5px;
}
.msg-left {
position: relative;
background: #e2e2e2;
padding: 5px;
min-height: 10px;
margin-bottom: 5px;
margin-right: 10px;
border-radius: 5px;
word-break: break-all;
}
.msg-right {
background: #d4e7fa;
padding: 5px;
min-height: 15px;
margin-bottom: 5px;
position: relative;
margin-left: 10px;
border-radius: 5px;
word-break: break-all;
}
/**** Slider Layout Popup *********/
#chat-sidebar {
width: 250px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #b2b2b2;
}
#sidebar-user-box {
padding: 4px;
margin-bottom: 4px;
font-size: 15px;
font-family: Calibri;
font-weight: bold;
cursor: pointer;
}
#sidebar-user-box:hover {
background-color: #999999;
}
#sidebar-user-box:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
img {
width: 35px;
height: 35px;
border-radius: 50%;
float: left;
}
#slider-username {
float: left;
line-height: 30px;
margin-left: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat-sidebar">
<div id="sidebar-user-box" class="100">
<img src="user.png" />
<span id="slider-username">User 1</span>
</div>
<div id="sidebar-user-box" class="200">
<img src="user.png" />
<span id="slider-username">User 2</span>
</div>
</div>

JavaScript-produced elements not working

I am making a game so I stared at it for awhile (and yes, I did look at the developer log console for errors), and found no errors (within my reasoning) of why it wouldn't open a battle function.
It is saying that for whatever reason that Giant is not defined when clicked, Zombie is not defined when clicked, and for Giant Spider it says something along the lines of missing parameter. I am quite sure it falls down to the code below -->
for(var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
}
If you wish to look at all the code look below. And if you're wondering why everything is so small it's because I'm making it on my phone, and transferred it to ask via GitHub.
var monsters = []; //All monsters are stored here
//All types of monsters are listed below
monsters.push(new monster_prototype("Giant", 50, 30, 1, 20, 20));
monsters.push(new monster_prototype("Giant spider", 20, 50, 1, 15, 30));
monsters.push(new monster_prototype("Zombie", 50, 50, 2, 40, 70));
for (var z = 0; z < monsters.length; z++) {
Gid("atkOpt_container").innerHTML += ("<div onclick='battle(" + monsters[z].name + "," + this.value + ")' class='monsterContainer' value=" + z + "><div class='monsterT'>" + monsters[z].name + "</div><table><tr><td>Strength</td><td>Health</td><td>XP</td><td>Level</td></tr><tr><td>" + monsters[z].dmg + "</td><td>" + monsters[z].hp + "</td><td>" + monsters[z].xp + "</td><td>" + monsters[z].lvl + "</td></tr></table></div>");
} //Where I believe the error occurs, it basically loads all monster stats into a div
function Gid(id) {
return document.getElementById(id);
} //So I don't have to write the whole document.getElementById
function monster_prototype(name, hp, dmg, lvl, xp, money) {
this.name = name;
this.hp = hp;
this.dmg = dmg;
this.lvl = lvl;
this.xp = xp,
this.money = money;
} //How I store the monsters info
function save() {
localStorage.player = JSON.stringify(playerStats);
}
var playerStats = {
lvl: 1,
xp: 0,
xpToLvl: 100,
name: null,
dmg: null,
hp: null,
money: 100
};
if (localStorage.player === undefined) {
save();
playerSetup();
} else {
playerStats = JSON.parse(localStorage.player);
alert("Welcome back " + playerStats.name);
refreshStats();
} //Checks if the player is new, and if so starts the main player setup. If not it loads it
function refreshStats() {
Gid("maxDmg").innerHTML = "Max damage: " + playerStats.dmg;
Gid("hp").innerHTML = "Health: " + playerStats.hp;
} //Refreshes some stats
function playerSetup() {
document.getElementById("mainContainer").style.display = "none";
$("#class_container").show();
}
function classChosen(pClass) {
if (pClass === "Juggernaut") {
playerStats.hp = 100;
playerStats.dmg = 10;
} else if (pClass === "Average Joe") {
playerStats.hp = 60;
playerStats.dmg = 30;
} else {
playerStats.hp = 40;
playerStats.dmg = 70;
}
refreshStats();
document.getElementById("class_container").style.display = "none";
var getName = prompt("What is your name?");
playerStats.name = getName;
document.getElementById("mainContainer").style.display = "block";
save();
} //Starts the class choosing feature
function toggle(id) {
$("#" + id).toggle();
} //Toggles display (Hidden or block)
function restartGame() {
localStorage.removeItem('player');
location.reload();
}
function battle(enemy, enemyLoc) {
console.log(enemy + " and " + enemyLoc);
enemy = enemy.toLowerCase();
Gid("attackInfo").innerHTML = "";
var battleWords = ['slashed', 'bashed', 'stabbed', 'punched'];
var enemyHp = monsters[enemyLoc].hp;
var enemyDmg = monsters[enemyLoc].dmg;
var playerHp = playerStats.hp;
var playerDmg = playerStats.dmg;
var battleLoop = setInterval(function() {
var atkName1 = Math.floor(Math.random() * battleWords.length);
var atkName2 = Math.floor(Math.random() * battleWords.length);
var enemyDealt = Math.round(Math.random() * enemyDmg);
var playerDealt = Math.round(Math.random() * enemyDmg);
playerHp -= enemyDealt;
enemyHp -= playerDealt;
Gid("attackInfo").innerHTML += ("<strong>•</strong>" + enemy + " " + battleWords[atkName1] + " you and dealt " + enemyDealt + " damage to you and you now have " + playerHp + " health remaining.<br>You " + battleWords[atkName2] + " the " + enemy + " and dealt " + playerDealt + " damage. The " + enemy + " has " + enemyHp + " health remaining.<br><br>");
if (enemyHp <= 0 && playerHp <= 0) {
clearInterval(battleLoop);
alert("You both died at the same time! A win... but mainly a loss. Game over");
restartGame();
} else if (enemyHp <= 0) {
clearInterval(battleLoop);
alert("You won!");
playerStats.money += monsters[enemyLoc].money;
playerStats.xp += monsters[enemyLoc].xp;
if (playerStats.xp >= playerStats.xpToLvl) levelUp();
} else if (playerHp <= 0) {
alert("Game over");
clearInterval(battleLoop);
restartGame();
}
}, 1000);
} //Main battle, this is the function that won't load
function levelUp() {
} //TBA
#container {
background-color: gray;
width: 300px;
height: 350px;
margin: auto;
}
#atkOpt_container {
display: none;
}
#attackBtn {
background-color: black;
width: 96px;
color: yellow;
border: 4px groove red;
float: left;
font-size: 30px;
text-align: center;
display: block;
margin-top: 5px;
margin-left: 5px;
}
#attackInfo {
float: left;
background-color: #eee;
width: 200px;
font-size: 10px;
height: 250px;
clear: left;
display: block;
margin-top: 5px;
margin-left: 5px;
border: 2px solid red;
}
#class_container {
z-index: 10;
display: none;
width: 300px;
height: 150px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: orange;
overflow: auto;
border: 5px groove black;
}
.playerClass {
margin: auto;
width: 200px;
border: 5px groove red;
color: #00FF00;
font-size: 35px;
text-align: center;
margin-bottom: 5px;
display: block;
background-color: black;
}
#title {
width: 95%;
background-color: black;
color: #00FF00;
border: 1px solid orange;
font-size: 25px;
font-weight: bolder;
text-align: center;
margin: auto;
}
#atkOpt_container {
z-index: 11;
width: 275px;
height: 300px;
overflow: auto;
background-color: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border: 2px solid orange;
}
.monsterContainer {
width: 200px;
margin: auto;
text-align: center;
background-color: orange;
border: 5px groove red;
margin-bottom: 5px;
}
.monsterT {
width: 100%;
background-color: black;
color: #eee;
font-size: 30px;
text-align: center;
}
td {
background-color: Cyan;
font-size: 15px;
width: 49%;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="class_container">
<div id="title">Choose a class</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Juggernaut</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Masculine Mat</div>
<div onclick="classChosen(this.innerHTML)" class="playerClass">Average Joe</div>
</div>
<div id="mainContainer">
<div id="container">
<div id="attackBtn" onclick="toggle('atkOpt_container'); toggle('mainContainer');">Attack</div>
<div id="attackInfo"></div>
<div id="maxDmg">Max damage: 0</div>
<div id="hp">Health: 0</div>
</div>
<button onclick="restartGame();">Delete stats</button>
</div>
<div id="atkOpt_container"></div>
</body>
</html>
Because
"<div onclick='battle(" + monsters[z].name + "," + this.value + ")'
produces
<div onclick='battle(whatever, whatever)'
Which is wrong, because you do not have quotes around the strings. You need to quote them. So add in the "
"<div onclick='battle(\"" + monsters[z].name + "\",\"" + this.value + "\")'
Ideally you would use DOM methods such as createElement and addEventListener so you would not have to deal with this.

Why is append() not attaching itself to a div but it is appending to the heading h2

In the below code, why aren't the values in the array appending to the div element but I am able to append it to the heading? I am storing semicolon separated values in a local storage, then splitting each item and appending it to the div.
<!DOCTYPE html>
<html>
<head>
<title>To do</title>
<style type="text/css">
html {
overflow-y: scroll;
}
body {
padding: 0px;
margin: 0px;
font-family: Verdana, Geneva, sans-serif
}
h2 {
color: black;
text-align: center
}
#omnibox {
margin-left: 400px;
height: 30px;
width: 500px;
font-size: 14px;
padding: 10px;
position: center;
}
#searchWrapper {
margin-left: 500px
}
/*#omnibox,#listWrapper{margin:20px;position:center}*/
.searchable {
color: white;
display: block;
padding: 10px;
font-size: 16px;
background: #4298E8;
width: 300px;
margin-bottom: 10px
}
.searchable:hover {
background-color: #E8C420;
}
.delete {
display: block;
float: right;
height: 20px;
width: 20px;
line-height: 20px;
border-radius: 10px;
background-color: black;
color: white;
text-align: center;
font-size: 1em;
transform: rotate(-45deg);
}
.delete:hover {
background-color: #D8FFF1;
color: red;
cursor: pointer;
}
.comments {
margin-left: -10px;
margin-top: 10px;
width: 310px;
display: inline-block
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
console.log('ready');
$(function() {
// body...
$('#omnibox').focus();
if (window.localStorage) {
localStorage.setItem(1,"how do;you do");
localStorage.setItem(2,"ok;got it");
myList();
function myList() {
var list = "";
console.log('Items in Local Storage = ' + localStorage.length);
document.querySelector('h2').innerHTML = "To do - " + localStorage.length;
for (var i = localStorage.length - 1; i >= 0; i--) {
var itemKey = localStorage.key(i);
var values = new Array();
values = localStorage.getItem(itemKey);
values = values.split(";");
console.log("Array - " + values + " Items - " + values.length);
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/></div>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
//Why doesn't this work?
$("#itemKey").append(myComments);
//This works though.
$("h2").append(myComments);
}
$("#listWrapper").html(list);
}
var todo = document.querySelector('#omnibox');
$('#omnibox').keyup(function(e) {
document.querySelector('.errorMessage').innerHTML = "";
if (e.keyCode == 13) {
var todoVal = document.querySelector('#omnibox').value;
if (!todoVal.match(/\S/)) {
console.log('Empty value entered.');
document.querySelector('.errorMessage').innerHTML = "Enter something!";
return false;
} else {
console.log("Some value entered.");
$(this).trigger("enterKey");
var remember = new Array();
myNote = document.querySelector('#omnibox').value;
$('#omnibox').val("");
document.location.reload(true);
return true;
}
}
});
}
});
</script>
</head>
<body>
<h2></h2>
<div id='searchWrapper'>
<div id="listAddWrapper">
<div id="empty"></div>
</div>
<div id="listWrapper">
</div>
</div>
</body>
</html>
You can't use a selector to find an element before you've added it to the DOM. Even if you could, your selector is wrong — it should be "#" + itemKey. But that doesn't matter because it won't work anyway; the element it would match is still just part of that list string you're building.
Looking at your code, I think the best thing to do is to add the comments to the text while you're building it.
list += "<div class='searchable' id='" + itemKey + "'><span class='note'>" + itemKey + " " + values[0] + " </span><input type='text' class='comments' placeholder='Comments.'><br/>";
var myComments = ""
for (var j = values.length - 1; j >= 0; j--) {
console.log("Element - " + values[j] + " parentNode is " + itemKey);
myComments += '<span>' + ' ' + values[j] + ' ' + '</span>';
};
list += myComments + "</div>";

Categories