On Click not updating the output of a function - javascript

$('.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.

Related

Autocomplete and suggestions of Leaflet Search doesn't work?

Good morning all,
I need your help with Leaflet search. I can't seem to find where the error is coming from, which is:
My search bar works fine but autocomplete with suggestions doesn't work, I don't know where it came from.
Also, but this is optional, can you help me to optimize the code for it to be fast to load on a web page (you can see that there is async but it's not enough given the amount of data I load).
Thanks for your help, I'll take everything into consideration.
async function init(){
var lat = 51.505;
var lng = -0.09;
var zoomLevel = 3;
/**********************************************************/
/*INIT MAP*/
/**********************************************************/
var mainLayer = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}{r}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap',
maxZoom: 11,
minZoom: 2,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
zoomControl: false,
accessToken: 'pk.eyJ1IjoiYW1hdXJ5MDg0MDAiLCJhIjoiY2todWZ3dmtsMDR2cjJ0bzIwajc2NjBobyJ9.VXOjqAoE1IQ2DcCVSYlXOg'
});
var map = L.map('mapAgentsCentrimex', {
center: [lat, lng],
zoom: zoomLevel,
layers: [mainLayer]
});
/**********************************************************/
/*SEARCHBOX*/
/**********************************************************/
var data = us_states;
var featuresLayer = new L.GeoJSON(data, {
style: function(feature) {
return {color: feature.properties.color };
},
onEachFeature: function(feature, marker) {
marker.bindPopup('<h4 style="color:'+feature.properties.color+'">'+ feature.properties.name +'</h4>');
}
});
map.addLayer(featuresLayer);
var searchControl = new L.Control.Search({
position: 'topleft',
layer: featuresLayer,
propertyName: 'name',
marker: false,
moveToLocation: function(latlng, title, map) {
//map.fitBounds( latlng.layer.getBounds() );
var zoom = map.getBoundsZoom(latlng.layer.getBounds());
map.setView(latlng, zoom);
}
});
searchControl.on('search:locationfound', function(e) {
console.log('search:locationfound', );
//map.removeLayer(this._markerSearch)
e.layer.setStyle({fillColor: '#3f0', color: '#0f0'});
}).on('search:collapsed', function(e) {
featuresLayer.eachLayer(function(layer) {
featuresLayer.resetStyle(layer);
});
});
map.addControl( searchControl );
/******************************************************************
*********** MARKERS ***********
******************************************************************/
var markers = L.markerClusterGroup();
var iconAirport = L.icon({
iconUrl: 'images/iconPlane.png',
iconSize: [22, 34]
});
$.getJSON("json/airports.geojson", function(data){
airport = $.each(data,function(key,val){
var titleAirport = val.name;
var latAiport = val.lat;
var lngAirport = val.lon;
markers.addLayer(L.marker([latAiport, lngAirport], {icon: iconAirport}).bindPopup('Name:' + titleAirport));
});
});
map.addLayer(markers);
var iconSeaport = L.icon({
iconUrl: 'images/iconBoat.png',
iconSize: [22, 34]
});
var markersSeaport = L.markerClusterGroup();
$.getJSON("json/IFR_LOCATION_PORTS.geojson",function(data){
var incidents = L.geoJson(data, {
pointToLayer: function (feature, latlng){
var marker = L.marker(latlng, {icon:iconSeaport});
marker.bindPopup('Name:' + feature.properties.Name);
return marker;
},
onEachFeature: function (feature, layer){
layer.addTo(markersSeaport);
}
});
map.addLayer(markersSeaport);
});
L.control.layers({
"Carte Pays": mainLayer
}, {
"Aérien": markers,
"Maritime": markersSeaport
}).addTo(map);
map.zoomControl.remove();
L.control.zoom({
position:'bottomright'
}).addTo(map);
/******************************************************************
*********** GEOLOCATION ***********
******************************************************************/
var geolocButton = L.control({position: 'bottomright'});
geolocButton.onAdd = (mapRef) => {
var button = L.DomUtil.create('button', 'geoloc-button');
button.innerHTML = '<span class="icon-location2"></span>';
button.onclick = () => {
mapRef.locate();
button.disabled = true;
mapRef.on('locationfound', (locEvent) => {
var radius = locEvent.accuracy / 2;
var point = locEvent.latlng;
mapRef.setView(point, 8);
button.disabled = false;
L.circle(point, radius).addTo(mapRef).bindPopup('Vous êtes ici sur la carte').openPopup();
});
mapRef.on('locationerror', (err) =>{
button.disabled = false;
});
}
return button;
}
geolocButton.addTo(map);
/******************************************************************
*********** COUNTRIES ***********
******************************************************************/
// Set color of countries
function style(feature) {
return {
fillColor: '#ff5349',
weight: 5,
opacity: 0,
color: '#ff5349',
dashArray: '3',
fillOpacity: 0
};
}
// Set Mouse Hover
async function highlightFeature(e){
var layer = e.target;
layer.setStyle({
fillColor: '#ff5349',
weight: 4,
opacity: 0.8,
color: '#ff5349',
dashArray: '',
fillOpacity: .5
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
}
async function highlightFeatureClick(e){
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#ff5349',
dashArray: '',
fillOpacity: .7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature.properties);
info.clickPays(layer.feature.properties);
}
// Back color Mouse Out
async function resetHighlight(e) {
geojson.resetStyle(e.target);
}
// Each Feature
async function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: highlightFeatureClick
});
}
// Display data to e.target inside wrapper
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create('div', 'info');
this._div.setAttribute("id", "idBoxList");
L.DomEvent
.addListener(this._div, 'mouseover', function () {
MapShowCommand();
});
this.update();
this.clickPays();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = '<div class="wrapper--popup-agents"><h3 class="title-med">Agents disponibles</h3><div class="buttonListeAgent" id="buttonListeAgentId"><span class="icon-keyboard_arrow_down"></span></div><div class="textfield">Liste des agents disponibles selon le pays sélectionné.</div></div><div class="agents--wrapper"><div class="content"><ul class="listAgents"></ul></div></div>';
};
info.clickPays = function(props){
if (props) {
this._div.classList.add("show");
var el = document.getElementById('idBoxList');
L.DomEvent.disableScrollPropagation(el);
L.DomEvent.disableClickPropagation(el);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var name = props.name;
var base_path = $('#url_base').val();
$.ajax({
url:"/map-agents",
type:'POST',
data:{name:name},
dataType: "JSON",
beforeSend: function () {
$('.listAgents').append('<div class="spinner-border text-info" role="status"></div>');
},
success: function (response) {
$.each(response, function (index) {
if (response[index].transport == 'M') {
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-bateau.png';
}
if (response[index].transport == 'A'){
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-avion.png';
}
if (response[index].transport == 'MA') {
var pathIcon = 'http://127.0.0.1:8000/images/icon/picto-centrimex-maritime-aerien.png';
}
var agents = '<li class="agents"><input type="hidden" class="agentId" name="idAgent" value="'+ response[index].id +'"><div class="leftSide"><h5 class="title">' + response[index].nom_fr_fr + '</h5><div class="name-firm">' + response[index].nameFirm + '<span>, ' + response[index].city + '</span></div></div><div class="rightSide"><img src="' + pathIcon + '" alt="Icon transport"></div></li>';
$('.listAgents').append(agents);
});
},
complete: function () {
$('.spinner-border.text-info').remove();
},
error: function (response){
console.log(response);
}
});
}
else
{
this._div.classList.remove("show");
}
};
info.setPosition('bottomleft');
info.addTo(map);
async function refreshDataAgent(){
$('.wrapper-overlay').html('<div class="wrapper--agent-map"></div>')
}
async function MapShowCommand() {
$('.buttonListeAgent').off().on('click', function(){
if ($('#idBoxList').hasClass("show")) {
$('#idBoxList').removeClass("show");
info.update();
}
});
$('.listAgents li').off().on('click', function(){
var el = document.getElementById('overlayMap');
L.DomEvent.disableScrollPropagation(el);
L.DomEvent.disableClickPropagation(el);
var idAgent = $(this).children('input').val();
var base_path = $('#url_base').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/map-agents/agents",
type:'POST',
data:{idAgent:idAgent},
dataType: "JSON",
beforeSend: function () {
$('.wrapper-overlay').addClass('active');
$('.wrapper--agent-map').append('<div class="spinner-border text-info" role="status"></div>');
},
success: function (response) {
var transport = '';
switch (response.transport){
case 'MA':
transport = '<li><img src="/images/icon/picto-centrimex-bateau.png"><span>Maritime</span></li><li><img src="/images/icon/picto-centrimex-avion.png"><span>Aérien</span></li>';
break;
case 'M':
transport = '<li><img src="/images/icon/picto-centrimex-bateau.png"><span>Maritime</span></li>';
break;
case 'A':
transport = '<li><img src="/images/icon/picto-centrimex-avion.png"><span>Aérien</span></li>';
break;
default:
transport = '<li><span class="whiteInput">Pas de transport renseigné</span></li>';
}
var wrapperContentAgent = '<div class="closePopUp"><span class="icon-cross"></span></div><div class="topSection"><div class="first"><h3>Compagnie</h3><ul class="compagnieList"></ul></div><div class="two"><h3>Mode de transport</h3><ul class="transportList"></ul></div><div class="three"><h3>Informations</h3><ul class="infosList"></ul></div></div><div class="middleSection"><div class="first"><h3>Référence client</h3><ul class="referenceList"></ul></div><div class="two"><div class="whitespace"></div><ul class="profitList"></ul></div></div><div class="bottomSection"><h3>Commentaire</h3><div class="contentComment"></div></div>';
$('.wrapper--agent-map').append(wrapperContentAgent);
$('.wrapper--agent-map').append('<input type="hidden" value="'+ response.id +'" name="idAgent">')
$('.compagnieList').append('<li>Nom Compagnie : '+ (response.nameFirm ? '<span>'+response.nameFirm+'</span>' : '<span class="whiteInput">Pas de nom de compagnie</span>') +'</li><li>Pays : '+ (response.nom_fr_fr ? '<span>'+response.nom_fr_fr+'</span>' : '<span class="whiteInput">Pas de pays</span>') +'</li><li>Ville : '+ (response.city ? '<span>'+response.city+'</span>' : '<span class="whiteInput">Pas de ville</span>') +'</li><li>Réseau : '+ (response.network ? '<span>'+response.nameNetwork+'</span>' : '<span class="whiteInput">Pas de réseau associé</span>') +'</li>');
$('.transportList').append(transport);
$('.infosList').append('<li>Nom : '+ (response.lastName ? '<span>'+response.lastName+'</span>' : '<span class="whiteInput">Pas de nom</span>') +'</li><li>Prénom : '+ (response.firstName ? '<span>'+response.firstName+'</span>' : '<span class="whiteInput">Pas de prénom</span>') +'</li><li>E-mail : '+ (response.mail ? '<span>'+response.mail+'</span>' : '<span class="whiteInput">Pas de mail</span>') +'</li><li>Téléphone : '+ (response.phone ? '<span>'+response.phone+'</span>' : '<span class="whiteInput">Pas de téléphone</span>') +'</li>');
$('.referenceList').append('<li>Référence compte client : '+ (response.accountCustomer ? '<span>'+response.accountCustomer+'</span>' : '<span class="whiteInput">Pas de référence client</span>') +'</li><li>Référence compte fournisseur : '+ (response.accountProvider ? '<span>'+response.accountProvider+'</span>' : '<span class="whiteInput">Pas de référence fournisseur</span>') +'</li>');
$('.profitList').append('<li>ProfitShare : '+ (response.profitShare ? '<span>'+response.profitShare+'</span>' : '<span class="whiteInput">Pas de profitShare renseigné</span>') +'</li><li>Condition de Paiement : '+ (response.payementCondition ? '<span>'+response.payementCondition+'</span>' : '<span class="whiteInput">Pas de conditionde paiement renseigné</span>') +'</li><li>Réciprocité Business : '+ (response.business ? '<span>'+response.business+'</span>' : '<span class="whiteInput">Pas de réciprocité business renseignée</span>') +'</li>');
$('.contentComment').append((response.comment ? '<p>'+response.comment+'</p>' : '<span class="whiteInput">Pas de commentaire sur cette agent</span>'));
// if (response.supsension != null) {
// $('.bottomSection').append('');
// }
$('.closePopUp').click(function(){
$('.wrapper-overlay').removeClass('active');
refreshDataAgent();
});
},
complete: function () {
$('.spinner-border.text-info').remove();
},
error: function (response){
console.log(response);
}
});
});
}
// Call data inside geoJSON
$.getJSON("json/countries.geojson",function(data){
geojson = L.geoJson(data, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
});
}
/************************************************************************************************/
/* MAP */
/************************************************************************************************/
#mapAgentsCentrimex{
width: 100%;
height: 100vh;
z-index: 1;
}
#buttonScrollMap
{
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
background-color: white;
width: 50px;
height: 50px;
border-radius: 50%;
box-shadow: 0px 0px 15px rgba(0,0,0,0.3);
color: #4690be;
font-size: 14px;
font-weight: 600;
}
#buttonScrollMap:before
{
content: '\e90e';
font-family: icomoon;
font-size: 26px;
color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#buttonScrollMap:hover{
text-decoration: none;
}
#mapAgentsCentrimex .info{
background-color: #003366;
color: white;
width: 400px;
float: none;
overflow-y: auto;
max-height: 80vh;
}
#mapAgentsCentrimex .buttonListeAgent {
position: absolute;
top: 10px;
right: 10px;
font-size: 30px;
color: white;
opacity: .8;
z-index: 999;
}
#mapAgentsCentrimex .buttonListeAgent:hover{
opacity: 1;
color: #FAFAFA;
cursor: pointer;
}
#mapAgentsCentrimex .info.active{
height: auto;
}
#mapAgentsCentrimex .wrapper--popup-agents{
padding: 30px;
}
#mapAgentsCentrimex .agents--wrapper{
background-color: white;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents {
display: flex;
flex-direction: row;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .leftSide{
width: 60%;
padding-left: 15px;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .rightSide{
width: 40%;
position: relative;
}
#mapAgentsCentrimex .agents--wrapper .listAgents .agents .rightSide img{
width: auto;
height: 50px;
position: absolute;
top: 50%;
right: 3%;
transform: translateY(-50%);
}
#mapAgentsCentrimex ul.listAgents {
margin: 0px;
padding: 0;
list-style: none;
}
#mapAgentsCentrimex li.agents {
width: 100%;
height: auto;
color: black;
padding: 20px;
}
#mapAgentsCentrimex li.agents:hover{
background-color: #FAFAFA;
}
#mapAgentsCentrimex h5.title {
text-transform: uppercase;
font-size: 14px;
font-weight: 700;
letter-spacing: .5px;
color: #4690be;
}
#mapAgentsCentrimex .name-firm {
font-size: small;
font-weight: 600;
text-transform: capitalize;
}
#mapAgentsCentrimex .name-firm span{
font-weight: 300;
text-transform: capitalize;
}
#mapAgentsCentrimex button.geoloc-button.leaflet-control {
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2);
border: none;
padding: 8px;
background-color: white;
border-radius: 2px;
font-size: 17px;
}
.leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar {
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2) !important;
border: none !important;
padding: 2px;
background-color: white;
border-radius: 2px;
font-size: 17px;
}
#mapAgentsCentrimex .wrapper-overlay{
background-color: rgba(0,0,0,.7);
width: 100%;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: 1001;
display: none;
cursor: initial;
}
#mapAgentsCentrimex .wrapper-overlay.active{
display: block;
}
#mapAgentsCentrimex .wrapper-overlay .wrapper--agent-map{
background-color: white;
width: 85%;
height: 80vh;
min-width: 300px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
box-sizing: border-box;
box-shadow: 0px 0px 20px rgba(0,0,0,.2);
padding: 30px;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp{
position: absolute;
top: 0px;
right: 0px;
padding: 20px;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp:hover{
cursor: pointer;
}
#mapAgentsCentrimex .wrapper-overlay .closePopUp .icon-cross{
font-size: 22px;
opacity: .7;
}
#mapAgentsCentrimex .wrapper-overlay h3{
color: #4690be;
font-size: 22px;
font-weight: 700;
letter-spacing: .5px;
line-height: 40px;
margin-bottom: 15px;
}
#mapAgentsCentrimex .wrapper-overlay .whitespace{
height: 40px;
width: 100%;
margin-bottom: 15px;
}
#mapAgentsCentrimex .wrapper-overlay ul{
list-style: none;
margin-left: 0;
padding: 0;
}
#mapAgentsCentrimex .wrapper-overlay ul li{
line-height: 25px;
font-size: 15px;
color: black;
opacity: 0.8;
font-weight: 300;
}
#mapAgentsCentrimex .wrapper-overlay ul li span{
font-weight: 600;
font-size: 16px;
}
#mapAgentsCentrimex .wrapper-overlay p{
color: black;
font-size: 16px;
font-weight: 300;
}
#mapAgentsCentrimex .wrapper-overlay ul li span.whiteInput{
color: #eda60c;
}
#mapAgentsCentrimex .wrapper-overlay ul li img{
width: 50px;
height: 50px;
margin-right: 20px;
}
#mapAgentsCentrimex .wrapper-overlay .topSection, #mapAgentsCentrimex .wrapper-overlay .middleSection{
display: flex;
flex-direction: row;
margin-bottom: 30px;
}
#mapAgentsCentrimex .wrapper-overlay .topSection .first, #mapAgentsCentrimex .wrapper-overlay .topSection .two, #mapAgentsCentrimex .wrapper-overlay .topSection .three{
width: 33%;
padding: 10px;
}
#mapAgentsCentrimex .wrapper-overlay .middleSection .first, #mapAgentsCentrimex .wrapper-overlay .middleSection .two{
width: 50%;
padding: 10px;
}
<section class="glob--map">
<div id="mapAgentsCentrimex">
<div class="wrapper-overlay" id="overlayMap">
<div class="wrapper--agent-map">
</div>
</div>
</div>
<input type="hidden" id="url_base" value="{{ URL::asset('images/centrimex_logo.png') }}" name="">
</section>
Problem of autocomplete & suggestion resolve.
When you add librairies, make sure that you don't include leaflet-search.js & leaflet-search-geocoder.js in the same time. "leaflet-search-geocoder.js" blocked a few functions like Autocomplete.
But if you want to help me with the optimization of my script, the topic is still open

