How to trigger click event with enter button? - javascript

I am building a very basic magic 8 ball type 'game' using vanilla javascript. I have a text field (for a user question) and a submit button underneath. At present, I have it working fine with a event listener for the submit button but am trying to also get the same result if a user was to click enter.
I saw on w3s that you can trigger a button click upon enter, as below...
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
// If the user presses the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
...but I can't seem to translate that into my own project. HTML and JS for my project below; I am trying not to use nested functions at the moment just to help with my understanding (as advised by my course mentor).
JavaScript
let question = document.querySelector('#userQuestion');
let button = document.querySelector('#shakeButton');
let answer = document.querySelector('#answer');
let options = [
'It is certain.',
'Signs point to yes.',
'Concentrate and ask again.',
'My sources say no.',
]
// Generate a random number
function generateAnswer() {
let index = Math.floor(Math.random() * 4);
let message = options[index];
answer.textContent = message;
answer.style.fontSize = '18px';
setTimeout(timeOut, 3000);
};
// Timeout function
function timeOut() {
answer.textContent = '8';
answer.style.fontSize = '120px';
};
// Enter button trigers click event
function enterButton (event) {
if (event.key === "Enter") {
event.preventDefault();
button.click();
}
};
//Event listener for button click
button.addEventListener('click', generateAnswer);
question.addEventListener("keypress", enterButton);
HTML
<!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">
<meta name="description" content="Magic 8 Ball, ask it anything and it will answer.">
<!-- Stylesheet & Font Awesome Links -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<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=Orbitron:wght#800&family=Press+Start+2P&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<!-- Stylesheet & Font Awesome Links End -->
<title>Magic 8 Ball</title>
</head>
<body>
<nav class="navbar">
<div class="container-fluid">
<a class="navbar-brand ms-auto" href="#">dc games</a>
</div>
</nav>
<!-- Header -->
<header class="heading">
<h1>The Magic 8 Ball</h1>
<p>Shake the Magic 8 Ball and it will answer your question.</p>
</header>
<!-- Header End-->
<!-- Magic 8 Ball -->
<div class="ball-black">
<div class="ball-white">
<p id="answer">8</p>
</div>
</div>
<!-- Magic 8 Ball End -->
<!-- User Question -->
<div class="user-input">
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2 userQuestion" placeholder="What is your question?" required>
<button type="button" class="btn" id="shakeButton">Shake!</button>
</div>
<!-- User Question -->
<!-- Footer -->
<footer>
<div class="copyright fixed-bottom">
<p>Copyright © dc games 2022</p>
</div>
</footer>
<!-- Footer End -->
<!-- JavaScript Links -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<!-- JavaScript Links End -->
</body>
</html>

You cannot have multiple Ids on a single DOMElement. If you remove inlineFormInputName2 from the id of the user question, your code will work.
You can only have multiple identifiers for a class.
classes are used for formatting with css and Ids to specifically identify an element.

Related

Autocomplete for address using Google Maps JavaScript API

I came across a challenge and I kindly needed your help. I was developing form input with one of the fields being address / location. I wanted to harness Google Maps API, with services such as AutoComplete and Address Geocoding. I have HTML and JS files. My main issue is that I wanted to tap invalid addresses that users might type and alert them that it is an error. Like for instance, if someone types an address that has not been suggested or types incomplete address, I should be able to tell them that it is not a valid address. This works but only when I press enter, and not submit. If I press submit, it submits the form and doesn't notify.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places">
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
//window.alert("No details available for input: '" + place.name + "'");
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="form.css">
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Libre+Franklin&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> -->
<!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
<title>Document</title>
</head>
<body>
<form action="" id="mform">
<div class="container">
<div class="row">
<!--Address Section-->
<div id="pac-container">
<input id="location-input" type="text" placeholder="Enter a location" />
</div>
<!--End of Address Section-->
<!--Form Submit Section-->
<div class="row fill-form">
<input name="submit" type="submit" id="submit" class="submit" value="Submit">
</div>
<!--End of Form Submit Section-->
</div>
</div>
<script src="places.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</form>
</body>
</html>
I have tried adding an submit event listener, but I cannot get what I expect
You need to first prevent the form from submitting and check place.geometry the way you check it on place_changed event. Show that nice swal message and then do whatever you want to if it's valid.
Here below is your own codes edited and checked before submit.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places">
function initMap() {
const input = document.getElementById("location-input");
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
//window.alert("No details available for input: '" + place.name + "'");
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
//Check before submit
document.getElementById('mform').addEventListener('submit', function(e){
e.preventDefault(); //prevent form submit
const place = autocomplete.getPlace(); //get place from autocomplete
if (!place.geometry) { //check if valid location
swal("Please fill all the *Required fields","Click okay to continue", "warning");
return;
}
});
}

