How can I connect a specific keyboard key to a DIV element? - javascript

I have looked online for answers on how to connect a specific keyboard key to a div element and so far what I have been able to only see was how to do a general key(onkeydown) What I am looking for is being a able to press a specific key by using keyCodes to detect that key so that it can call up a DIV element by id and make it active
var inpt = document.getElementById("11w");
inpt.addEventListener("keyup", function(e){
e.preventDefault();
if (e.keyCode==49)
document.getELementById("11w").click();
}
});

First thing, there is a syntax error in your code.
var inpt = document.getElementById("11w");
inpt.addEventListener("keyup", function(e){
e.preventDefault();
if (e.keyCode==49)
document.getELementById("11w").click();
}//<--------- syntax error
});
As I understand your question, this may be one of the solutions:
<textarea id="11w" placeholder="Press 1 or write 1"></textarea>
<br/>
<button id="btn">My value will change</button>
<script>
var inpt = document.getElementById("11w");
inpt.addEventListener("keyup", function(e){
e.preventDefault();
console.log(e.keyCode);
if (e.keyCode==49){
document.getElementById("btn").click();
}
});
document.getElementById("btn").addEventListener("click", function(e){
document.getElementById("btn").innerHTML = "I am clicked";
console.log("btn clicked");
});
</script>

You can listen on keyup events of the document then do what you please with each key.
DEMO
// Assingin to the keyup event of the document
document.onkeyup = (e) => {
// Getting the div element by it's id #test
const div = document.querySelector('#test');
// e.which returns the ascii code of the key that has been pressed
switch (e.which) {
case 83:
// 83 is lower case 's' (show) so we set the div to be block
div.style.display = 'block';
break;
case 72:
// 72 is lower case h (hide) so we set the div to be none
div.style.display = 'none';
break;
}
};
div {
width: 150px;
height: 150px;
background: blue;
}
<div id="test"></div>
This is just an example showing you how to bind a key to a certain element, it is not by any means bind to it, it just depends on the logic, we can add more logic to control two or more element with press of one key.
the point is that the code you write for each key will fire where you're even when you're typing in an input, that can be avoided, however i'll leave it to you :)

Related

I have to double click the follow button to functioning this is due to using click event 2 time

I am working on follow button and with the help of JavaScript I've come up with the following code.
But the problem is I have to double click the follow button to functioning this is due to using click event 2 time. I am open to better methods of solving this too.
var value = null;
const onClick = (event) => {
// event.target.id
value = event.target.id;
console.log(value);
document.getElementById(`${value}`).addEventListener('click',function(){
// console.log(value.id);
if(this.classList.contains('follow')){
this.classList.remove('follow');
this.innerHTML ="Following";
this.style.backgroundColor = 'green' ;
}else{
this.classList.add('follow');
this.style.backgroundColor = 'rgb(27,18,83)' ;
this.innerHTML="Follow";
}
})
}
window.addEventListener('click', onClick);
There is a double click event. You can check the if it satisfies your requirement.
MDN link - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
For multiple buttons with the same function, I would give all of them the same class (e.g. "btn"). Then in JS simply get all of the elements with this class, loop over the HTMLCollection which you would get and assign each element an eventlistener. When you want to change something on the button you have to use event.target in the function:
let buttons = document.getElementsByClassName("btn");
for (btn of buttons) {
btn.addEventListener("click", (event) => {
if(event.target.classList.contains('follow')){
event.target.classList.remove('follow');
event.target.innerHTML ="Following";
event.target.style.backgroundColor = 'green' ;
}else{
event.target.classList.add('follow');
event.target.style.backgroundColor = 'rgb(27,18,83)' ;
event.target.innerHTML="Follow";
}
});
}
<button class="btn">1</button>
<button class="btn">2</button>

Capture written text without focusing input element

