Bootstrap dropdown menu button not showing with Leaflet map - javascript

I'm trying to create a leafletJS Map with Bootstrap buttons. I made the map fullscreen and placed the buttons on top of it. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="static/bootstrap/js/bootstrap.min.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
<link rel="stylesheet" media="screen" href ="static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap-theme.min.css">
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100%;
}
#back_button {
position: absolute;
top: 20px;
left: 20px;
padding: 10px;
z-index: 1001;
}
#drop_button {
position: absolute;
top: 80px;
left: 20px;
padding: 10px;
z-index: 1001;
}
</style>
</head>
<body>
<div id='map'>
</div>
<form action="/" method="post" role="form">
<button type="submit" class="btn btn-default" id="back_button"><- Back</button>
</form>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" id="drop_button">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</div>
<script>
var map = L.map('map', {zoomControl:false}).setView([47.57768554635565,-122.16660887002944], 13);
var coordinate = {{list_latlong | tojson | safe}};
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var logoIcon = L.icon({
iconUrl: './static/picture.png',
iconSize: [22, 22], // size of the icon
iconAnchor: [11, 22], // point of the icon which will correspond to marker's location
});
var i;
for (i = 0; i < coordinate.length; i++) {
var point = coordinate[i]
var text = "";
text = "<dl><dt>Number: " + point[2] + "</dt>"
+ "<dt>" + point[5] + "</dt>"
+ "<dt>" + point[6] + ", " + point[7] + ", " + point[8] + "</dt>"
+"</dl>"
L.marker([point[3],point[4]], {icon: logoIcon}).bindPopup(text).addTo(map);
}
</script>
</body>
</html>
Running this code will only show the "Back" button and no dropdown button. If I remove
<link rel="stylesheet" media="screen" href ="static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap-theme.min.css">
The dropdown button and back button is showing but the elements in the dropdown menu are not showing.

I've fixed that for you, for more than one reason, first the bootstrap link is wrong, second you add wrong styles on wrong id #dropdown button, so the button was displayed but in footer so you don't see it, here's the full code with edit some files places and urls with update new style from #dropdown to parent div .dropdown
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.4/dist/leaflet.css"/>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100%;
}
#back_button {
position: absolute;
top: 20px;
left: 20px;
padding: 10px;
z-index: 1001;
}
.dropdown {
position: absolute;
top: 80px;
left: 20px;
z-index: 1001;
}
</style>
</head>
<body>
<div id='map'>
</div>
<form action="/" method="post" role="form">
<button type="submit" class="btn btn-default" id="back_button"><- Back</button>
</form>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" id="drop_button">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet#1.3.4/dist/leaflet.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var map = L.map('map', {zoomControl:false}).setView([47.57768554635565,-122.16660887002944], 13);
var coordinate = {{list_latlong | tojson | safe}};
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var logoIcon = L.icon({
iconUrl: './static/picture.png',
iconSize: [22, 22], // size of the icon
iconAnchor: [11, 22], // point of the icon which will correspond to marker's location
});
var i;
for (i = 0; i < coordinate.length; i++) {
var point = coordinate[i]
var text = "";
text = "<dl><dt>Number: " + point[2] + "</dt>"
+ "<dt>" + point[5] + "</dt>"
+ "<dt>" + point[6] + ", " + point[7] + ", " + point[8] + "</dt>"
+"</dl>"
L.marker([point[3],point[4]], {icon: logoIcon}).bindPopup(text).addTo(map);
}
</script>
</body>
</html>

