Remove JavaScript Default Keypress Events - javascript

HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="testdiv">
<button type="button"></button>
</div>
<body>
<html>
CSS:
button {
background-color: skyblue;
height: 75px;
width: 150px;
border-radius: 5px;
}
JavaScript:
const testdiv = document.querySelector('.testdiv');
document.addEventListener('click', (event) => {
console.log('I was clicked');
});
Open your console, now click the blue button. Then press the Enter key. Notice how the keypress caused the button to click. Now, click it again, but this time click in the white space afterwards and then press Enter. Notice that nothing is logged in the console.
Why does the enter key cause an element to be clicked after the element has been selected with the mouse, and how do you disable this feature?
If I wanted to map a keydown or keyup event for the Enter key to a different element without the console being logged in this program, I would have a serious problem.
I'm not sure the cause of this behavior. I noticed Tab exhibits a weird behavior too where if multiple elements are present and one is selected by the mouse, you can press Tab and it will select the next element. This doesn't bother me, but it's another example of these pre-bound key behaviors that I would like to be able to disable.

Try setting the property tabindex=-1 on the divs, that should help.

Related

Input field loses focus if I don't hold down left-mouse click

This is 100% of the code:
<html lang="en">
<head>
<title>Test</title>
<script defer src="index.js"></script>
</head>
<body>
<span id="spanName">Hi</span>
</body>
</html>
const mySpan = document.getElementById('spanName');
mySpan.addEventListener('click', e =>{
document.getElementById('spanName').innerHTML = "<form><input type=\"text\" placeholder=\"enter name\"></input></form>"
})
This essentially does what I want it to. When I click on this span, it replaces the inner HTML with the input form. The only problem is that it doesn't stay in focus unless you hold down the left mouse-key. There's nothing else using hover or focus or anything that would compete with the focus.
My best guess is it has something to do with the fact that I'm using the "on-click" event listener, and that's the thing competing with the focus, but clearly the form doesn't just disappear when I unclick the mouse, so the behavior is a little confusing for me.
Heads up, I'm quite new to JavaScript and based off the behavior, I assume that this isn't the correct way to go about this. I had started writing out a bunch of CSS (which I'm also new to), and I currently have a basic navbar at the top full of anchor tags that highlight when I hover over them, but I'm trying to add this into the navbar as a span so that it says "Login" and then when the user clicks on it, the span changes into a login/password form without affecting the other components of the navbar.
That said, aesthetically everything appears to working the way I intended to except for this focus issue. Since it's a problem in this minimal example, I'm assuming it's an issue independent of the other code I've written
Thanks in advance!
Just define an Id to your input and after call the focus function.
const mySpan = document.getElementById('spanName');
mySpan.addEventListener('click', e =>{
document.getElementById('spanName').innerHTML = "<form><input type=\"text\" id=\"myInput\" placeholder=\"enter name\"></input></form>";
document.querySelector("#myInput").focus();
})
<html lang="en">
<head>
<title>Test</title>
<script defer src="index.js"></script>
</head>
<body>
<span id="spanName">Hi</span>
</body>
</html>
Adding .focus() on the input element will help, as #Vinicius has demonstrated in his answer.
I modified your HTML a bit in that I replaced your <span> with a <form> element. In order to make it behave like a span I added some display:inline-block style to it. I also added an .onsubmit handler that will process the input value after you press return.
document.getElementById('frmName').onclick = e =>{
const frm=e.target
frm.innerHTML = "<input type=\"text\" placeholder=\"enter name\">";
const inp=frm.children[0];
frm.onsubmit=ev=>(console.log("you entered:",inp.value),false)
inp.focus();
}
form {display:inline-block; cursor: pointer}
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
abc<form id="frmName">Hi, click me!</form>def
</body>
</html>

Is there anyway to arrange these 2 links so that the link doesn't get written twice?

I got a page I got a link. The link goes to http://stackoverflow.com.
In addition, click anywhere on the link and it goes to http://stackoverflow.com too.
I am just curious. Is there a way to do so without writing stackoverflow.com twice?
Can I make the link in the link to be inactive and clicking the link means the user activate the code written in "onclick" on body?
This is the code:
<!doctype HTML>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Title</title>
<style>
#centerInScreen {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
#centerInScreen h1 {
position: relative;
top: 50%;
transform: translateY(-50%);
}
.auto-style1 {
text-align: center;
}
</style>
</head>
<body onclick="window.location.replace('http://stackoverflow.com');">
<div id="centerInScreen">
<h1 class="auto-style1">
Click here to Get Game and See Yourself</h1>
</div>
</body>
</html>
You can see the code in action here
http://romancepriorities.com/test/index2.html
Basically the link is part of the body. So I want body.onclick to be called when a user click the link.
You could give your a element an id, and then when the click event happens, you would get the element by that id, and call the click method on it:
<body>
<div id="centerInScreen">
<h1 class="auto-style1">
<a id="go" href="http://stackoverflow.com">Click here to Get Game and See Yourself</a>
</h1>
</div>
<script>
document.addEventListener('click', function() {
document.getElementById('go').click();
});
</script>
</body>
Note that as you had it, the behaviour was not the same: location.replace will not generate an entry in the browser history, so you cannot go back. Also, the body element does not necessarily fill the page, so not all clicks would be detected, like is the case with listening to the event on document.
Two-step link
If you want to have the link "inactive" until it is clicked, and only then allow a navigation to happen on a second click anywhere on the page, then use a variable:
<body>
<div id="centerInScreen">
<h1 class="auto-style1">
<a id="go" href="http://stackoverflow.com">Click here to Get Game and See Yourself</a>
</h1>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () { // after doc loaded
var hasClicked = false;
var go = document.getElementById('go');
document.addEventListener('click', function() {
// only when link was activate with previous click
if (hasClicked) go.click();
});
go.addEventListener('click', function() {
if (!hasClicked) { // not yet clicked before?
// log the fact that the link was clicked
hasClicked = true;
// but cancel the navigation
return false;
}
});
});
</script>
</body>
You would need to use some visual hints so this becomes user-friendly: with classes you could make the link "look" inactive until it receives its first click. Upon that click you could change the style, and maybe its text,...etc. But this goes beyond the question.