I want to delete all checked lists pressing the delete button but I don't know how

I'm learning Javascript and now I'm making to-do list.I've finished the basic one but I want to add the delete button which delete all the checked lists to my to-do list.
I've tried some ways that I came up with and they all failed and I cannot find the answer by googling.
How can I do this ? If there is someone who know, please teach me . I'd appreciated if you could show me how.
this is my code ↓ the error happened saying cannot read property 'parentElement' of null at Object.deleteAll
deleteAll: function() {
let taskListItem, checkBox, checkBoxParent;
for (i=0; i<this.taskListChildren.length; i++){
taskListItem = this.taskListChildren[i];
checkBox = taskListItem.querySelector('input[type = "checkbox"]:checked');
checkBoxParent = checkBox.parentElement;
checkBoxParent.remove();
}
document.getElementById('deleteChecked').addEventListener('click', () => {
tasker.deleteAll();
});
🙏
// this is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="css/styles.css">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
<body onLoad = "tasker.construct();">
<div class="tasker" id="tasker">
<div class="error" id="error">Please enter a task</div>
<div class="tasker-header" id="tasker-header">
<input type="text" id="input-task" placeholder ="Enter a task">
<button id="add-task-btn"><i class="fas fa-plus"></i></button>
</div>
<div class="tasker-body">
<ul id="tasks">
</ul>
</div>
<button id="deleteChecked">Delete</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
You can use the jQuery library and solve it as follows.
Step 1) Define in your html button element:
<button id="button" onclick="reset()"> RESET </button>
Step 2) define the 'reset ()' function, like this
function reset()
{
$("input:chceckbox").removeAttr("chcecked");
}
Good luck!!

How to reload javascript without refreshing the page?

I have a webpage that links some javascript via tags. The script is amazon-localiser.js which will change an amazon link to one appropriate for the visitor. e.g. an Amazon.com link will swap to amazon.co.uk for a UK visitor or Amazon.de for a german visitor.It also appends to the link the relevant amazon affiliate link.
When the user lands on the page they click through some options (javascript) however by the time you reach an amazon link the page must be refreshed for the amazon-localiser.js script to work. I have tried using a page refresh in HTML but this sends me back to the very beginning of the questions. How do I reload the javascript without affecting the users location on the site?
The site is www.wfbsir.com, if you select "Scifi" then "Maybe" you will get to an amazon.com link, if you hover over it you will see it links to amazon.com if you refresh the page it will show you the link to your local store with an affiliate link appended.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>What book should I read?</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="app.css" />
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="col-xs-12 text-right">
<button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>
</div>
</div>
</div>
<div class="container main">
<div class="row">
<div class="c12 text-center">
<h1 data-bind="text: queryData().text"></h1>
<h3 data-bind="text: queryData().subhead"></h3>
<h3><a data-bind="text: queryData().link, attr: {href: url}"></a></h3>
<div class="option-group" data-bind="foreach: queryData().answers">
<button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>
</div>
<button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
<button class="btn btn-default" type="submit" data-bind="click: buyBook, visible: navHistory().length > 1">Buy the book</button>
</div>
</div>
</div>
<div class="push"></div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
<script src="app.js?v=0.4.0"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="amazon-localiser.js"></script>
<script>
</script>
I have tried using jQuery getScript and also window.location.reload(); but neither reload just the javascript, the only thing that I can find to work is F5/Refresh.
I noticed that the amazon-localiser.js invokes the function findLocation onload of the page, as you can see below.
if (window.addEventListener) {
window.addEventListener("load", findLocation, false)
} else {
window.attachEvent("onload", findLocation)
}
So, a possible solution to your problem, could be to invoke this function again when you need to update your amazon link.
I tried invoking it from the console and it works, so try to invoke findLocation() manually when needed and see if it serves your scope.
Simone
You can add dynamically script on the page with some condition, for example:
var script = document.createElement('script');
var src;
if (true) {
src = 'amazon.co.uk';
} else {
src = 'amazon.com';
}
script.src = src;
document.head.appendChild(script);
As gnllucena told, you can view the question or there is the solution.
Build the loader function:
Put the following code in the document
<script type="text/javascript">
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var newScript= document.createElement("script");
newScript.type = "text/javascript";
newScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
</script>
// place a button for reloading script.
<input type="button" name="reloadNewJs" value="Reload JavaScript" onClick="LoadMyJs('needed_script.js')">