I am trying to achieve simple scenario:
I want to capture keyboard events on the document
I want to update text from those events like the input element or textarea does
To put that in an example, imagine that you have some element with focus and you want to track the text that's written into it (for example some simple filtering). I don't want to create some visible input element and giving it focus.
I tried naive solution like delegating event to another element (input in this case), because I still need to translate keyCode to valid character according to system locale etc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function initialize() {
console.log('initializing');
var body = document.getElementsByTagName('body')[0];
var input = document.getElementById('text');
function delegateEvent(e) {
if (e.__delegate) {
return;
}
var ev = new e.constructor(e.type, e);
ev.keyCode = e.keyCode;
ev.__delegate = true;
input.dispatchEvent(ev);
}
body.addEventListener('keydown', function (e) {
delegateEvent(e);
}, false);
body.addEventListener('keyup', function (e) {
delegateEvent(e);
}, false);
input.addEventListener('keydown', function (e) {
console.log('input keydown', e);
});
input.addEventListener('keyup', function (e) {
console.log('input keyup', e);
});
}
</script>
</head>
<body onload="initialize()" tabindex="0">
<div>
<input type="text" id="text" />
</div>
</body>
</html>
However this does not work for me. For some reason unknown to me, the KeyboardEvent is delegated to input element, but it does not change text at all.
What's wrong with that example?
Is there any better way how to achieve results in my given case? Simply I need to update text, that's being processed by some non-input element.
This might help:
var input = document.getElementById('text');
function appendCharacter (c) {
switch (c) {
case 8: // Backspace
input.value = input.value.slice(0, -1);
break;
default:
input.value = input.value + String.fromCharCode(c);
}
}
// Keypress gets the keyCode of the current character not key.
// e.g. pressing the 'A' key will result in 'a' unless 'Shift' is also held.
window.addEventListener('keypress', function (e) {
console.log(e.charCode)
console.log(e.keyCode)
appendCharacter(e.keyCode);
});
// Use Keydown to get special keys like Backspace, Enter, Esc.
window.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 8: // Backspace
e.preventDefault(); // Stops the backspace key from acting like the back button.
appendCharacter(e.keyCode);
break;
}
});
Try it out: https://jsfiddle.net/vuoriliikaluoma/9u29wyzd/

Function activate after two onclicks

Hey I'm using javascript+html only.
Is there any way to activate a function after the button has been clicked two (or more) times? I want the button to do NOTHING at the first click.
For a "doubleclick", when the user quickly presses the mouse button twice (such as opening a program on the desktop), you can use the event listener dblclick in place of the click event.
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/dblclick
For a quick example, have a look at the below code. http://jsfiddle.net/jzQa9/
This code just creates an event listener for the HTMLElement of "item", which is found by using getElementById.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('dblclick',function(e) {
var target = e.target || e.srcElement;
target.style.backgroundColor = 'red';
},false);
</script>
As for wanting the user to click an element X times for it to finally perform an action, you can do the following. http://jsfiddle.net/5xbPG/
This below code works by adding a click tracker to the HTMLElement and incrementing the click count every time it's clicked. I opted to save the clicks to the HTMLElement instead of a variable, but either way is fine.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('click',function(e) {
var target = e.target || e.srcElement;
var clicks = 0;
if(target.clicks)
clicks = target.clicks;
else
target.clicks = 0;
if(clicks >= 4) {
target.style.backgroundColor = 'red';
}
target.clicks += 1;
},false);
</script>
== UPDATE ==
Since you recently posted a comment that you want two different buttons to be clicked for an action to happen, you would want to do something like this... http://jsfiddle.net/9GJez/
The way this code works is by setting two variables (or more) to track if an element has been clicked. We change these variables when that item has been clicked. For each event listener at the end of changing the boolean values of the click state, we run the function checkClick which will make sure all buttons were clicked. If they were clicked, we then run our code. This code could be cleaned up and made to be more portable and expandable, but this should hopefully get you started.
<input type="button" id="button1">
<input type="button" id="button2">
<div id="result" style="width:15px;height:15px;background-color:black;"></div>
<script>
var result = document.getElementById('result');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button1Clicked = false;
var button2Clicked = false;
button1.addEventListener('click',function(e) {
button1Clicked = true;
checkClick();
},false);
button2.addEventListener('click',function(e) {
button2Clicked = true;
checkClick();
},false);
function checkClick() {
if(button1Clicked && button2Clicked) {
result.style.backgroundColor = 'red';
}
}
</script>
Two ways you can do this, one would be to have a data attribute within the html button that identifies whether the click has been done.
<button id="btn">Click Me!</button>
<script>
var clickedAlready = false;
document.getElementById('btn').onclick = function() {
if (clickedAlready) {
//do something...
}
else
clickedAlready = true;
}
</script>
While global variables aren't the best way to handle it, this gives you an idea. Another option would be to store the value in a hidden input, and modify that value to identify if it's the first click or not.
Maybe something like this?
var numberTimesClicked = 0;
function clickHandler() {
if (numberTimesClicked > 0) {
// do something...
}
numberTimesClicked++;
}
document.getElementById("myBtn").addEventListener("click", clickHandler);