Force iPhone keyboard to appear over Safari window when I make an input visible

This may be simply impossible, judging from the many comments on this topic in StackOverflow from several years ago. However, in case I am missing something, here's the situation:
I have an html canvas element. When the user taps it, I make an input element visible. Ideally, the input gets the focus and on a mobile device, the native keyboard pops up.
And that's what happens on an Android device. However, when an iPhone user on Safari taps the canvas, the input appears but it doesn't get the focus and the native keyboard does not appear. The user has to tap the input element for the native keyboard to show up.
Does anyone have a way to make the keyboard show up on an iPhone without that last extra tap?
Here is a test case:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="box" style="width:100px;height:100px;position:relative;background-color:blue"></div>
<div id="holder">
<form>
<input id="in">
</form>
</div>
</body>
<script>
$(function() {
$("#holder").hide();
$("#box").mousedown(function() {
$("#holder").show({complete:function() {$("#in").focus();}});
});
});
</script>
</html>
Found a combination of strategies that works. Not sure why, but if I handle the tap in 'touchstart' instead of 'mousedown,' and add an extra call to 'focus,' the IOS device awards me focus and native keyboard:
$("#box").on("touchstart", function(e) {
$("#holder").show({complete:function() {$("#in").focus();}});
event.stopPropagation();
event.preventDefault();
$("#in").focus();
});

iPhone/Android browser occasionally follows link href instead of jQuery onclick event

