Event handling function - javascript

In the task, you need to change the background colour of the block to green when you press the G key, but no changes are made.
<body>
<div id="colorOutput">
</div>
<script>
let div = document.querySelector("#colorOutput");
document.addEventListener("keydown", function (event) {
if (event.code == "Enter") changeToGreen();
})
function changeToGreen() {
div.style.backgroundСolor = "green";
}
</script>

Try using the below JS code.
const div = document.getElementById("colorOutput");
window.addEventListener("keydown", (e)=>{
e.code === "Enter" ? changeToGreen() : null;
});
function changeToGreen() {
alert("JAI HARI");
div.style.backgroundСolor = "green";
}
Use window instead of document for Event Listener.

Related

Simulate keyboard with Jquery on button

I'm trying to experiment some things with js-dos (a plugin of dosbox on browser) and I need a button to simulate a keyboard key (ENTER for example)
I've tried creating an onclick event and inside the function,a Jquery "keypress" event,but nothing seems to work.
I've tried this:
$("button").on("click",function(){
var val=13;
$("canvas").trigger({
type:keypress, keyCode:val,which:val,charCode:val
});
})
and this
var e = jQuery.Event('keydown');
e.which = 13;
e.keyCode = 13;
$("canvas").trigger(e);
What am I doing wrong here?
Add listener to the triggered event.
let e = jQuery.Event('keydown');
$('div').on('keydown', function() {
console.log('calling');
});
$('button').on('click', function() {
$('div').trigger(e);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Lorem Ipsum</div>
<button>Click Me</button>
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});

Bluetooth headphones button event detection in javascript

I am building a web app where I detect the headphones button event. I succeeded in capturing headphones button event when they are plugged in. Now I am trying to capture Bluetooth headphones next button event. Any help on this please?
Code for headphone button detection.
document.addEventListener('volumeupbutton', () => {
//Do something here
}, false);
I need something similar to this.
You can use keydown and keyup events for implementing the long press functionality.
// Imprementation of Long Press
const longPressTime = 1500;
let keyDownTimeout;
document.addEventListener('keydown', e => {
if (keyDownTimeout) {
return;
}
keyDownTimeout = setTimeout(() => {
// button was held for 1500ms, consider it a long-press
if (e.code === 'ArrowUp') {
console.log("Action Performed");
// do long-press action
} else {
console.log("Other action performed");
}
}, longPressTime);
});
document.addEventListener('keyup', e => {
clearTimeout(keyDownTimeout);
keyDownTimeout = 0;
});
Press any key
The above methods work for single key long press. Refer to KeyCode for key code.
Demo of above
I don't believe using the built-in volumeupbutton event will allow you to detect how long the click was, to determine if it should be treated as volume-up or skip-track. Instead you should be able to use the keyup/keydown events, combined with the keyCode property to determine if it is the volume button, like this:
const longPressTime = 1500;
let volumeUpButtonTimeout;
const volumeButtonKeyCode = 0; // you'll need to determine the key code
// cross platform way to get the key code
const getKeyCode = e => {
if (e.key !== undefined) {
return e.key;
} else if (e.keyIdentifier !== undefined) {
return e.keyIdentifier;
} else if (e.keyCode !== undefined) {
return e.keyCode;
}
}
document.addEventListener('keydown', e => {
if (getKeyCode(e) == volumeButtonKeyCode) {
volumeUpButtonTimeout = setTimeout(() => {
// button was held for 1500ms, consider it a long-press
// do long-press action
}, longPressTime)
}
});
document.addEventListener('keyup', e => {
if (getKeyCode(e) == volumeButtonKeyCode) {
clearTimeout(volumeUpButtonTimeout);
}
});
You could use this code to determine what keyCode corresponds to the volume up button:
document.addEventListener('keyup', e => {
console.log(e.keyCode);
});

Javascript Onkeydown loop till variable = false

Lets say var myVariable = true by default. Now how do i make it that on key press right arrow, this code is executed:
document.write("Right");
And will keep being executed till myVariable = false again...
You can use Jquery to do it easily:
<script>$( "body" ).keydown(function( event ) {
if ( event.which == 39) {
event.preventDefault();
document.write("Right");
}
});</script>
Bind the event keydown to your body element.
var myVariable = true
document.body.addEventListener('keydown', function(e) {
if (myVariable && e.keyCode === 39) {
document.write("Right");
myVariable = false;
console.log('First time!');
}
});
<h1>Click here and then right arrow</h1>
I think what you are looking for is something like this:
let arrowRight = null;
function keyChange(type, event) {
if (type === 'down' && event.keyCode === 39) {
if (!arrowRight) {
arrowRight = setInterval(function() {
document.body.append('right');
}, 500);
}
}
else if (type === 'up') {
if (arrowRight) {
clearInterval(arrowRight);
arrowRight = null;
}
}
}
document.addEventListener('keyup', keyChange.bind(null, 'up'));
document.addEventListener('keydown', keyChange.bind(null, 'down'));
But since I'm adding listeners to document and document.write actually clear the document if the one you're writing on is already closed (loaded) you will have to use another method to write on your document (like document.body.append).
You can read more about document.write here.

Javascript event keypress on hover