Array[0] undefined

When I output my code I get this output:
0[object Object]
1[object Object]
I believe this is because it is an object. Although I'm pretty noob, so I believe an object is an array. Correct me if that's wrong.
I noticed the object in my console:
Objectresult: Objectadmin_county: "Somerset"admin_district: "Sedgemoor"admin_ward: "Axevale"ccg: "NHS Somerset"codes: Objectcountry: "England"eastings: 343143european_electoral_region: "South West"incode: "2WL"latitude: 51.2870673059808longitude: -2.81668795540695lsoa: "Sedgemoor 001A"msoa: "Sedgemoor 001"nhs_ha: "South West"northings: 154531nuts: "Somerset"outcode: "BS26"parish: "Axbridge"parliamentary_constituency: "Wells"postcode: "BS26 2WL"primary_care_trust: "Somerset"quality: 1region: "South West"__proto__: Objectstatus: 200__proto__: Object
it maybe neater to look at this: https://api.postcodes.io/postcodes?lon=0.080647&lat=51.626281000000006&radius=115
I am trying to separate these parts into usable items stored as variables. I tried array[0] but that is undefined. Which I assume means I need to do something more like object(array[0])
I've been searching a while and I'm not getting anywhere.
Here's my full code that I was forking from elsewhere.
$(window).ready(function() {
$(initiate_geolocation);
});
function initiate_geolocation() {
navigator.geolocation.getCurrentPosition(handle_geolocation_query);
}
function handle_geolocation_query(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = "https://api.postcodes.io/postcodes?lon=" + lon + "&lat=" + lat + "&radius=125";
post(url).done(function(postcode) {
displayData(postcode);
// console.log("postcode says: "+postcode);
console.log(postcode[0[1]]);
});
}
//display results on page
function displayData(postcode) {
var html = "";
$('#text').hide();
for (var index in postcode['result']) {
html += "<div class='row'>";
html += "<div class='cell'>";
html += index.replace(/_/g, ' ').strFirstUpper();
html += "</div><div class='cell'>";
html += postcode['result'][index];
html += "</div></div>";
console.log(postcode)
}
$('#text').html(html).fadeIn(300);
}
//ajax call
function post(url) {
return $.ajax({
url: url,
success: function() {
//woop
},
error: function(desc, err) {
$('#text').html("Details: " + desc.responseText);
}
});
}
//uppercase
String.prototype.strFirstUpper = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
#import url(//fonts.googleapis.com/css?family=Roboto);
html {
font-family: 'Roboto', sans-serif;
}
.header {
position: fixed;
z-index: 10;
width: 100%;
background: -moz-linear-gradient(90deg, #394D66, #3A5B85);
background: linear-gradient(90deg, #394D66, #3A5B85);
height: 80px;
min-width: 500px;
}
h1 {
font-weight: 400;
text-align: center;
margin: 0px;
font-size: 1.5em;
color: #9DC3EB;
text-transform: uppercase;
}
h1 span {
font-size: 0.8em;
text-transform: lowercase;
color: #E0E0E0;
}
.row {
width: 100%;
font-size: 1.2em;
padding: 5px 0px;
border-bottom: 1px solid #ccc;
}
.inputHolder {
width: 100%;
font-size: 20px;
text-align: center;
}
.inputHolder input {
text-align: center;
color: #333;
}
.cell {
display: inline-block;
width: 49%;
color: #393939;
}
.row .cell:first-child {
text-align: right;
padding-right: 10px;
}
.row:hover {
background: #ccc;
}
#text {
z-index: 0;
padding: 90px 0px;
width: 60%;
margin: 0px auto;
min-width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<div class='header'>
<h1><span>Postcode Seach with</span> Postcodes.io</h1>
<!-- <div class='inputHolder'>
<input placeholder='Postcode' type='text' id='txtPostcode'/>
<input type='button' value='Search' id='btnPostcode'/>
</div>
-->
</div>
<div id='text'></div>
Eventually i want this code to ask you for permission to discover your location when you open the page and then find your post code (using postcode.io). I've got most of the way there but my noobishness is hurting me badly. Any help is much appreciated.
The code must be https to run geolocation.

Can I use CSS calc within Javascript?

Can I use the css calc() function when setting positions in JavaScript?
ePopup.style.top = "calc(100px - 1.5em)";
Yes, calc() will work when setting styles in javascript.
Working Example:
var innerDiv = document.getElementsByClassName('inner-div')[0];
function growInnerDiv() {
innerDiv.style.setProperty('width', 'calc(100% + 224px)');
}
innerDiv.addEventListener('click', growInnerDiv, false);
.outer-div {
display: inline-block;
width: 200px;
height: 100px;
padding: 12px;
border: 1px solid rgb(255,0,0);
background-color: rgb(255,255,0);
}
.inner-div {
width: 100px;
height: 100px;
color: rgb(255, 255, 255);
font-weight: bold;
text-align: center;
line-height: 100px;
font-family: arial, helvetica, sans-serif;
background-color: rgb(255,0,0);
cursor: pointer;
transition: all 0.5s linear;
}
<div class="outer-div">
<div class="inner-div">Click Me</div>
<div>
There are some interesting things that happen when you use calc with the same type of units, e.g. 10px + 5px. It gets simplified to 15px by the process that puts it onto the element.
So, to expand on rounin's great answer, here's some examples of that behaviour in action:
function growDiv(e) {
const thisDiv = e.target;
const x = 100;
const y = 42;
const z = 69;
let widthVal;
if (thisDiv.id == "simplifies") {
widthVal = `calc(${y + z}px + ${x}px + ${y}px)`;
} else if (thisDiv.id == "mixed-units") {
widthVal = `calc(0em + ${y + z}px + ${x * 2}px + ${y}px)`;
} else if (thisDiv.id == "variables") {
thisDiv.style.setProperty("--x", x + "px");
thisDiv.style.setProperty("--y", y + "px");
thisDiv.style.setProperty("--z", z + "px");
widthVal = "calc((var(--x) * 2) + var(--y) + (var(--z) * 2))";
}
thisDiv.style.width = widthVal;
thisDiv.innerHTML =
`input: ${widthVal}<br>style:${thisDiv.style.width}`;
}
document
.querySelectorAll("div")
.forEach((el) => el.addEventListener("click", growDiv, false));
.inner-div {
background-color: hotpink;
color: white;
font-weight: bold;
height: 100px;
margin-bottom: 5px;
text-align: center;
transition: all 0.5s linear;
width: 100px;
}
<div class="inner-div" id="simplifies">simplifies<br />1) Click Me</div>
<div class="inner-div" id="mixed-units">mixed-units<br />2) Click Me</div>
<div class="inner-div" id="variables">variables<br />3) Click Me</div>
Div 1 has all the same units, and therefore simplifies.
Div 2 has a token 0em unit, which makes no difference to the calculation, but forces the full expression to come through.
Div 3 is my favourite because it's a little bit self-documenting. I do this because I'm a bit forgetful and it lets me see why I set that element to 728.3 high, not just that I did.

