Reputation: 1020
I want to control events when hovering a <div>
element.
I have my code pretty much working, but I have 2 remaining problems!
console.log('click and press');
This is getting fired each time I press shift
and is not looking for a click
- why is this getting fired when pressing shift when I call it within a function that says $(document).on('keydown click', function (e) {
My JS code is as follows
$(document).ready(function () {
$(".target").hover(function () {
$(document).on('keydown click', function (e) {
if (e.shiftKey) {
// code to go here for click
console.log('click and press');
}
});
$(document).on('keydown', function (e) {
if (e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
$('.target').css('cursor', 'sw-resize', 'important');
});
});
});
Thanks
Upvotes: 1
Views: 1116
Reputation: 20270
The reason why you need to click first on the fiddle demo is because the frame doesn't have focus, normally this should work fine.
You shouldn't be attaching a keydown
listener, you only need a to attach click
, otherwise keydown
will fire the event regardless of a click
occurring.
Also, currently you're attaching 3 handlers every time you hover over .target
, see @techfoobar's answer for a cleaner solution.
Upvotes: 2
Reputation: 66693
Your event binding is incorrect. you can use:
Demo: http://jsfiddle.net/g9ea8/8/
Code:
$(document).ready(function () {
var hovering = false;
$(".target").hover(function () {
hovering = true;
}, function() {
hovering = false;
});
$(document).on('click', function (e) {
if (hovering && e.shiftKey) {
// code to go here for click
console.log('hovering+shift+click');
}
});
$(document).on('keydown', function (e) {
if (hovering && e.shiftKey) {
// change cursor to ne-resize
$('.target').css('cursor', 'ne-resize', 'important');
console.log('hovering+shift');
}
});
$(document).on('keyup', function (e) {
// change cursor to sw-resize
if(hovering) {
$('.target').css('cursor', 'sw-resize', 'important');
console.log('hovering+keyup');
}
});
});
Upvotes: 3