Hi I have multiple divs on the page. I want to raise an alert based on a user hovering over one of the divs and pressing control z. I need to in effect alert out what is in the span dependant upon which div the user is hovered over on.
I have tried with getbyId the problem arises with multiple elements. I am unsure if i need to bind every element.
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
var pressed = false;
onload = function(e) {
var myElement = document.getElementsByTagName('div');
function keyaction(e, element) {
// var originator = e.target || e.srcElement;
if (e.charCode === 122 && e.ctrlKey) {
//myElement.innerHTML += String.fromCharCode(e.charCode);
alert(true);
}
}
for (var i = 0; i < myElement.length; i++) {
myElement[i].addEventListener("mouseover", function (e)
{
document.addEventListener("keypress", function(t){keyaction(t,e);}, false);
});
myElement[i].addEventListener("mouseout", function ()
{
document.removeEventListener("keypress", keyaction, false);
});
}
}
I think you are overdoing for what is needed. A simple keydown event bind on mouseover and unbind on mouseout would do the trick.
Here's an example :
<div id="wrapper">
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
</div>
<br>
Keys Pressed :
<br>
<div id="key"></div>
$("#wrapper .mydiv").on("mouseover",function()
{
$(document).bind("keydown",function(e) {
var originator = e.keyCode || e.which;
if(e.ctrlKey)
$("#key").append(originator + ",");
});
}).on("mouseout",function()
{
$(document).unbind("keydown");
});
http://jsfiddle.net/s095evxh/2/
P.S : for some reason , Jsfiddle doesn't allow keydown event on mouseover so you might have to click manually on the div to make it work but the solution works flawless on a local system.
I would suggest that you use the normalized e.which if available. You also have code 122 which is F11 keys code not 90 related to the 'z' key.
Turn the event manager on when over and off when not per your stated desire:
$('.mydiv').on('mouseenter', function () {
$(window).on('keydown', function (e) {
var code = e.which ||e.keyCode;
$('#status').append('we:'+ code);
if (code === 90 && e.ctrlKey) {
$('#status').append('howdy');
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
});
Note that I changed to post some text to a fictitious "status" div rather than your alert as that will change where the cursor hovers. Change that to some real action. There MAY be issues with the event bubbling but I will leave that determination to you.
Here is a key code list (google for more/another) https://gist.github.com/lbj96347/2567917
EDIT: simple update to push the span text into the status div:
<div class="mydiv">Keypress here!<span>test</span>
</div>
<div class="mydiv">Keypress here!<span>test1</span>
</div>
<div id="status">empty
<div>
$('.mydiv').on('mouseenter', function () {
var me = this;
$(window).on('keydown', function (e) {
var code = e.which || e.keyCode;
$('#status').append('we:' + code);
if (code === 90 && e.ctrlKey) {
$('#status').append($(me).find('span').text());
}
});
});
$('.mydiv').on('mouseleave', function () {
$(window).off('keydown');
$('#status').text('out');
});
Listen for the keypress on the window and add mouse events to the elements to toggle a variable with what element is active.
var activeElem = null;
$(".mydiv")
.on("mouseenter", function () {
activeElem = $(this);
}).on("mouseleave", function () {
if(activeElem && activeElem.is(this)) {
activeElem = null;
}
});
$(window).on("keydown", function (evt) {
if( activeElem && evt.keyCode===90 && evt.ctrlKey) {
console.log(activeElem.find("span").text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Keypress here!<span>test</span></div>
<div class="mydiv">Keypress here!<span>test1</span></div>
To prevent frequent binding/unbinding of the "keydown" handler whenever the user hovers over the <div>, I would simply keep track of the <div> currently being hovered. Something like this:
var hovering = null;
$(document)
.on('keydown', function(e) {
if (e.which === 90 && e.ctrlKey && hovering) {
console.log($('span', hovering).text());
}
})
.on('mouseover', '.mydiv', function(e) {
hovering = this;
})
.on('mouseout', '.mydiv', function() {
hovering = null;
});
.mydiv:hover {
cursor: pointer;
color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">Test <span>1</span></div>
<div class="mydiv">Test <span>2</span></div>
<div class="mydiv">Test <span>3</span></div>
<div class="mydiv">Test <span>4</span></div>
<div class="mydiv">Test <span>5</span></div>
I would propose the other way around. Listen for the keypress, and select the element which has the hover.
$(document).keypress(function(e) {
if (e.charCode === 26 && e.ctrlKey) {
console.log("Key pressed");
console.log($('.mydiv:hover span').html());
}
});
Codepen Demo
If I am understanding your question correctly, you are looking for the text value of the span within the hovered element. Traversing the DOM from $(this) will get you what you want.
$(".mydiv").mouseover(function (e) {
alert($(this).find('span').text());
});

Calling same function on both mouse click and key press using html and javascript

I want to call the same function in javascript either on mouse click or keypress(enter).This is my code in html but it is not working..how can i do it.?
<div class="C" onclick="Cfunc()" onKeyDown="if(keycode==13)Cfunc();">
<p >C</p>
</div>
and this is my js code:
function Cfunc() {
var audio = document.getElementById("Caudio")
audio.play();
}
I would do it outside of the markup like so:
// elements
var audio = document.getElementById("Caudio")
var play_btn = document.querySelector('.C')
// event handlers
play_btn.addEventListener('click', function() {
audio.play()
})
document.addEventListener('keydown', function (event) {
if ( event.keyCode == 13 ) {
audio.play()
}
})
If you don't want the keydown event bound to the entire document, make the div focusable and change it accordingly
you can do this to make this work for both
<div class="C" onclick="Cfunc()" onKeyDown="Cfunc();">
<p >C</p>
</div>
and this is my js code:
function Cfunc(e) {
if(e.keycode && e.keycode!=13)
return;
var audio = document.getElementById("Caudio")
audio.play();
}

Categories

Resources