Reputation: 3050
$(document).keydown(function(e){
if (e.keyCode == 37) {
return false;
}
});
$(".direction").click(function() {
var direction = $(this).text();
When I click on a button with .direction class the second function above is called. When the left key is pressed I want to call the $(".direction").click(function() {
But with a value (Instead of the var direction = $(this).text(); part) It would be var direction = value passed to function;
How can I do that?
Upvotes: 3
Views: 11915
Reputation: 34168
Create a function to handle the event and then call it:
function handleMyEvent(direction){
/* do your handling here */
}
$(document).keydown(function(e){
if (e.keyCode == 37) {
var direction = e.keyCode; // or create an appropriate string for your use
// OR IF you want the value of the focused element, you can get that also:
// IF this is not what you want/mean clarify please
var direction = $(e.target).text();
handleMyEvent(direction);
return false; //still return false to prevent the default behavior
}
});
$(".direction").click(function() {
var direction = $(this).text();
handleMyEvent(direction);
});
Upvotes: 1
Reputation: 14219
var changeDirection = function(data) {
var direction = data;
alert(direction);
};
$(document).keydown(function(e) {
if (e.keyCode == 37) {
changeDirection("your value here");
}
});
$(".direction").click(function() {
changeDirection($(this).text());
});
See a live example here
Upvotes: 1
Reputation: 5249
I would use another function to do this instead of trying to trigger the click handler.
$(document).keydown(function(e){
if (e.keyCode == 37) {
updateDirection("Something else");
}
});
$(".direction").click(function() {
updateDirection($(this).text());
});
function updateDirection(d) {
var direction = d
}
Upvotes: 2
Reputation: 850
Add another function that is used by both methods:
$(document).keydown(function(e){
if (e.keyCode == 37) {
move("left");
}
});
$(".direction").click(function() {
move($(this).text());
});
function move(newDirection)
{
var direction = newDirection;
}
Upvotes: 4