click event not happening with bootstrap panel

I'm trying to make my own class with panels that open and close content using Bootstrap and jQuery (not an accordion, I want multiple open at a time). However, the click event isn't working for me and I have no idea why... I tried the "*" selector and the alert was working but it's not working when I try to associate it with specific elements.
Practice2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Practice 2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../static/css/prism.css">
<link rel="stylesheet" href="../static/css/styles.css">
<script src="../static/js/prism.js"></script>
<script src="../static/js/script.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="panel panel-default panel-toggle" id="demo">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code><br>
Explanation
</div>
</div>
</div>
</body>
</html>
script.js
// $(".panel-toggle:panel-header").click(function(){
// // $(this).next().toggle();
// alert("hello");
// });
$("#demo").click(function(){
alert("hello");
});
styles.css
.panel-toggle .panel-heading:after {
font-family:'Glyphicons Halflings';
content:"\e114";
float: right;
color: grey;
}
.panel-toggle .collapsed:after {
content:"\e080";
}
.panel-toggle .panel-body {
}
Clearly the rest of the code needs some adjustment but I'm just troubleshooting this part right now and would appreciate some advice on what I'm missing. Thanks!
With
HTML
<div class="panel panel-default panel-toggle">
<div class="panel-heading">solution</div>
<div class="panel-body">
<code class="language-python">
def solution(self):
func = self.functionGenerator()
length = self.endTime - self.initialTime
timesConcerned = [self.initialTime+x/1000. for x in range(length*1000)]
return odeint(func,self.initialValues,timesConcerned)
</code>
Explanation
</div>
</div>
JS
$(document).ready(function(){
$(".panel-heading").click(function(){
$(this).next().toggle("slow");
});
});
works
JSFiddle demo
You should put your jQuery code in document.ready block ensure your code working after those element been generated.
Script.js should be changed like this.
$(document).ready(function(){
$("#demo").click(function(){
alert("hello");
});
});

Swipe a div prints a message and disappear instead of display another div ( PhoneGap 2.9 - Android )

