calling a jquery function and passing it an object on arrow keypress - javascript

Trying to call a function "clickEvent()" and pass it an obj with attributes on arrow-keyUp using jQuery. But Im not reaching the function. Here is the code. Thanks.
Please Note: Im forking existing code, but adding my arrowPress events to it. So everything should remain as is expect for the document ready if (direction != null) area.
$(document).ready(function() {
$('body').keyup(function(event) {
var direction = null;
// handle cursor keys
if (event.keyCode == 37) {
// slide left
direction = 'prev';
} else if (event.keyCode == 39) {
// slide right
direction = 'next';
}
if (direction != null) {
//alert($('.'+ direction).attr('rel'));
//need to pass the alert above as an obj to the function clickEvent() below.
}
});
}); //end $(document).ready
//function on external .js src
(function($) {
function clickEvent(obj) {
alert(obj.attr("rel"));
}
$.fn.slidingPage = function(options) {
$el = $(this);
}
})(jQuery); //end ext js scr

If you need to wrap your code into anonymous function to prevent global variable pollution, then your event and function code should be put in the same scope.
You probably need to trigger click event on .prev and .next.
$(document).ready(function() {
$('body').keyup(function(event) {
var direction = null;
// handle cursor keys
if (event.keyCode == 37) {
// slide left
direction = 'prev';
} else if (event.keyCode == 39) {
// slide right
direction = 'next';
}
if (direction != null) {
$('.'+ direction).click()
}
});
}); //end $(document).ready

The function clickEvent is inside another function's scope, put them into the same scope, or higher scope:
function clickEvent(obj) {
alert(obj.attr("rel"));
}
$.fn.slidingPage = function(options) {
var $el = $(this);
};
(function($) {
$('body').keyup(function(event) {
var direction = null;
// handle cursor keys
if (event.keyCode == 37) {
// slide left
direction = 'prev';
} else if (event.keyCode == 39) {
// slide right
direction = 'next';
}
if (direction != null) {
clickEvent( $('.'+ direction) );
}
});
});
There is no reason for the clickEvent and slidingPage declarations to be inside a document ready handler.

Thanks to Andrey Kuzmin...
if (direction != null) {
$('.'+ direction).click();
}

Related

Javascript several keyboard events

I'm currently building a music player with three buttons (actually simple divs) for Play/Pause (id="play"), Previous (id=rew) and Next (id="fwd").
I want the Play/Pause to be "clicked" when pressing SPACEBAR.
I want the Previous to be "clicked" when pressing LEFT ARROW.
I want the Next to be "clicked" when pressing RIGHT ARROW.
I've successfully managed the SPACEBAR control of Play with this :
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
However, when I add the same for the two other buttons in my script, the SPACEBAR control of Play does not work anymore, as well as the other two.
So, what I have currently in my script and which is obviously not working is this :
<script>
var play = document.getElementById("play");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
};
var rew = document.getElementById("rew");
document.onkeydown = function (e) {
if (e.keyCode == 37) {
rew.click();
}
};
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 39) {
fwd.click();
}
};
</script>
What am I doing wrong ?
Each of your keydown events is overwriting the previous one.
Instead, put all the logic into one keydown event, like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function(e) {
if (e.keyCode == 32) {
play.click();
} else if (e.keyCode == 37) {
rew.click();
} else if (e.keyCode == 39) {
fwd.click();
}
};
When you assign to onkeydown several times only the last one will be assigned because it will override the previous one. You can use addEventListener instead but that isn't the best approach neither. Just make more test inside one event listener like this:
var play = document.getElementById("play");
var rew = document.getElementById("rew");
var fwd = document.getElementById("fwd");
document.onkeydown = function (e) {
if (e.keyCode == 32) {
play.click();
}
else if(e.keyCode == 32) {
rev.click();
}
else if(e.keyCode == 32) {
fwd.click();
}
};

grab both the right and the left clicks of a user simultaneously