Adding an extra two variables to a count simulator function

I've created the following fiddle https://jsfiddle.net/jnoweb/v421zzbe/2/
At the moment it has one variable which makes all three IDs count up to 20:
var game = {score:0},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display) {
display.innerHTML = game.score;
});
}
add20();
I want to change this so that each ID counts to a different value, for example 16, 18 and 20!
Does anyone know how to achieve this?
Here is the more elegant, generic, configurable solution.
function ScoreDisplay(id, increment) {
this.elm = document.getElementById(id);
this.inc = increment;
this.game = {score: 0};
}
ScoreDisplay.prototype = {
update: function(){
this.elm.innerHTML = this.game.score;
}
};
var scoreDisplay = [];
scoreDisplay.push(new ScoreDisplay('score1', 16));
scoreDisplay.push(new ScoreDisplay('score2', 18));
scoreDisplay.push(new ScoreDisplay('score3', 20));
function addScore() {
scoreDisplay.forEach(function(sd) {
TweenLite.to(sd.game, 1, {score: "+=" + sd.inc, roundProps:"score", onUpdate:sd.update.bind(sd), ease:Linear.easeNone});
});
}
addScore();
#score1 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score2 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score3 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
<!--TweenLite/TweenMax GSAP-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TimelineLite.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/RoundPropsPlugin.min.js"></script>
<div id="prodArrow"></div>
<div id="prodCount">
<div id="score1"></div>
</div>
<div id="testArrow"></div>
<div id="testCount">
<div id="score2"></div>
</div>
<div id="devArrow"></div>
<div id="devCount">
<div id="score3"></div>
</div>
var game = {
score1: 0,
score2: 0,
score3: 0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")
];
function add(scoreIndex, numToAdd) {
TweenLite.to(game, 1, {score:("+="+numToAdd), roundProps: ("score" + scoreIndex), onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, i) {
var key = ("score" + (i+1))
display.innerHTML = game[key];
});
}
add(1 , 16);
add(2 , 18);
add(3 , 20);
What about this ?
var game = {
score1:0,
score2:0,
score3:0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score1:"+=16", score2:"+=18", score3:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, key) {
var score = scoreDisplay[key].id;
display.innerHTML = game[score];
});
}
add20();
https://jsfiddle.net/hundma4g/

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