<script src="static/bootstrap/js/bootstrap.min.js"></script>
This is the bootstrap script file to make the menus and other fancy js-dependent stuff work. But in order for it to work it needs to have a DOM (document object model) to work with. What you currently have is the script firing right at the top after jQuery, without any DOM element for it to work with (the menu elements haven't been parsed yet!).
Try putting this at the spot right before you close your </body> tag. That should make the menu elements work.

Related

How to highlight a row in DATATABLE from Leaflet map marker info?

The code below highlights a row in a table when the mouse cursor is over a map marker.
This works, but not for all map markers, although there are values in the log.
I've tried using the trim() function on marker.on, but that's clearly not the problem. What could be the problem?
now the selection is like this
AAA no
BBB Yes
CCC no
DDD Yes
FFF-no
Mapscript
<script>
function createmaprker(dataArray) {
var map = L.map('viewmap').setView([51.56, -0.12], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
for (var i = 0; i < dataArray.length; i++) {
var marker = L.marker([dataArray[i][5], dataArray[i][6]]).addTo(map);
marker.bindPopup("Book: " + dataArray[i][2] + "<br>" + "Pages: " + dataArray[i][3]);
marker.on("mouseover", function(e) {
var popup = e.target.getPopup();
var content = popup.getContent();
var tr = $("#data-table").find("td").filter(function() {
return $(this).text() == content.split("<br>")[0].split(": ")[1];
}).closest("tr");
tr.addClass("highlight");
});
marker.on("mouseout", function(e) {
var popup = e.target.getPopup();
var content = popup.getContent();
var tr = $("#data-table").find("td").filter(function() {
return $(this).text() == content.split("<br>")[0].split(": ")[1];
}).closest("tr");
tr.removeClass("highlight");
});
}
}
</script>
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
function getData() {
var values=[['111', '1111', 'AAA', '752', 'Hardcover', '51.55', '-0.11'], ['222', '5555', 'BBB',' 1040', 'Hardcover', '51.55', '-0.10'], ['333', '777','CCC', '846', 'Hardcover', '51.565', '-0.11'], ['444', '888', 'DDD','258','Paperback', '51.56', '-0.12'], ['555', '555',' FFF',' 789','Hardcover', '51.55', '-0.13']]
return values;
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Scriptdata
<script>
google.script.run.withSuccessHandler(showData).getData();
function showData(dataArray){
console.log(dataArray);
createmaprker(dataArray);
$(document).ready(function(){
$('#data-table').DataTable({
data: dataArray,
columns: [
{"title":"Rating"},
{"title":"Reviews"},
{"title":"Book"},
{"title":"Pages"},
{"title":"Type"},
{"title":"Longitude"},
{"title":"Latitude"},
]
});
});
}
</script>
index
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css">
<?!= include('Scriptdata'); ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<style>
body {
margin: 0;
padding: 0;
}
#viewmap {
width: 60%;
height: 60vh;
left: 0%;
margin: auto;
}
#text {
font-family: Georgia, 'Times New Roman', Times, serif;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div class="container">
<br>
<div class="row">
<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
</table>
</div>
</div>
<div id="viewmap"></div>
<?!= include('Mapscript'); ?>
</body>
</html>
The problem is that the DataTables zebra-striping style is interfering with your attempts to highlight the rows with dark grey stripes.
One fix for this is to remove table-striped from your HTML table definition.
If you want to keep your zebra striping, you will need to add !important to your highlighting style:
.highlight {
background-color: yellow !important;
}
You can see an example of this in the official DataTables documentation: Highlighting rows and columns.
Click on the "CSS" tab on that page to see the style example they are using.
There is also a small typo in the data set here: ' FFF' - note that extra space before the first F.

leaflet.ajax: json feature not appearing on the map

I want to load geojson feature on the map. Intially the code below worked perfectly fine, later when I moved leaflet.ajax code to different lines, it stopped working. Tried everything I can think of but still is not working. It does not even enter the function when placing a break point with leaftlet.ajax function in google developer tool. Any response will be well appreciated. The code is as below:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webmap 101</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> //load bootstrap
<style>
#header{
height: 100px;
background-color: darkblue;
}
#mapdiv{
height: 800px;
background-color: salmon;
}
#side_panel{
height: 800px;
background-color: beige;
}
#footer{
height: 100px;
background-color: darkgrey;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin=""/> <!--leaftlet css-->
<script src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script> <!--leaflet-->
<script src="https://code.jquery.com/jquery-3.6.3.js"></script> <!--jQuery-->
<script src="resources/leaflet.ajax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.min.js"></script>
</head>
<body>
<div id="header" class="col-lg-12">
<h1 class="text-center" style="color:white">My Schools</h1>
</div>
<div id="side_panel" class="col-md-3">
<h1 class="text-center">Schools</h1>
</div>
<div id="mapdiv" class="col-md-9"></div>
<div id="footer" class="col-md-12">
<h4 id="map_coords" class="text-center">Lat: Lon: Zoom Level:</h4>
<h4 class="text-center">&copy:2023 MACS</h4>
</div>
<script>
var mymap = L.map('mapdiv')
mymap.setView([-37.91819148068221, 145.19098722558402], 9);
var backgroundLayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
});
mymap.addLayer(backgroundLayer);
mymap.on('mousemove',function(e){
var str = "Latitude: "+ e.latlng.lat.toFixed(5)+" Longitude: "+e.latlng.lng.toFixed(5)+" Zoom Level: "+mymap.getZoom();
$("#map_coords").html(str);
});
var geojsonLayer = new L.GeoJSON.AJAX('data/schoolWGS84.geojson', {pointToLayer:function(feature,latlng){
var str1 = "<h4>"+feature.properties.sch_name+"</h4><hr>";
debugger;
str += "<a href='"+ feature.properties.web+"' target='blank'>";
str += "<img src='img/"+feature.properties.img+"' width='200px'>";
str += "</a>";
return L.marker(latlng).bindPopup(str);
}});
geojsonLayer.addTo(mymap);
</script>
</body>
</html>`

My h1 keeps repositioning while I update it

Okay so I'm making this thing where I use the reddit api and i get a post number then spit out all the info from it. Now I am making a custom number input and here is images of me using it.
How it looks when i load it
How it looks when i update the number
Here's my code:
const numberText = document.querySelector("#numberText")
const modalOpenBtn = document.querySelector("#numberBtn")
const modal = document.querySelector("#modal")
const done = document.querySelector("#done")
modalOpenBtn.addEventListener("click", () => {
modal.showModal()
})
done.addEventListener("click", () => {
let number = document.querySelector("#number")
number.textContent = numberText.value;
modal.close()
})
// The code below is in another file
const add = document.querySelector('#add');
const subtract = document.querySelector('#subtract');
let number = document.querySelector('#number');
add.addEventListener('click', () => {
number.innerHTML = `<h1>${parseInt(number.textContent) + 1}</h1>`;
})
subtract.addEventListener('click', () => {
if (parseInt(number.textContent) <= 0) {
alert('Cannot subtract from 0');
} else {
number.innerHTML = `<h1>${parseInt(number.textContent) - 1}</h1>`;
}
})
body, h1 {
background: rgb(34, 116, 165);
color: rgb(250, 250, 255);
font-family: 'Dosis', sans-serif;
}
button {
background: none;
border: none;
cursor: pointer;
resize: none;
}
div, button {
display: flex;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>the most stupidest app ive ever made</title>
<script defer src="input.js"></script>
<script defer src="openModal.js"></script>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Dosis:wght#200;800&display=swap" rel="stylesheet">
</head>
<body>
<!-- intro -->
<h1>the most stupidest app ive ever made</h1>
<p>this app is from a reddit post with random knowledge; enter the number of the reddit post and you'll get it's info:</p><br>
<!-- buttons -->
<div>
<button class="add-subtract"><img src="add.svg" width="50" height="50" title="add" id="add"></button>
<button title="number" id="numberBtn"><h1 id="number">0</h1></button>
<button class="add-subtract"><img src="subtract.svg" width="50" height="50" title="subtract" id="subtract"></button>
</div>
<!-- da modal -->
<dialog id="modal">
<input type="number" id="numberText"><br>
<button id="done"><img src="./check.svg"></button>
</dialog>
</body>
</html>
Ask me any question in the comments regarding the code.
Help is appreciated. Thanks!!!
You should have inspected the layout first. You're adding a new h1 to the existing one. Thats what causing the shift. Instead replace the number inside it.
Just replace this line with
number.innerHTML = `<h1>${parseInt(number.textContent) + 1}</h1>`
to
number.innerHTML = `${parseInt(number.textContent) + 1}`
Since according to your comment you couldn't make this simple fix and say that solution isn't working for you, I'm adding the snippet you shared with the change I mentioned
const numberText = document.querySelector("#numberText")
const modalOpenBtn = document.querySelector("#numberBtn")
const modal = document.querySelector("#modal")
const done = document.querySelector("#done")
modalOpenBtn.addEventListener("click", () => {
modal.showModal()
})
done.addEventListener("click", () => {
let number = document.querySelector("#number")
number.textContent = numberText.value;
modal.close()
})
// The code below is in another file
const add = document.querySelector('#add');
const subtract = document.querySelector('#subtract');
let number = document.querySelector('#number');
add.addEventListener('click', () => {
number.innerHTML = `${parseInt(number.textContent) + 1}`;
})
subtract.addEventListener('click', () => {
if (parseInt(number.textContent) <= 0) {
alert('Cannot subtract from 0');
} else {
number.innerHTML = `${parseInt(number.textContent) - 1}`;
}
})
body, h1 {
background: rgb(34, 116, 165);
color: rgb(250, 250, 255);
font-family: 'Dosis', sans-serif;
}
button {
background: none;
border: none;
cursor: pointer;
resize: none;
}
div, button {
display: flex;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>the most stupidest app ive ever made</title>
<script defer src="input.js"></script>
<script defer src="openModal.js"></script>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Dosis:wght#200;800&display=swap" rel="stylesheet">
</head>
<body>
<!-- intro -->
<h1>the most stupidest app ive ever made</h1>
<p>this app is from a reddit post with random knowledge; enter the number of the reddit post and you'll get it's info:</p><br>
<!-- buttons -->
<div>
<button class="add-subtract"><img src="add.svg" width="50" height="50" title="add" id="add"></button>
<button title="number" id="numberBtn"><h1 id="number">0</h1></button>
<button class="add-subtract"><img src="subtract.svg" width="50" height="50" title="subtract" id="subtract"></button>
</div>
<!-- da modal -->
<dialog id="modal">
<input type="number" id="numberText"><br>
<button id="done"><img src="./check.svg"></button>
</dialog>
</body>
</html>
You can add position: relative to your navbar.
example for mi code
.navbar.navbar-inverse {
position: relative;
}
<div style="margin-top: 15px;text-align: center;" class="navbar navbar-inverse navbar-fixed-top container">

Change time based on input timezone with JS

I'd like to do a simple clocks project.
In this project the user has to choose a timezone from combobox and when click one of them, the main time (id=digital-clock) has to change with timezone time.
I've one txt file (zone.txt) which contain all timezones.
This is my code: (it doesn't work here as a snippet).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clockify</title>
<link rel="shortcut icon" href="http://cdn.onlinewebfonts.com/svg/img_461716.png">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<style>
body {
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradient 15s ease infinite;
height: 100vh;
font: open-sans-serif;
}
a {
text-decoration: none;
color: black;
}
#keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.dst-btn {
margin-right: 75px;
}
</style>
</head>
<body class="unselectable">
<div class="time-label">
<div id="analog-clock" class="clock" style="margin-left:200px; margin-top: -180px;">
<div class="hour">
<div class="hr" id="hr"></div>
</div>
<div class="min">
<div class="mn" id="mn"></div>
</div>
<div class="sec">
<div class="sc" id="sc"></div>
</div>
</div>
<div id="digital-clock" style="margin-top:-350px;"><span id="time" style="font-size:170px;font-weight:bold;color:#fff;"></span></div>
<br><br><br>
<div class="buttons animate__animated animate__bounceInUp" style="display: inline-block;">
<button type="button" class="btn btn-light btn-lg dst-btn">Alarm</button>
<select onchange="changeTimeZone();" style="padding: 10px;border-radius: 5px;padding-bottom:-2px;width:200px;" class="btn btn-light dst-btn" name="timezone-label" id="timezone-label" aria-required="true">
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.3/dist/umd/popper.min.js "></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.min.js "></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js "></script>
<script>
// Load data from file ['Europe/Rome, Europe/Amsterdam, etc.'] into combobox
$.ajax({
url: 'zone.txt',
success: function(data) {
var splitData = data.split("\n");
for(i = 0; i <= splitData.length; i++) {
$('#timezone-label').append("<option id='timezone-label' value='" + splitData[i] + "'>" + splitData[i] + "</option>");
}
}
});
</script>
</select>
<button id="style" type="button" class="btn btn-light btn-lg dst-btn">Style</button>
<button id="stopwatch" type="button " class="btn btn-light btn-lg dst-btn ">Stopwatch</button>
<button type="button" class="btn btn-light btn-lg dst-btn ">Countdown</button>
</div>
</div>
<script>
function changeTimeZone() {
var timeZone = document.getElementById('timezone-label');
const str = new Date().toLocaleString('it-IT', {
timeZone: timeZone
});
var myArray = str.split(",");
document.getElementById("time").innerHTML = myArray[1];
}
</script>
</body>
</html>
I tried to use this code , but it doesn't work :
function changeTimeZone() {
var timeZone = document.getElementById('timezone-label');
const str = new Date().toLocaleString('it-IT', {
timeZone: timeZone
});
var myArray = str.split(",");
document.getElementById("time").innerHTML = myArray[1];
}
I use boostrap 5, jquery and ajax in my project.
In my opinion, the problem is with this line: timeZone: timeZone. How can I do it? I want to set a timezone variable as attribute.
I've this error in javascript console:
Uncaught RangeError: Invalid time zone specified: [object HTMLSelectElement]
at Date.toLocaleString (<anonymous>)
at changeTimeZone (clocks.html:87)
at HTMLSelectElement.onchange (clocks.html:62)
timeZone: timeZone
change to
timeZone: timeZone.value
try => This

Access a Variable within a function in Javascript

I want to Check the woodCount Variable if it is equal to or greater than 25 I want to have a new button appear on the page. For now I just had it console.log true or false.
Sorry if this is really easy or makes no sense but I am new to Javascript. Thanks!
JAVASCRIPT FILE
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function(){
woodCount++;
wood.innerHTML = woodCount;
}
function fire() {
if woodCount >= 25 {
console.log('True');
}else{
console.log('False');
}
}
HTML FILE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>
Add a button to the DOM and keep it hidden. When it exceeds the threshold, toggle the display property from hidden to block.
Make sure we call the function where the toggling of style happens in the onclick event handler where incrementation occurs.
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function() {
woodCount++;
wood.innerHTML = woodCount;
fire();
};
function fire() {
if (woodCount >= 25) {
document.getElementById("higherThan25")
.style.display = "block";
} else {
//console.log("False");
}
}
.woodbtn {
border-style: solid;
border-color: white;
color: white;
padding: 10px 10px;
text-align: center;
font-size: 13px;
cursor: pointer;
float: right;
background-color: transparent;
}
.woodtxt {
text-color: white;
}
body {
background-color: black;
color: white;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
<input style="display: none;" class="woodbtn" type="button" value="Higher Than 25" id="higherThan25" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>

Categories

Resources