I am writing an interactive application where user performs operations using keyboard. Most of the keystrokes are captured properly and executed, but on chrome when I press (ctrl + t) a new tab opens up, instead of calling my keypress event. Where as it works perfectly on Firefox and Internet Explorer, here is the sample code
<html>
<head>
<style>
#section {
width: 80%;
height: 500px;
background: grey;
margin: auto;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#section").keydown(function(e) {
stopEvent(e);
console.log(e.key + " down");
});
function stopEvent (e) {
e.stopPropagation();
e.preventDefault();
}
});
</script>
</head>
<body>
<div id="section" tabindex="1">
<h2>Keyboard operations</h2>
</div>
</body>
</html>
See if this is of any help,
From: http://unixpapa.com/js/key.html
On keydown and keyup, the event objects also have flags that indicate
which modifier keys were being pressed when the key was typed. These
are:
event.shiftKey
event.ctrlKey
event.altKey
event.metaKey
Related
I have a div that I made focusable with tabindex, and I want it to act like a button, doing something on both mouse click and enter key press. Can you do this with a single event listener, combining the following into one?
document.getElementById("myId").addEventListener("click", function() {
console.log("click");
});
document.getElementById("myId").addEventListener("keyup", function(e) {
if(e.keyCode === 13) {
console.log("click");
}
});
You can put the events to handle in an Array and use forEach to add the event listener to the element.
<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
div.addEventListener(ev, function(e){
if(ev=="click"){
console.log("click");//clicked
}
if(e.keyCode==13){
console.log("click");//enter key pressed
}
});
});
</script>
You can also define a function that both of the event listeners call.
<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
div.addEventListener(ev, handleEvent);
});
function handleEvent(e){
if(e.type=="click"){
console.log("click");//clicked
}
if(e.keyCode==13){
console.log("click");//enter key pressed
}
}
</script>
No, you need to use two listeners, but as you have to pass a function to the listener which is called and gets all the necessary arguments you can create a single function for both cases like this:
function handleEvent(e){
if(e //make sure a mouseEvent has been passed as argument
&&
e.keyCode === 13 //check for the correct key
){
console.log("click");
}
}
document.getElementById("myId").addEventListener("click", handleEvent);
document.getElementById("myId").addEventListener("keyup", handleEvent);
If you'd like just take the enter key, click, you can use the "click" event that will trigger the following inputs: "Enter", "Space" and "Click"
You can test it 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>TEST</title>
</head>
<body>
<button id="test">TEST</button>
</body>
<script>
const testBtn = document.getElementById("test");
testBtn.addEventListener("click", (event) => {
console.log("Hello world");
});
</script>
</html>
I thinks this is the best answer
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
I am working on a iframe android app on phonegap. I use phonegap build to compile my code online. For a day,I am searching for a code that pop out confirmation box that shows "do you want to exit?" yes|no ?? I comeout with these code.But it is not working.Can you help out? do we have to add any plugin in config.xml?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Layout</title>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false); //Listen to the User clicking on the back button
}
function onBackKeyDown(e) {
e.preventDefault();
navigator.notification.confirm("Are you sure you want to exit ?", onConfirm, "Confirmation", "Yes,No");
// Prompt the user with the choice
}
function onConfirm(button) {
if(button==2){//If User selected No, then we just do nothing
return;
}else{
navigator.app.exitApp();// Otherwise we quit the app.
}
}
</script>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#content
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="content">
<iframe width="100%" height="100%" frameborder="0" src="#" />
</div>
</body>
</html>
For Apache Cordova / Phonegap you don't need any plug-in for the native events (like deviceready orbackbutton) but you need the cordova-plugin-dialogs plug-in to show the native alerts.
So, I'm guessing that your problem is not to catch the event, but to show the alert.
Please, try just ti print a classic window.alert(), to verify if the event is catch, after that you can try with the dialog plug-in.
I think two changes are there in your code
first, if you haven't added cordova.js then please add it to your header section of file
second, before calling backbutton event you need to give some time to complete loading of the page otherwise it will not understand the back button click event
So here I just added timeout to your function
function onDeviceReady() {
setTimeout(function(){
document.addEventListener("backbutton", onBackKeyDown, false); //Listen to the User clicking on the back button
},500);
}
Here is my working code too.
$(document).ready(function(){
setTimeout(function(){
document.addEventListener('backbutton', function(e){
if (confirm("Are you sure you want to exit app?"))
{
navigator.app.exitApp();
}
}, false);
}, 500);
}
here is my working code on pressing backbutton it will ask for exit
document.addEventListener("backbutton", function (e) {
e.preventDefault();
navigator.notification.confirm("Are you sure want to exit from App?", onConfirmExit, "Confirmation", "Yes,No");
}, false);
function onConfirmExit(button) {
if (button == 2) { //If User select a No, then return back;
return;
} else {
navigator.app.exitApp(); // If user select a Yes, quit from the app.
}
}
I have got the problem, that a window with the file content pops up though e.stopPropagation() is called. When I drag the file from the desktop in the div in my browser, my current tab is reloaded with the new content (pictures, text). As a browser I am using Chrome, but I have also tried it with Safari and Firefox!
I simply don't get it, here's my code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>File Uploader</title>
<link href="../styles/allgemein.css" rel="stylesheet" type="text/css"/>
<link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!--<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">//-->
<!--<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap-theme.min.css">//-->
<!--<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>//-->
</head>
<body style="position:relative;">
<script>
var dropZone = document.getElementById('drag_upload');
dropZone.addEventListener('drop', handleDrop, false);
</script>
<script>
$(document).ready(function () {
$("#home").button();
$("#frm_logout").button();
});
function handleDrop(e) {
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault();
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
alert(files[i]);
}
}
</script>
<div style="width:100%; text-align:center; font-family: Arial; font-size:28px;"><b>Cloudservice</b></div>
<form action="../" method="post">
<input type="submit" name="logout" value="Logout" id="frm_logout" style="z-index: 1000; float:right;"/>
</form>
<input type="button" value="Home" id="home"/>
<div style="width:100%; font-size:18px; text-align:left; font-family:Arial; position:absolute; left:5px; top:100px;">
<?php echo "User: " . $user . "<br/>Maximum <br/>upload size: " . $size . " MB<br/><br/>"; ?>
<a href="fileupload">
<div
style="width: 125px; height: 40px; background-color: #003366; text-align: center; font-family: Arial; border-radius: 10px; color:#CCC;">
<div style="top: 10px; position: relative;">Fileupload</div>
</div>
</a><br/>
<div style="width: 250px; height: 435px; border: 2px solid #003366; border-radius: 15px;">
<div style="position: relative; top:200px; text-align: center;" id="drag_upload">Drop File here to upload!</div>
</div>
</div>
</body>
</html>
Deleted Answer:
You'll need to use e.preventDefault() in conjunction
with e.stopPropogation() as the default behavior is to load the file
in the current tab.
Why it's wrong is that you had preventDefault, but it's also possible the event is out of scope. e.stopPropogation() will only prevent the event from going higher up the DOM tree to parent elements. Here's some clean-up of the code that tested fine for me:
$(document).ready(function () {
$("#home").button();
$("#frm_logout").button();
});
$('body').on('dragover drop', function(e) { e.preventDefault(); });
$(document).on('draginit dragstart dragover dragend drag drop', function(e) {
e.stopPropagation();
e.preventDefault();
});
$("#drag_upload").on('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
$(this).addClass('dragHover');
}).on('dragleave dragend', function(e) {
e.stopPropagation();
e.preventDefault();
$(this).removeClass('dragHover');
}).on('drop', function(e) {
e.stopPropagation(); // Stops parent elements from receiving event.
e.preventDefault(); // Stops some browsers from redirecting.
$(this).removeClass('dragHover');
$(this).addClass('loading');
if (window.FileReader) {
if (e.originalEvent.dataTransfer.files.length<1) {
// do stuff here
}
}
else alert('Internet Explorer 9 and below are not supported for this feature.');
});
I removed </script><script> as you can just continue the previous.
I used e.preventDefault() directly on both body & document to make sure it's not going to redirect the browser, although using both e.preventDefault() and e.stopPropogation() in the event should accomplish this, I'd rather be safe than sorry.
I made the functions inline using JQuery's .on() which has proven to be the most reliable way to me of binding events.
I also added some classes that are set/unset during the events, really just copy/paste remnants from code I use, but they're useful for styling the elements when events occur. Leave them or delete them, this is more for the user than yourself.
Next, you'll want to make sure the browser is capable of window.FileReader as there is no IE support below version 10.
Last, e.dataTransfer.files does not exist. You'll need e.originalEvent.dataTransfer.files (although as you've written it I'm not sure it's that way due to the scope of the event in the different methods).
I want to detect mouse speed, for example the event will be fired only if the detected number is greater than 5
I found one example which I think is something similar: http://www.loganfranken.com/blog/49/capturing-cursor-speed/
but i am not able to make it see the number which is inside div and fire the event based on the resulting number, this is my attempt:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.cursometer.1.0.0.min.js"></script>
<script>
$(function() {
var $speedometer = $('#speedometer');
$('#test-area').cursometer({
onUpdateSpeed: function(speed) {
$speedometer.text(speed);
},
updateSpeedRate: 20
});
$("#test-area").mouseover(function(){
if(this.value > 5) {
console.log("asdasd");
}
else {
console.log("bbb");
}
})
});
</script>
<style>
#test-area
{
background-color: #CCC;
height: 300px;
}
</style>
</head>
<body>
<div id="test-area"></div>
<div id="speedometer"></div>
</body>
</html>
(I'm the author of the plug-in that's causing the trouble here)
The example isn't working because this.value isn't referring to the speed (it's undefined). Here's an updated version of your example:
http://jsfiddle.net/eY6Z9/
It would probably be more efficient to store the speed value in a variable rather than within the text value of an HTML element. Here’s an updated version with that enhancement:
http://jsfiddle.net/eY6Z9/2/
Hope that helps!
I am building a website specifically for the iPad. I am attempting to get drag & drop to work but the ondrop event seems to never fire for some reason.
Can you help me get the div to detect when I drop an element on top of it?
I have a very simple HTML page that demonstrates that the ondrop event is never fired in Safari. This fails in both desktop safari & ipad safari.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> </title>
<style type="text/css">
<!--
body {
margin: 100px;
}
.dropTarget {
width: 300px;
height: 100px;
float: left;
display: inline;
margin: 10px;
background-color: green;
-webkit-user-drop: element;
}
.drag {
width: 100px;
height: 100px;
background-color: red;
-webkit-user-drag: element; /*element*/
}
-->
</style>
<script type="text/javascript">
<!--
function onDrop(e, ele) { alert("drop"); }
-->
</script>
</head>
<body>
<div class="drag">
</div>
<br/>
<div class="dropTarget" ondrop="onDrop(e,this);">
</div>
<br/>
</body>
</html>
You need to cancel the dragover event's default action before you can use the drop event for something, otherwise the browser ignores it.
Change your dropTarget <div> from this:
<div class="dropTarget" ondrop="onDrop(e,this);">
To this:
<div class="dropTarget" ondragover="return false;" ondrop="onDrop(event,this);">
If you use inline event registration you have to use event to pass the event instead of e.
Another reason might be:
In reference with the drag-and-drop-processing-model, the drop event surprisingly does not get fired if the platform is changing the e.dataTransfer.dropEffect which (preferably should match) is not matching with e.dataTransfer.effectAllowed property of the event.