So my problem is this,
I was wondering if there was a way to detect if a user right clicks and left clicks simultaneously and commit an action if doing so in jQuery. It seems like the code can only detect one right click or one left click at a time in mouse events.
UPDATE
Thanks for the answers, I decided ultimately that feature would be too funky to have for users when I was trying to implement it. Hopefully these answers will be able to help other people too.
You can create variables to hold the state of each mouse button individually and use that to determine whether both buttons are down:
window.isLeftMouseDown = false;
window.isRightMouseDown = false;
$(document).on('mousedown', function(e) {
if (e.which == 1)
window.isLeftMouseDown = true;
else if (e.which == 3)
window.isRightMouseDown = true;
if (window.isLeftMouseDown && window.isRightMouseDown) {
console.log('both down');
}
});
$(document).on('mouseup', function(e) {
if (e.which == 1)
window.isLeftMouseDown = false;
else if (e.which == 3)
window.isRightMouseDown = false;
});
https://jsfiddle.net/2j151tpt/
Something like this. It uses ES2015.
let left = false;
document.addEventListener('mousedown', e => {
if (e.button === 0) {
left = true;
} else if (e.button === 2 && left) {
fireYourFunctionForTwoButtons();
}
})
document.addEventListener('mouseup', e => {
if (e.button === 0) {
left = false;
}
});
My proposal is based on the elapsed time in milliseconds between the two consecutive clicks:
$(function () {
$('#btn').data('last-left-click', 0).on('mousedown contextmenu', function (e) {
var nowTime = Date.now();
if (e.which == 1) {
$(this).data('last-left-click', nowTime);
}
if (e.which == 3) {
// if less then 300 milliseconds....
if ((nowTime - $(this).data('last-left-click')) < 300) {
console.log('Both left and right clicked in sequence in less then 300 milliseconds!');
}
$(this).data('last-left-click', 0);
}
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="btn">Click Me</button>

Perform an action on both click and keydown (Left & Right) arrow keys

I have a dashboard page that has a left pane which slides on click. I want to make the same thing happen on pressing the Left Arrow and the Right Arrow keys.
Can anybody help me on this? I could do it on click. Below is my solution:
$(document).ready(function() {
$('#opener, .left-panel-head').on('click', function() {
var panel = $('#LeftPanel');
if (panel.hasClass("visible")) {
panel.removeClass('visible').animate({'margin-left': '-300px'});
$('#rightPanel').animate({'width': '100%'});
} else {
panel.addClass('visible').animate({'margin-left': '0px'});
$('#rightPanel').animate({'width': '74%'});
}
return false;
});
});
function updatePanel(direction) {
if(direction === 'left') {
// pressing left
}else if(direction === 'right') {
// pressing right
}
};
$(document).keypress(function( event ) {
if(event.which == 37) {
updatePanel('left');
}else if(event.which == 39) {
updatePanel('right');
}
};
$('#opener, .left-panel-head').on('click', updatePanel('left'));
$('#opener, .right-panel-head').on('click', updatePanel('right'));
You can make your function an actual function instead of an anon function passed into your click event and then call it from multiple places.
(function($, document){
var $document = $(document);
//shared function
function stuff(){
}
//check if key pressed was one of the left or right arrows
function checkKey(e){
var c = e.which ? e.which : e.keyCode;
//left arrow, right arrow
if(c === 37 || c === 39){
//call stuff if left or right arrow was pressed
stuff();
}
}
//call stuff on click
$('#opener, .left-panel-head').on('click', stuff);
$document.on('keydown', checkKey);
})(jQuery, document);

after keyup event I want the change to be permanent

I want to add a class to a list using keyup event but when the keyup event is called it add the class to the list. After some seconds, the class from the list will be removed then i try to use setinterval on the callback function. It work but if i try to navigate through the list it behave funny.
Here is the code
(function(){
var AutocompleteActivities = {
init: function(config)
{
this.config = config;
$("#keywords").on("keyup", this.confirm);
},
confirm: function(e)
{
var self = AutocompleteActivities;
var con = self.config.div;
key = e.keyCode;
press = e.timeStamp
//check whether there is a key up invent in the search textfield and up or down arrow is press
if(press != "" && e.keyCode == 40 || e.keyCode == 38)
{
if(con.css("display") == "block")
{
setInterval(function(){
self.navigation(key)},500)
}
}
},
navigation: function(key)
{
var con = this.config.div, // #options - the container of the autocomplete
li = con.find("ul").find(">li"),
totalLi = li.length,
firstLi = li.first(),
current = 1; // it should be zero for debug reasons it is one
if(key == 40)
{
if(current != 0) // check whether the autoComplete selection is the first in the
{
firstLi.addClass("selection")
++current
con.find("ul li").filter(function() {
return $(this).hasClass("selection");
}).next().addClass("selection").end().removeClass("selection")
return false;
}
}
}
}
AutocompleteActivities.init({
div: $("#options"),
})
})()

Horizontal movement with Javascript

I feel like a complete klutz, I had this working and then I accidentally forgot to save it! I'm an idiot. I've spent the last day trying to recreate what I had but I can't do it. Basically (from my last save) I had this:
function canvasMove(e) {
if(!e) var e = window.event;
var downcheck;
var upcheck;
var leftcheck;
var rightcheck;
if(e.keyCode == '38') {
if(up + down == 0) downcheck = false;
else downcheck = true;
e.preventDefault();
}
if(e.keyCode == '40') {
if(up + down > HEIGHT - 110) upcheck = false;
else upcheck = true;
e.preventDefault();
}
if(e.keyCode == '37') {
if(left + right == 0) rightcheck = false;
else rightcheck = true;
e.preventDefault();
}
if(e.keyCode == "39") {
if(left + right > WIDTH - 110) leftcheck = false;
else leftcheck = true;
e.preventDefault();
}
if(leftcheck == true) { left += 10; counting() };
if(rightcheck == true) { right -= 10; counting() };
if(upcheck == true) { up += 10; counting(true) };
if(downcheck == true) { down -= 10; counting(true) };
}
The problem of course being that Javascrpt doesn't support the ability to check if two keys are being pressed at the same time. What I want to accomplish is when the user pressed up and left they'll move diagonally. Ignore the "counting" function, it's just to keep track of how much the user has moved.
I managed to accomplish this with just else and if statements, no less! So I was wondering if you guys could give it a shot. The first if statement in each key if statement is so the user can't leave the canvas box. Then I have a function that moves the user by redrawing the canvas.
function redraw() {
clear(draw);
draw.fillStyle = 'rgba(0,0,0,0.5)';
draw.fillRect(left + right, up + down, '100', '100');
}
The "clear" function is just a simple function that clears the entire canvas. This is all controlled by an init function that looks like this:
function init() {
canvas = document.getElementById('game');
HEIGHT = canvas.height;
WIDTH = canvas.width;
draw = canvas.getContext('2d');
setInterval(redraw, 30);
document.onkeydown = canvasMove;
}
Your -check flags need to be global variables rather than function-scoped variables, otherwise they will never stay set between keydown events (handling only one key at a time). You also need a keyup event handler that will unset the correct flag when a key is released.

Categories

Resources