I want to have a swipe function in my first html page of the mobile application that I am implementing. I use Phonegap 2.9 and Eclipse. For this function, I used from this files the Page_scrolling.html and the JavaScripts it calls.
My head in .html file that I want to have the swipe function:
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Guide-Me For-All</title>
<link href='http://fonts.googleapis.com/css?family=Patrick+Hand|Permanent+Marker|Exo|Nunito|Limelight|Ubuntu|Montserrat|Audiowide|Architects+Daughter' rel='stylesheet' type='text/css'>
<!-- import stylesheets -->
<link rel="stylesheet" type="text/css" href="../../css/home/home.css">
<link rel="stylesheet" type="text/css" href="../../css/home/home-eng-fonts.css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css" />
<link rel="stylesheet" href="../../jQuery-Mobile-Bootstrap-Theme-master/themes/Bootstrap.css">
<!-- <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="http://twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css" rel="stylesheet" /> -->
<link href="css/main.css" type="text/css" rel="stylesheet" />
<!-- import js -->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="../../cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="../../jss/connect.js"></script>
<script type="text/javascript" charset="utf-8" src="../../jss/home/change_page.js"></script>
<script type="text/javascript" src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
<script type="text/javascript" src="../../plugins/jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="../../plugins/js/main.js"></script>
<script src="../../plugins/swipe.js"></script>
According to the link, I needed the last .css link and the last four .js links. The forth JavaScript is the one that is inside the Page_scrolling.html in the tutorial I put above. The only file that I changed, is the last JavaScript:
My Swipe.js contains :
$(function() {
$("#trust_us").swipe( { swipeLeft:swipe2, swipeRight:swipe2} );
$("#how_it_works").swipe( { swipeLeft:swipe2, swipeRight:swipe2} );
$("#owners").swipe( { swipeLeft:swipe2, swipeRight:swipe2} );
$("#sign_up_in").swipe( { swipeLeft:swipe2, swipeRight:swipe2} );
//Swipe handlers.
function swipe1(event, direction, distance, duration, fingerCount) {
$(this).text( "You have swiped " + direction +' with ' + fingerCount +' fingers' );
}
function swipe2(event, phase, direction, distance) {
$(this).text( phase +" you have swiped " + distance + "px in direction:" + direction );
}
});
//{ swipeStatus:swipe2, allowPageScroll:"horizontal"}
My body file is divided in the divs I want to swipe:
<body>
<div id="logo">
<img id="lg" src="../../imgs/logo.png" alt="Logo">
</div>
<div id="trust_us">
<div id="trust_us_h2">
<h3>Why you should trust us :</h3>
</div>
<ul>
<li><p>All the info about the shops, are being validated with their owners.</p></li>
<li><p>You can send your thoughts or complaints to the shops' owners, so that they will do improvements to it. *</p></li>
</ul>
<div id="notice">*Only for occasions when there was a contact between administrator - shop's owner!</div>
</div> <!--trust us-->
<div id="how_it_works">
<div id="how_it_works_h2">
<h3>How it works :</h3>
</div>
<div id="first">
<h5>First:</h5>
</div>
<div id="Sign_Up" class="float-left">
<img src="../../imgs/1sign-up.png" alt="Sign-Up">
<p> 1. Register</p>
</div>
<div id="Rate" class="float-right">
<img src="../../imgs/5rate.png" alt="Rate">
<p>5. Rate it according to your experience</p>
</div>
</div> <!--how it works-->
<div id="owners">
<div id="owners_h2">
<h3>For the owners of a shop :</h3>
</div>
<ol>
<li><p>Register</p></li>
<li><p>After that, you can take interesting reports and useful statistics about your shop. *</p></li>
<li><p>Now, you can do improvements to your shop according to what the customers need so you can get even more of them.</p></li>
</ol>
<div id="notice">*Contact the admin of the app for more information.</div>
</div> <!--owners-->
<div id="sign_up_in">
<h2>...REGISTER NOW OR SIGN IN...</h2>
Sign-Up Now!
</div>
<div id="last_line">
<br>
</div>
<div id="footer">
<p>Copyright (c) 2014 Guide-Me For-All. Design by Marialena S.</p>
</div>
</body>
What Is happening right now, Is when I swipe to the left or to the right a div, it disappears and in it's place it appears a message. And all the divs are in a vertical row. There are all viewable from the start when you scroll the page. What I want now, is when I swipe to the right the first div for example, to display the second div. In the same way I want to do the swipe to left function to display the previous div. That's all. I tried many other options but this looks the most simple.
I couldn't find the solution to my problem but I found this very nice tutorial and it's really simple to to do the swipe function. But if anyone finds my mistakes to the above code, please post the answer so that I can learn how to do the swipe function with this method too.

Categories

Resources