How to manage events on a specific div?

I would like to catch some events for a specific div if the user clicked on the div (focus the div), keyboard events are catch (not if the last click was out of the div (unfocus the div)
I tried some things, but haven't succeeded : JSFiddle
document.getElementById("box").onkeydown = function(event) {
if (event.keyCode == 13) { // ENTER
alert("Key ENTER pressed");
}
}
This code doesn't work even if I click on the div.
Pure JS solution please
The div element isn't interactive content by default. This means that there isn't a case where the return key will ever trigger on it. If you want your div element to be interactive you can give it the contenteditable attribute:
<div id="box" contenteditable></div>
In order to now fire the event you need to first focus the div element (by clicking or tabbing into it). Now any key you press will be handled by your onkeydown event.
JSFiddle demo.
Giving the 'div' a tabindex should do the trick, so the div can have the focus:
<div id="box" tabindex="-1"></div>
If you click on the div it gets the focus and you can catch the event.
JSFIDDEL
If you set 'tabindex' > 0 you can also select the div using TAB.
You could catch all the click events, then check if the event target was inside the div:
var focus_on_div = false;
document.onclick = function(event) {
if(event.target.getAttribute('id') == 'mydiv') {
focus_on_div = true;
} else {
focus_on_div = false;
}
}
document.onkeyup = function(event) {
if (focus_on_div) {
// do stuff
}
}
try this code i hope this work
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
window.onkeydown = function(event) {
var x = mousePosition.x;
var y = mousePosition.y;
var elementMouseIsOver = document.elementFromPoint(x, y);
if(elementMouseIsOver.id == "box" && event.keyCode == "13") {
alert("You Hate Enter Dont You?");
}
}
DEMO

How to detect control+click in Javascript from an onclick div attribute? [duplicate]

This question already has answers here:
How can I check if a key is pressed during the click event with jQuery?
(5 answers)
Closed 5 years ago.
I need to know if the user is clicking or CONTROL CLICKING a div element.
I have seen examples on how to do it using event listeners.. but my code is already set in place, and is using an on-element onclick method..
HTML
<div id='1' onclick='selectMe()'>blah</div>
JS
function selectMe(){
//determine if this is a single click, or a cntrol click
}
...also would love to know if it was a left or right mouse button click.
In your handler, check the window.event object for the property ctrlKey as such:
function selectMe(){
if (window.event.ctrlKey) {
//ctrl was held down during the click
}
}
UPDATE:
the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:
HTML
<span onclick="handler(event)">Click me</span>
JS
function handler(ev) {
console.log('CTRL pressed during click:', ev.ctrlKey);
}
The same applies for keyboard events
See also
KeyboardEvent.getModifierState()
2021 UPDATE: There are better ways to do this now. Please be sure to check out the other answers
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey.
Look down for example
$("xyz").click(function(e)){
if(e.ctrlKey){
//if ctrl key is pressed
}
else{
// if ctrl key is not pressed
}
}
note: https://www.w3schools.com/jsref/event_key_keycode.asp
Try this code,
$('#1').on('mousedown',function(e) {
if (e.button==0 && e.ctrlKey) {
alert('is Left Click');
} else if (e.button==2 && e.ctrlKey){
alert('is Right Click');
}
});
Sorry I added e.ctrlKey.
Try this:
var control = false;
$(document).on('keyup keydown', function(e) {
control = e.ctrlKey;
});
$('div#1').on('click', function() {
if (control) {
// control-click
} else {
// single-click
}
});
And the right-click triggers a contextmenu event, so:
$('div#1').on('contextmenu', function() {
// right-click handler
})
You cannot detect if a key is down after it's been pressed. You can only monitor key events in js. In your case I'd suggest changing onclick with a key press event and then detecting if it's the control key by event keycode, and then you can add your click event.
From above only , just edited so it works right away
<script>
var control = false;
$(document).on('keyup keydown', function (e) {
control = e.ctrlKey;
});
$(function () {
$('#1x').on('click', function () {
if (control) {
// control-click
alert("Control+Click");
} else {
// single-click
alert("Single Click");
}
});
});
</script>
<p id="1x">Click me</p>
pure javascript:
var ctrlKeyCode = 17;
var cntrlIsPressed = false;
document.addEventListener('keydown', function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
document.addEventListener('keyup', function(){
if(event.which=="17")
cntrlIsPressed = true;
});
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}

Categories

Resources