I have a mobile web gallery page where I have a CSS floated "next" link. The CSS float property causes the link to have a display: block behavior on it. A jQuery touchstart event is bound to the link. When the user clicks on the link, the Javascript code bound to that touchstart event advances the gallery by one slide via Ajax. In other words, there is no page refresh.
However, I noticed that occasionally when I touch an area of the link's block space that is not the link text itself, the browser follows the href and causes a page refresh (because the URL has changed) instead of executing the Javascript code bound to the touchstart event.
Has anybody seen this before? Is there a way to fix this?
I simplified it down to this code below, and it still happens, although much less frequently.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Test</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<style type='text/css'>
.cont { width: 320px; }
.next { border-left: 1px solid #000; float: right; text-align: right; width: 65px; }
.msg { clear: both; width: 200px; }
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
if (event.type == 'touchstart') {
$(this).unbind('click');
}
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
</head>
<body>
<div class="cont">Next</div>
<div class="msg"></div>
</body>
</html>
I tested this on my iPhone and it seems to work. For some reason after registering a touchstart event you are unbinding the click events. Is there any reason for that?
When you click on the text of the link all it seems to register is indeed touch start, so unbinding click does not break things. I do believe, however, that when you touch outside the text link, but still within the block space it registers both a touchstart and click, so at this point you have already unbound click and it works as a regular link.
You should notice, that on your first click outside the bounds it never goes to yahoo.com. It's only the subsequent once that do that.
So in essence what you need to do is remove that unbind, as so:
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.next').bind('click touchstart', function(event) {
event.preventDefault();
$('.msg').append('<p>Click!</p>');
});
});//]]>
</script>
Is there any reason why you would want to unbind click?

disable/enable right click on a particular part of the html body

i want to disable right click on the webpage but i want enable right click on textarea. Hey wat is this provide answers dont post lot of comments on right click (lol). i dont care if people would see my source code, thats nt the point ... i just want to know how one can enable right click only in the textarea while disabling the rest
so any1 here know the javascript function that would perform the job ??
is the below code possible ??
<html>
<head>
<title> Your Title </title>
</head>
<body oncontextmenu="return false;">
<textarea oncontextmenu="return true;">
</textarea>
</body>
</html>
-thanx in advance
-miss subanki
To enable right click on a particular element on the body while disabling the right click on the rest of the body (in html), you wil have to put the required element (whose right click you want to enable) into an iframe. And disable the right click on main body like this....
Main Body
<html>
<head>
<title>Your Title</title>
</head>
<body oncontextmenu="return false;">
<iframe src="frame1.html">
</iframe>
</body>
</html>
frame1.html
<html>
<body>
<textarea> Your text, u can right click here </textarea>
</body>
</html>
if anyone else has a better answer please post it here, thanx everyone.
What about: http://www.dynamicdrive.com/dynamicindex9/noright2.htm
But there's not much point disabling right click, it's easy to bypass and get content.
http://www.quirksmode.org/js/events_properties.html#button has probably all the information you need. You get the click event and test to see which keycode it is. Then choose to return false or true depending on where the click came from.
I have found one solution:
document.superListener = document.addEventListener;
document.addEventListener = function(type, listener, useCapture){
if(type != 'contextmenu')
document.superListener(type, listener, !!useCapture);
};
from here:
https://stackoverflow.com/a/3009161/3649420
You can disable the right click using javascript to keep the honest people honest. But the not so honest people can easily reverse this. If you are interested read on "oncontextmenu" property of html elements.
let divs = $("div");
divs.each(function(i, v) {
$(v).on("contextmenu", function() {
return false;
})
})
$(".no").off("contextmenu");
body {
background: black;
}
.yes {
width: 100px;
height: 100px;
background: tomato;
text-align: center;
}
.no {
width: 100px;
height: 100px;
background: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="yes">No Click</div>
<div class="no"></div>
<div class="yes">No Click</div>
<div class="no"></div>
<div class="yes">No Click</div>
The off() method removes event handlers that were attached with on().
jsfiddle => https://jsfiddle.net/dare444/we91t5gd/183/

Categories