Not able to get Metamask popup to appear - javascript

I have managed to write the following code. The idea is to be able to get a pop up asking how much ETH I want to send.
But I am not able to get the pop-up. I have spent hours to fix this and not able to reach a conclusion.
I am able to get the popup sometimes but only when I refresh the page.
<!doctype html>
<html>
<head>
<title>MetaMask</title>
<style>
input[type=number], select {
width: 50%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.tip-button {
width: 304px;
height: 79px;
background-size: 100%;
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_over.png');
cursor: pointer;
}
.tip-button:hover {
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_over.png');
}
.tip-button:active {
background-image: url('https://github.com/MetaMask/TipButton/raw/master/images/1_pay_mm_off.png');
}
</style>
</head>
<body>
<h3>To Proceed please click the METAMASK LOGO below.</h3>
<h3>A popup will appear to ask you the ETH amount</h3>
<div class="tip-button"></div>
<div class="message"></div>
</body>
<script>
var MY_ADDRESS = '0x7266D19108705D60066f5d0c29f60893A7B1fE14'
var tipButton = document.querySelector('.tip-button')
tipButton.addEventListener('click', function() {
if (typeof web3 === 'undefined') {
return renderMessage('<div>Looks like you dont have <a href=https://metamask.io>MetaMask</a> to use this feature. <a href=https://metamask.io>https://metamask.io</a></div>')
}
var numSubmit = prompt("Please enter the ETH amount.");
if(isNaN(numSubmit)) {
numSubmit = prompt("A number is required.");
numSubmit = +numSubmit;
}
else {
numSubmit = +numSubmit;
}
var user_address = web3.eth.accounts[0]
web3.eth.sendTransaction({
to: MY_ADDRESS,
from: user_address,
value: web3.toWei(numSubmit, 'ether'),
gas: 232575,
gasPrice: 4000000000,
}, function (err, transactionHash) {
if (err) return renderMessage('There was a problem! Please reload the Page again.')
// If you get a transactionHash, you can assume it was sent,
// or if you want to guarantee it was received, you can poll
// for that transaction to be mined first.
renderMessage('Thank You')
})
})
function renderMessage (message) {
var messageEl = document.querySelector('.message')
messageEl.innerHTML = message
}
</script>
</html>
Thank you!

Related

How to add bg image to API weather project?

Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!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>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly

How to change the font color of an user input value (prompt) in JavaScript?

How can I change the color of the value of the variable number (nb)? How can I change the font color of an user input value (prompt) in JavaScript?
<html>
<head>
<style>
#block{
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
</style>
</head>
<body>
<div id="block">
</div>
<script>
window.onload = function printNumber(){
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if(nb == null || nb == ""){
unBlock.innerHTML = "No input number.";
}else{
unBlock.innerHTML = "Your input number is "+nb;
}
}
</script>
</body>
</html>
The code below illustrates two ways.
By creating a span with colored as its class, it turns it blue.
Subsequently, in my code, I'm overriding that by turning it red using javascript.
Either of those methods will work, but you only need one, not both. I used both just for illustration of your options.
window.onload = function printNumber() {
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if (nb == null || nb == "") {
unBlock.innerHTML = "No input number.";
} else {
unBlock.innerHTML = `Your input number is <span class='colored'>${nb}</span>`;
//the next line will select your span and override blue with red.
document.querySelector("span.colored").style.color = 'red';
}
}
#block {
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
span.colored {
color: blue;
}
<div id="block">
</div>

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

After auto scroll to bottom of div, enable user to scroll back up?

There are a large number of this question floating around this site. None of them seem to help me though. I am trying to code a text based browser game using javascript and jQuery, as a base to build my knowledge of coding.
I have a javascript code:
window.setInterval(function(e) { //This function is the only way to get the scroll to bottom to work, for me.
e = document.getElementById('console'); //'console' is the area that outputs the system text, after a user answers questions.
e.scrollTop = e.scrollHeight - e.clientHeight; //It works without the '- e.clientHeight', but I read that this is proper.
});
For the scroll to bottom function, this works very well, but how in the world do I allow the user to scroll up... to review what has transpired?
I haven't found a question asked in this fashion, so I don't believe it is a duplicate. If so, I guess I'll keep searching.
-Edit-
Okay... I guess my description wasn't descriptive enough, so let me try to fix that.
Here is a snipit of the first bit of my code (I know it isn't set up the best right now, but that is why I'm learning):
Javascript/JQuery
window.setInterval(function(e) { //'#console' scrolls to bottom <-- how do I let the user scroll up to review?
e = document.getElementById('console');
e.scrollTop = e.scrollHeight - e.clientHeight;
});
onkeyup = (function(e) { //On <enter> erase data in the ("input")
if (e.keyCode == 13) {
$("input").val("");
e.preventDefault();
return false;
}
});
$(document).ready(function() {
$("#console").fadeIn(3000); //A console to output answers and scenarios to
$("form").submit(function() { //User input
var input = $("#command_line").val(); //A nifty box to put your answers in
var check = false;
function check() { //If you don't follow directions this happens
check = true;
}
//startup
var yes = false;
var no = false;
currentarea = "Start";
function start() {
while (yes != true && no != true && currentarea == "Start") {
if (input == "yes") {
yes = true;
$("<p>Great! What is your gender? Type <u><b>m</b></u> for Male or <u><b>f</b></u> for Female.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
clothes = s_clths;
document.getElementById("clothes").innerHTML = clothes;
currentarea = "Gender Assignment";
check();
return currentarea;
}
}
start();
});
So, basically, after getting the scroll to bottom working, I noticed users might want to scroll up to see what previous statements said. Right now, they cannot scroll up. If I need to make another code all together that is okay, but I cannot find one that will work for me. I've tried every suggestion I could find from all the relative postings, with no success. I have been at this for about twelve hours now, and can't figure it out by myself.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="scripts/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="banner">
<p>Welcome To ! An Epic Journey Awaites You!</p>
</div>
<div id="console_wrapper">
<div id="console">
<p id="Start">Would you like to begin your adventure? Type <u><b>yes</b></u> or <u><b>no</b></u>.</p>
<p id="message_help" style="display: none;">Some help, if you need it.</p>
<!--
PLACEHOLDER: THIS IS WHERE YOUR CHOICES ARE INPUTED
-->
<div id="placeholder"></div>
</div>
</div>
<form id="form" onsubmit="return false;">
<input type="text" size="50" autofocus="autofocus" autocomplete="off" id="command_line" />
</form>
<script type="text/javascript" src="scripts/game.js"></script>
</body>
</html>
CSS
#banner {
width: auto;
background-color: maroon;
border-style: ridge;
border-width: 5px;
border-color: grey;
text-shadow: 2px 2px orange;
}
#console_wrapper {
border-style: ridge;
border-width: 3px;
border-color: grey;
max-height: 150px;
margin: 75px auto;
margin-top: 12px;
width: 44%;
}
#console {
display: none;
height: 150px;
text-align: center;
margin-top: 0px;
overflow-y: scroll;
}
#command_line {
font-family: Times New Roman;
font-size: 14px;
border-style: ridge;
border-color: blue;
border-width: 4px;
margin: auto;
}
body {
background-color: black;
border-style: ridge;
border-width: 5px;
border-color: red;
width: 90%;
max-height: 900px;
margin: auto;
}
The answer to my question was:
$("#console").animate({ scrollTop: "999999999px" }, 'slow'); //Scroll the console to the bottom.

Chat with only javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to make a chat in a long time, but I had no succes in making it.
I tried alot of ways, but making it insert the msg to my database and then with javascript refresh the chat every second, and get the msg from database, but that dosent work that well.
I was wondering is theire a way to make a chat with only javascript?
So it appends to a div all the users can see.
I saw some sites do this but I haven't been able to do it myself.
Yes - You can make a chat client that takes advantage of Websockets.
The only thing required is that you run a server in order to forward requests to other clients as they arrive.
The server can be written in a variety of different languages -- some of the most popular are C/C++ (Qt), node.js, Python, and go.
There are more languages which can provide this as ability as well ---
This came from http://www.tutorials.kode-blog.com/websocket-chat-client
var output;
var websocket;
function WebSocketSupport() {
if (browserSupportsWebSockets() === false) {
document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
var element = document.getElementById("wrapper");
element.parentNode.removeChild(element);
return;
}
output = document.getElementById("chatbox");
websocket = new WebSocket('ws:localhost:999');
websocket.onopen = function(e) {
writeToScreen("You have have successfully connected to the server");
};
websocket.onmessage = function(e) {
onMessage(e)
};
websocket.onerror = function(e) {
onError(e)
};
}
function onMessage(e) {
writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}
function onError(e) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}
function doSend(message) {
var validationMsg = userInputSupplied();
if (validationMsg !== '') {
alert(validationMsg);
return;
}
var chatname = document.getElementById('chatname').value;
document.getElementById('msg').value = "";
document.getElementById('msg').focus();
var msg = '#<b>' + chatname + '</b>: ' + message;
websocket.send(msg);
writeToScreen(msg);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function userInputSupplied() {
var chatname = document.getElementById('chatname').value;
var msg = document.getElementById('msg').value;
if (chatname === '') {
return 'Please enter your username';
} else if (msg === '') {
return 'Please the message to send';
} else {
return '';
}
}
function browserSupportsWebSockets() {
if ("WebSocket" in window) {
return true;
} else {
return false;
}
}
body {
font: 12px arial;
color: #222;
text-align: center;
padding: 35px;
}
#controls,
p,
span {
margin: 0;
padding: 0;
}
input {
font: 12px arial;
}
a {
color: #0000FF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
#wrapper,
#loginform {
margin: 0 auto;
padding-bottom: 25px;
background: #66CCFF;
width: 504px;
border: 1px solid #ACD8F0;
}
#chatbox {
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 270px;
width: 430px;
border: 1px solid #ACD8F0;
overflow: auto;
}
#chatname {
width: 395px;
border: 1px solid #ACD8F0;
margin-left: 25px;
float: left;
}
#msg {
width: 395px;
border: 1px solid #ACD8F0;
}
#submit {
width: 60px;
}
<!DOCTYPE html>
<html>
<head>
<title>WebSocket PHP Open Group Chat App</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="websocket_client.js"></script>
</head>
<body onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<div id="wrapper">
<div id="menu">
<h3 class="welcome">Welcome to WebSocket PHP Open Group Chat App v1</h3>
</div>
<div id="chatbox"></div>
<div id="controls">
<label for="name"><b>Name</b>
</label>
<input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here" />
<input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" />
<input name="sendmsg" type="submit" id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
</div>
</div>
</body>
</html>

Categories

Resources