clearInterval() won't be triggered if setInterval() button is clicked multiple times - javascript

I'm playing around with a Colour Generator app and I added a "disco" function which will trigger random colours to "flash" to the rythm of a song. By the way, you won't be able to hear it but it's "Turn down for what" :))
Everything works, but: If I click multiple times the "Disco" button, setInterval() will accelerate (which I don't mind, in fact I like it), but it won't be cleared no more once I decide to stop it by scrolling or swiping on mobile.
I read multiple similar questions here, but none had a similar problem, and I really have no clue of what I could do.
I'd like to make it accelerate if clicked multiple times, but I also want to be able to clear it.
let button = document.querySelector('.button')
let body = document.querySelector('.body')
let container = document.querySelector('.container')
let disco = document.querySelector('.disco')
let song = document.querySelector('.song')
button.addEventListener('click', ()=> {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
document.querySelector('.color').innerText = 'rgb (' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
button.style.border = 'none'
document.querySelector('.scrollto').style.display = 'block'
disco.style.display = 'none'
})
let dance = function() {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
}
let dancing;
let stopping;
disco.addEventListener('click', ()=> {
document.querySelector('.scrollto').style.display = 'block'
dancing = setInterval(dance,300)
stopping = setTimeout(function() {
clearInterval(dancing)
button.style.display = 'block'
body.style.background = 'white'
document.querySelector('.scrollto').style.display = 'none'
}, 15400)
if(song.paused) {
song.play()
button.style.display = 'none'
}
})
window.addEventListener('touchmove', ()=> {
body.style.background = 'white'
document.querySelector('.color').innerText = ''
document.querySelector('.scrollto').style.display = 'none'
button.style.border = '1px solid black'
clearInterval(dancing)
clearTimeout(stopping)
song.pause()
song.currentTime = 0
button.style.display = 'block'
disco.style.display = 'block'
})
.button {
font-family: 'Poppins', sans-serif;
border-radius: .5em;
padding: .3em .7em;
font-size: 1.1em;
position: relative;
background: white;
mix-blend-mode: screen;
border: 1px solid black;
}
.color {
font-family: 'Poppins', sans-serif;
color: white;
text-shadow: 1px 1px 3px black;
letter-spacing: 1px;
}
.container {
text-align: center;
position: absolute;
top: 40vh;
left: 50vw;
transform: translate(-50%, -50%);
}
.scrollto {
position: absolute;
bottom: 10px;
left: 50vw;
transform: translateX(-50%);
font-family: 'Poppins', sans-serif;
font-size: .7em;
display: none;
}
.disco {
position: absolute;
bottom: 5px;
right: 10px;
font-family: 'Poppins', sans-serif;
font-size: .8em;
border: .5px solid black;
border-radius: .3em;
padding: 0 .3em;
padding-top: .1em;
}
<body class="body">
<div class="container">
<h3 class="button">Generate Colour</h3>
<p class="color"></p>
</div>
<div class="line">
<p class="scrollto">swipe on screen to reset</p>
</div>
<h3 class="disco">Disco</h3>
<audio class="song" src="song.mp3"></audio>

It is because you change the content of the dancing variable at each click. Means that at click 1 it will reference the setInterval1, at click 2 setInterval2 etc. then when you try to do clearInterval you actually clear only the last reference you created.
You can avoid it by simply clearing the old interval before to add a new one:
(I changed the stop event to right click, for example purpose )
let button = document.querySelector('.button')
let body = document.querySelector('.body')
let container = document.querySelector('.container')
let disco = document.querySelector('.disco')
let song = document.querySelector('.song')
button.addEventListener('click', ()=> {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
document.querySelector('.color').innerText = 'rgb (' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
button.style.border = 'none'
document.querySelector('.scrollto').style.display = 'block'
disco.style.display = 'none'
})
let dance = function() {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
}
let dancing;
let stopping;
disco.addEventListener('click', ()=> {
document.querySelector('.scrollto').style.display = 'block'
clearInterval(dancing);
clearTimeout(stopping)
dancing = setInterval(dance,300)
stopping = setTimeout(function() {
clearInterval(dancing)
button.style.display = 'block'
body.style.background = 'white'
document.querySelector('.scrollto').style.display = 'none'
}, 15400)
if(song.paused) {
//song.play()
button.style.display = 'none'
}
})
window.addEventListener('contextmenu', ()=> {
body.style.background = 'white'
document.querySelector('.color').innerText = ''
document.querySelector('.scrollto').style.display = 'none'
button.style.border = '1px solid black'
clearInterval(dancing)
clearTimeout(stopping)
song.pause()
song.currentTime = 0
button.style.display = 'block'
disco.style.display = 'block'
})
.button {
font-family: 'Poppins', sans-serif;
border-radius: .5em;
padding: .3em .7em;
font-size: 1.1em;
position: relative;
background: white;
mix-blend-mode: screen;
border: 1px solid black;
}
.color {
font-family: 'Poppins', sans-serif;
color: white;
text-shadow: 1px 1px 3px black;
letter-spacing: 1px;
}
.container {
text-align: center;
position: absolute;
top: 40vh;
left: 50vw;
transform: translate(-50%, -50%);
}
.scrollto {
position: absolute;
bottom: 10px;
left: 50vw;
transform: translateX(-50%);
font-family: 'Poppins', sans-serif;
font-size: .7em;
display: none;
}
.disco {
position: absolute;
bottom: 5px;
right: 10px;
font-family: 'Poppins', sans-serif;
font-size: .8em;
border: .5px solid black;
border-radius: .3em;
padding: 0 .3em;
padding-top: .1em;
}
<body class="body">
<div class="container">
<h3 class="button">Generate Colour</h3>
<p class="color"></p>
</div>
<div class="line">
<p class="scrollto">swipe on screen to reset</p>
</div>
<h3 class="disco">Disco</h3>
<audio class="song" src="song.mp3"></audio>
EDIT:
From the comments, I see that you want to keep the accelerating effect:
let button = document.querySelector('.button')
let body = document.querySelector('.body')
let container = document.querySelector('.container')
let disco = document.querySelector('.disco')
let song = document.querySelector('.song')
button.addEventListener('click', ()=> {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
document.querySelector('.color').innerText = 'rgb (' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
button.style.border = 'none'
document.querySelector('.scrollto').style.display = 'block'
disco.style.display = 'none'
})
let dance = function() {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
body.style.background = 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree
+ ')'
}
let dancing;
let stopping;
let speed = 300;
const accFactor = 1.5;
disco.addEventListener('click', ()=> {
document.querySelector('.scrollto').style.display = 'block'
if(dancing) {
clearInterval(dancing);
clearTimeout(stopping);
speed = speed/accFactor;
}
dancing = setInterval(dance,speed);
stopping = setTimeout(function() {
clearInterval(dancing)
button.style.display = 'block'
body.style.background = 'white'
document.querySelector('.scrollto').style.display = 'none'
}, 15400)
if(song.paused) {
//song.play()
button.style.display = 'none'
}
})
window.addEventListener('contextmenu', ()=> {
body.style.background = 'white'
document.querySelector('.color').innerText = ''
document.querySelector('.scrollto').style.display = 'none'
button.style.border = '1px solid black'
clearInterval(dancing)
clearTimeout(stopping)
song.pause()
song.currentTime = 0
button.style.display = 'block'
disco.style.display = 'block'
})
.button {
font-family: 'Poppins', sans-serif;
border-radius: .5em;
padding: .3em .7em;
font-size: 1.1em;
position: relative;
background: white;
mix-blend-mode: screen;
border: 1px solid black;
}
.color {
font-family: 'Poppins', sans-serif;
color: white;
text-shadow: 1px 1px 3px black;
letter-spacing: 1px;
}
.container {
text-align: center;
position: absolute;
top: 40vh;
left: 50vw;
transform: translate(-50%, -50%);
}
.scrollto {
position: absolute;
bottom: 10px;
left: 50vw;
transform: translateX(-50%);
font-family: 'Poppins', sans-serif;
font-size: .7em;
display: none;
}
.disco {
position: absolute;
bottom: 5px;
right: 10px;
font-family: 'Poppins', sans-serif;
font-size: .8em;
border: .5px solid black;
border-radius: .3em;
padding: 0 .3em;
padding-top: .1em;
}
<body class="body">
<div class="container">
<h3 class="button">Generate Colour</h3>
<p class="color"></p>
</div>
<div class="line">
<p class="scrollto">swipe on screen to reset</p>
</div>
<h3 class="disco">Disco</h3>
<audio class="song" src="song.mp3"></audio>

Related

JQUERY - Drag & Drop file input replaces previous added files

Im making an user generated music playlist. The user drops files / adds files with the button.
However, whenever more files are dropped / added, the previously added files are replaced.
How to modify code to append the files with the previously added files?
PS:
I have used jquery to build the app. I have used jquery, cos i want to work with audio time duration(to find total playtime of the playlist, etc) and its a bit difficult to accomplish that with vanillaJS.
var dropZoneId = "drop-zone";
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = $("#" + dropZoneId);
var inputFile = dropZone.find("input");
var finalFiles = {};
var objectUrl;
// Function
$(function() {
var ooleft = dropZone.offset().left;
var ooright = dropZone.outerWidth() + ooleft;
var ootop = dropZone.offset().top;
var oobottom = dropZone.outerHeight() + ootop;
document.getElementById(dropZoneId).addEventListener("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
dropZone.addClass(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
if (buttonId != "") {
var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left;
var oright = clickZone.outerWidth() + oleft;
var otop = clickZone.offset().top;
var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) {
var x = e.pageX;
var y = e.pageY;
if (!(x < oleft || x > oright || y < otop || y > obottom)) {
inputFile.offset({
top: y - 15,
left: x - 160
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
});
}
document.getElementById(dropZoneId).addEventListener("drop", function(e) {
$("#" + dropZoneId).removeClass(mouseOverClass);
}, true);
// FILE
inputFile.on('change', function(e) {
finalFiles = {};
$('#filename').html("");
var fileNum = this.files.length,
initial = 0,
counter = 0;
$.each(this.files, function(idx, elm) {
finalFiles[idx] = elm;
});
for (initial; initial < fileNum; initial++) {
counter = counter + 1;
// Object URL
var file = e.currentTarget.files[initial];
objectUrl = URL.createObjectURL(file);
$("#filename").prop("src", objectUrl);
//console.log('Object URL: ', objectUrl);
//console.log('FILE: ', file);
// Object URL End
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>');
$('#filename').append('<div class="playlist draggable" id="file_' + initial + '"><span class="fa-stack fa-lg"><i class="fa fa-file-audio-o"></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + '</strong></span> ' + '<audio controls controlsList="nodownload noplaybackrate" preload="auto" id="audioFiles" >' + '<source src="' + objectUrl + '" type="audio/mpeg" />' + '</audio>' + '<span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span> ' + this.files[initial].name + '</div>');
//$('#filename').append('<div class="playlist draggable" id="file_' + initial + '">' + '<audio controls id="audioFiles" >' + '<source src="' + objectUrl + '/' + this.files[initial].name + '" type="audio/mpeg" />' + '</audio>' + '</div>');
console.log('NAME: ', this.files[initial].name);
//console.log('INITIAL: ', this.files[initial]);
// Audio Duration
var Duration;
$(audioFiles).on("canplay", function() {
console.log('THIS DURATION: ', this.duration);
Duration = this.duration;
});
// Audio Duration End
}
// Total File Count
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').css("display", "initial");
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
// End Total File Count
});
})
function removeLine(obj) {
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
URL.revokeObjectURL(objectUrl);
// Total Files
var count = $('#filename').children().length;
console.log('Number of files: ', count);
$('#totalFiles').html('<font style="color:#06a7e5">Files Uploaded: ' + '<b>' + count + '</b>' + '</font>');
if (count == 0) {
$('#totalFiles').css("display", "none");
} else {}
}
// Draggable Items
$(function() {
$('.draggable, .droppable').sortable({
connectWith: '.playlists'
});
});
#import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: visible;
font-family: 'Source Code Pro', monospace;
}
.dropper {
padding: 10px;
}
#drop-zone {
width: 100%;
min-height: 150px;
border: 3px dashed rgba(0, 0, 0, .3);
border-radius: 5px;
font-family: 'Source Code Pro', monospace;
text-align: center;
position: relative;
font-size: 20px;
color: #7E7E7E;
}
#drop-zone input {
position: absolute;
cursor: pointer;
left: 0px;
top: 0px;
opacity: 0;
}
/*Important*/
#drop-zone.mouse-over {
border: 3px dashed rgba(0, 0, 0, .3);
color: #7E7E7E;
}
/*If you dont want the button*/
#clickHere {
display: inline-block;
cursor: pointer;
color: white;
font-size: 1rem;
width: 200px;
border-radius: 0px;
background-color: #000000;
padding: 10px;
}
#clickHere:hover {
background-color: #376199;
}
.uploadedFiles {
padding: 0;
margin: 10px 50px;
}
#filename {
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
font-size: 14px;
line-height: 1.5em;
border: 1px solid;
min-height: 200px;
max-height: 400px;
overflow-y: scroll;
color: #240aff;
}
#filename span {
font-size: 1.5rem;
line-height: 1.2rem;
height: 1.5rem;
width: 1.5rem;
}
/* File Info */
#totalFiles {
border: 1px solid #06a7e5;
padding: 5px;
display: none;
}
.file-preview {
background: rgb(99, 8, 8);
border: 5px solid #fff;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
display: inline-block;
width: 60px;
height: 60px;
text-align: center;
font-size: 14px;
margin-top: 5px;
}
.closeBtn {
color: black;
display: inline-block;
vertical-align: -20%!important;
}
.closeBtn:hover {
color: red;
display: inline-block;
cursor: pointer;
}
.playlist {
border: 1px solid black;
padding: 10px;
margin: 5px;
background: #e9eaf9;
}
.playlist:hover {
cursor: move;
}
/* AUDIO CONTROLS */
#audioFiles {
vertical-align: middle;
margin: 0px 10px 0px 0px;
}
audio {
/*
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
*/
width: 25%;
height: 35px;
}
audio::-webkit-media-controls-enclosure {
border-radius: 5px;
background-color: #cfcfcf;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload & Draggable</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js" integrity="sha256-xH4q8N0pEzrZMaRmd7gQVcTZiFei+HfRTBPJ1OGXC0k=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
</head>
<body>
<div class="dropper">
<div id="drop-zone">
<p>Drop files here</p>
<div id="clickHere">or click here <i class="fa fa-upload"></i>
<input type="file" name="file" id="file" multiple accept="audio/*" />
</div>
</div>
</div>
<div class="uploadedFiles">
<p>Uploaded Files are Draggable. <span id="totalFiles"></span></p>
<div id="filename" class="playlists droppable"></div>
</div>
<!--
<audio id="audio2"></audio>
<p>
<label>File Size:</label>
<span id="filesize"></span>
<input type="hidden" id="size" name="size" value="" />
</p>
<p>
<label>Total Duration:</label>
<span id="duration"></span>
<input type="hidden" id="timelength" name="time" value="" />
</p>
-->
<script src="./script.js" async defer></script>
</body>
</html>
It worked well when i removed the following line of jquery code:
$('#filename').html("");

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.

how to avoid document.write my below code

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>

On Click not updating the output of a function

$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
I am trying to use a button on click event to change the temp display, but it doesn't seem to work like this. The function keeps seeing Celsius no matter what. I tried $(this).html too. The text of the button is actually changing, just the function isn't updating. I tried running the change units function inside the the button click even as well and it still doesn't update.
What am I not understanding about this onclick event and how can I get it to work.
JS Code:
var apiKey = "get your own key from http://openweathermap.org";
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
var currentTemp = changeUnits(weather.main.temp);
var high = changeUnits(weather.main.temp_max);
var low = changeUnits(weather.main.temp_min);
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
$('#currentTemp').html(currentTemp);
$('#high-low').html('<span id="high">High: ' + high + '</span><br>'
+ '<span id="low">Low: ' + low + '</span>');
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"><h1 id="currentLocation">Your Current Location is </h1></div>
<div class="navbar"></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<h2 class="text-center content-title" id="currentTemp"></h2>
<div class="content-body text-center">
<p id="high-low"></p>
<button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
<p id="currentConditions"></p>
</div>
</div>
</body>
</html>
I have done every change I can think of. console.log(el.text()) in the onclick clearly shows the text changing; but the function for changeUnits never seems to pick it up in the if statement when I run the function again during the onclick.
Looks like you're using html() instead of text(). I assume you're looking for button text instead of html, so try this:
$('.btn').on("click", function() {
$(this).text(function(f, c) {
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
});
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius'){
return Math.round(Temp - 273.15) + " &degC";
}else{
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
}
you are not calling the function, read comments in code
Also you are not passing any information to the '.btn' in the function passed to the text method.
$('.btn').on("click", function() {
var text = function(f, c) { // where are you getting your f and c parameters?
console.log(f); // should be undefined
console.log(c); // should be undefined
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
}();
console.log(text); // should be 'Celsius'
$(this).text(text); // changed from }) to }())
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius') // change html() to text() as well
return Math.round(Temp - 273.15) + " &degC";
else
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
Additionaly you should use a ID to associate your button to do this
<input id='thisID'>
// then call it in javascript
$("#thisID")
Toggleing the button
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});
Here is what I think is your problem. I didn't get to test it because I need to get the weather API and stuff. By looking at your code, here is what I get.
When the page loads, you are getting weather data from OpenWeatherMap. However, you are not cashing this info in some sort of global variable in order for you to access it later. You have declared all your variables inside the ajax callback and you have no way of accessing them later.
Try to do this:
var currentTemp;
var high;
var low;
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
currentTemp = weather.main.temp;
high = weather.main.temp_max;
low = weather.main.temp_min;
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
updateDisplay();
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
function changeUnits(Temp) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
updateDisplay();
});
function updateDisplay(){
$('#currentTemp').html(changeUnits(currentTemp));
$('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>'
+ '<span id="low">Low: ' + changeUnits(low) + '</span>');
}
I have introduced another function updateDisplay() to actually handle the changing of the displayed temps. As I said, I didn't get to test it. But I am pretty sure it will work.
JS:
var apiKey="get an openweathermap APIKey";
var loc;
var lat;
var long;
var temp;
var high;
var low;
var icon;
//var wind;
//var windDir;
//var windSpd;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
lat = parseFloat(loc[0]);
long = parseFloat(loc[1]);
getWeather(lat, long);
initGmaps(lat, long);
});
//api call to use lat and long to generate a map
window.addEventListener('load', function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
document.body.appendChild(script);
});
function initGmaps(lat, long) {
var map = new GMaps({
div: '#map',
lat: lat,
lng: long,
zoom: 14,
disableDefaultUI: true,
mapTypeId: "satellite",
});
map.addMarker({
lat: lat,
lng: long
});
}
//using weather to get data and plug it into our page
function getWeather(lat, long) {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat + '&lon=' + long + '&appid=' + apiKey;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = {
f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
};
high = {
f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
low = {
f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
windSpd = {
f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
c: Math.round((data.wind.speed)*10)/10 + " M/S"
};
var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))];
$('#currentLocation').append(data.name);
$('#high').append(" " + high.f);
$('#low').append(" " + low.f);
$('#currentTemp').html(temp.f);
$('#weatherDesc').html(data.weather[0].description);
$('#windDir').html(windDir);
$('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');
icon = data.weather[0].icon;
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
}
});
}
$('#currentTemp').on('click', function() {
var current = $(this).data('nexttemp');
$('#currentTemp').text(temp[current]);
$('#high').html(high[current]);
$('#low').html(low[current]);
$('#windSpd').html(windSpd[current]);
if (current == 'c') {
$(this).data('nexttemp', 'f');
return;
}
$(this).data('nexttemp', 'c');
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"></div>
<div class="navbar"><h4>Free Code Camp Weather App</h4></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<div class="col-lg-4" id="map"></div>
<div class="col-lg-4">
<h1 id="currentLocation">Your Current Location is </h1>
</div>
<h2 class="center-text content-title" id="currentTemp"></h2>
<h3 id="caption">Click temperature to change Units</h3>
<div class="center-text">
<p class="oneLine" id="labels">High: <span id="high"></span></p>
<p class="oneLine" id="labels">Low: <span id="low"></span></p>
</div>
<p class="center-text" id="currentConditions"></p>
<p class="center-text" id="weatherDesc"></p>
<div class="windCompass col-lg-4">
<div class="compass">
<div class="direction">
<p id="windDir"></p>
</div>
<div class="arrow ne"></div>
</div>
</div>
</div>
</body>
</html>
CSS:
#import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
body {
background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
background-size: auto;
background-repeat: no-repeat;
font-family: Ranga, cursive;
}
h4 {
margin-top: 7px;
}
h1 {
margin-left: -7px;
font-size: 1.05em;
color: white;
}
#header {
background: #2980b9;
color: white;
padding: 0 5px;
display: inline-block;
width: 100%;
margin: 0;
box-shadow: 0 2px 5px #555555;
}
#header .left {
display: inline-block;
width: auto;
float: left;
margin-top: 7px;
margin-left: 7px;
}
#header .navbar {
display: inline-block;
width: 60%;
}
#header .right {
display: inline-block;
width: auto;
text-align: right;
float: right;
margin-top: 2px;
margin-right: 7px;
vertical-align: bottom;
}
.bigger_icon {
margin-top: 10px;
font-size: 2em;
color: white;
}
#map {
height: 200px;
width: 200px;
border-radius: 5%;
margin-top: 20px;
}
#container {
background: rgba(66, 66, 66, 0.6);
display: block;
position: relative;
width: 40%;
margin: 24px auto;
min-height: 300px;
padding: 16px;
border-radius: 4px;
}
#container .center-text {
text-align: center;
}
h2 {
color: white;
font-family: Ranga, cursive;
font-size: 2.5em;
font-weight: bold;
margin-top: -230px;
}
#caption {
font-size: 17px;
text-align: center;
color: pink;
}
#labels {
color: darkGrey;
font-size: 1.5em;
}
.oneLine {
color: darkGrey;
font-size: 1.5em;
text-align: center;
display: inline;
padding: 5px;
}
#high {
text-align: center;
color: orange;
}
#low {
text-align: center;
color: blue;
}
#currentConditions {
text-align: center;
color: black;
}
#weatherDesc {
margin-top: -25px;
color: white;
}
.windCompass {
margin-left: 75%;
margin-top: -20%;
}
.compass {
display: block;
width: 120px;
height: 120px;
border-radius: 100%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
position: relative;
font-family: 'Dosis';
color: #555;
text-shadow: 1px 1px 1px white;
}
.compass:before {
font-weight: bold;
position: absolute;
text-align: center;
width: 100%;
content: "N";
font-size: 14px;
top: -2px;
}
.compass .direction {
height: 100%;
width: 100%;
display: block;
background: #f2f6f5;
background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
border-radius: 100%;
}
.compass .direction p {
text-align: center;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 100%;
line-height: 80px;
display: block;
margin-top: -35%;
font-size: 28px;
font-weight: bold;
}
.compass .direction p span {
display: block;
line-height: normal;
margin-top: -10%;
font-size: 17px;
text-transform: uppercase;
font-weight: normal;
font-family: Ranga, cursive;
}
.compass .arrow {
width: 100%;
height: 100%;
display: block;
position: absolute;
top: 0;
}
.compass .arrow:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid red;
position: absolute;
top: -6px;
left: 50%;
margin-left: -5px;
z-index: 99;
}
.compass .arrow.nne {
transform: rotate(22.5deg);
}
.compass .arrow.ne {
transform: rotate(45deg);
}
.compass .arrow.ene {
transform: rotate(67.5deg);
}
.compass .arrow.e {
transform: rotate(90deg);
}
.compass .arrow.ese {
transform: rotate(112.5deg);
}
.compass .arrow.se {
transform: rotate(135deg);
}
.compass .arrow.sse {
transform: rotate(157.5deg);
}
.compass .arrow.s {
transform: rotate(180deg);
}
.compass .arrow.ssw {
transform: rotate(202.5deg);
}
.compass .arrow.sw {
transform: rotate(-135deg);
}
.compass .arrow.wsw {
transform: rotate(-114.5deg);
}
.compass .arrow.w {
transform: rotate(-90deg);
}
.compass .arrow.wnw {
transform: rotate(-69.5deg);
}
.compass .arrow.nw {
transform: rotate(-45deg);
}
.compass .arrow.nnw {
transform: rotate(-24.5deg);
}
I ended up finding some Ajax and working with it to do what I expected the button to do. While not a button, it does what is intended. I also worked in changing the high, low, and wind speed to also change with the unit change.
I appreciate the help that everyone offered.
feel free to offer suggestions on the code as well for fixing the css for the compass gradient and making the stupid thing more responsive if you'd like. (The Map is not doing the responsive thing.
Your script probably gets loaded before the DOM is ready.
What you want to do here is one of a few options:
1. Load the JS script tag at the end of the body.
2. Wrap your $('.btn').on(...) function with document.on('ready') event, so this code will only be triggered when the DOM is ready.

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.

Categories