Jquery keydown event only working every second press? - javascript

Essentially I've created a thumbnail gallery which you can scroll through using the left and right arrows. The right arrow event works perfectly fine, so I assumed that the left arrow event would be the same except with a (-) value. However when I press the left key it only goes to the previous thumbnail every SECOND time.
Can somebody take a look at my code and let me know what I'm missing? Thanks!
$(document).bind("keydown", function(event) {
if (event.keyCode == 39)
{
$("#thumbnail img").each(function(i) {
if ($(this).hasClass("currentThumb"))
{
currentSelectionIndex = i;
$("#thumbnail img").removeClass("currentThumb").addClass("thumb");
if (currentSelectionIndex == 14 && parseInt($('#end').text()) < parseInt($('#total').text()))
{
nextImages(currentCategory.value);
}
}
if(i == currentSelectionIndex + 1)
{
$(this).removeClass("thumb").addClass("currentThumb");
$(this).parent().click();
}
});
}
if (event.keyCode == 37)
{
$("#thumbnail img").each(function(i) {
if ($(this).hasClass("currentThumb"))
{
currentSelectionIndex = i;
$("#thumbnail img").removeClass("currentThumb");
$("#thumbnail img").addClass("thumb");
if (currentSelectionIndex == 0 && parseInt($('#start').text()) > 1)
{
prevImages(currentCategory.value);
}
}
if(i == currentSelectionIndex - 1)
{
$(this).removeClass("thumb").addClass("currentThumb");
$(this).parent().click();
}
});
}
});

Reversing your selection should be enough to make it go in reverse.
$.fn.reverse = [].reverse; // at the top of your code
// in the event handler for left arrow
$("#thumbnail img").reverse().each(function(i) {
don't forget to change back to +

It may works using keyup instead of keydown. I had some issues with it. If it doesn't work use http://jsfiddle.net so that we can easier solve it.

Related

Jquery keydown only works once

EDIT: I solved it by changing = to ==, but that didnt fully solve it but then I added a change to $currentSlide and now it works! Yay!
$(document).keydown(function(e) {
if(e.keyCode == 39)
{
if($currentSlide == $slide1){
slideShow(slide2);
$currentSlide = $slide2;
}
else if($currentSlide == $slide2){
slideShow(slide3);
$currentSlide = $slide3;
}
else if($currentSlide == $slide3){
slideShow(slide1);
$currentSlide = $slide1;
}
}
})
I have searched for an answer but haven't found anything that suits my question. I am a noob on javascript so bear with me.
I have a function that works as a slideshow. (I use $ in front of my jquery variables, I have a lot of javascript variables too so I just use it to separate them.)
var $currentSlide = "#slide1";
var $slide1 = "#slide1";
var $slide2 = "#slide2";
var $slide3 = "#slide3";
function slideShow($slide) {
if ($slide != $currentSlide){
$($currentSlide).fadeOut(500);
$($slide).delay(500).fadeIn(500);
$currentSlide = $slide;
}
};
To call this function, I use a simple link with parameter depending on which slide is active.
onclick="slideShow(slide2)"
And then I want to change slide with keypress (to right). This is my code for the keypress:
$(document).keydown(function(e) {
if(e.keyCode == 39) {
if ($currentSlide = $slide1){
slideShow(slide2);
} else if($currentSlide = $slide2) {
slideShow(slide3);
} else if($currentSlide = $slide3) {
slideShow(slide1);
}
}
})
It works perfectly when using the links but when I press key it behaves very weird. First click works like a charm, but then it doesnt work any more. If I click to get the third slide, another click will put next slide on top of slide3 but slide3 never goes away.
I realise there is some huge mistake by me here but I'm too much of a beginner to fix it. Any ideas?
your if-else conditions will always be true, because you used '=' instead of '=='. since your first if condition will be true it always shows slide2 and it looks to you that it only worked once
$(document).keydown(function(e) {
if(e.keyCode == 39) {
if ($currentSlide == $slide1){
slideShow(slide2);
} else if($currentSlide == $slide2) {
slideShow(slide3);
} else if($currentSlide == $slide3) {
slideShow(slide1);
}
}
})
The second problem maybe caused by the clock on the slideshow, if you are using one. When you click the next/previous button you need to reset the clock of your slideshow.
There are two issues
You do an assignment in your if conditions, so they always are true. Instead use the comparator ===;
In the onclick attribute you specify an undefined variable, since the $ is missing from it
Beside correcting this, I would suggest to use a class for your slide elements, not individual IDs. So use class="slide" instead of id="slide1" in your HTML, and apply it to all slides -- they can share the same class.
Then store the sequence number of the current slide, counting from 0.
I would also remove all the onclick attributes on the slide elements and deal with click handlers from code, which can be done quite concisely with $('.slide').click( ... ):
var currentSlideNo = 0; // zero-indexed
function slideShow(slideNo) {
if(slideNo != currentSlideNo){
$('.slide').get(currentSlideNo).fadeOut(500);
currentSlideNo = slideNo;
$('.slide').get(currentSlideNo).delay(500).fadeIn(500);
}
};
$('.slide').click(function () {
slideShow((currentSlideNo + 1) % $('.slide').length);
});
$(document).keydown(function(e) {
if (e.keyCode == 39) {
slideShow((currentSlideNo + 1) % $('.slide').length);
}
});

Javascript check if left mouse button is clicked

I have this code to detect mouse down. However on android phones, mouse down for a long time often converts to a right click.
Is there a way I can only get information about left mouse click?
var mouseDown = 0;
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
using this as the code below
if (mouseDown){
xyz happens
}
Still a beginner, please tell me what to change in both the codes.
Thanks
This might help you,
$(document).ready(function() {
$(document).mousedown(function(e) {
if (e.which === 1) {
alert("left");
}else if(e.which === 3){
alert("right");
}
});
});

Using shift key and click to go to the next slide

Hei guys, i added these lines of code as javascript on succes of a click box in captivate :
document.onkeydown = function (e) {
if (e.keyCode == 16) {
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', 5);
}
};
It does good what it does but after first atempt even if im on another slide and i press shift key it goes to slide 5 :( Another question is, how to set an mousedown and onkeyup event on same button. What i try to achieve is to jump to next slide if i press shift key and i click on a click box.
EDIT: new code:
document.onmousedown = function (e) {
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5 && e.keyCode == 16){
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide' , 5);
}
};
As i think it, should fire the function when i click on it, BUUUT , unfortunately it doesnt work... seems like Captivate doesnt recognize onmousedown event :|
RE-EDIT : i figurate out how to make it work. Here's the code :
document.onkeydown = function(e) {
var currentFrame = document.Captivate.cpEIGetValue('m_VarHandle.rdinfoCurrentFrame');
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5 && e.keyCode == 16){
document.Captivate.cpEISetValue('m_VarHandle.rdcmndGotoFrameAndResume' , 491);
}
};
document.onkeyup = function(e) {
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5){
document.Captivate.cpEISetValue('m_VarHandle.rdcmndGotoFrameAndResume' , 485);
}
};
Now everything's just PERFECT! its exactly what i wanted to do... but it works only on localhost... only when i press F12 in Captivate :( if i try to run exported swf or html from captivate it crush :((( Any ideea ?
var slide = 4;
document.onkeydown = function (e) {
if (e.keyCode == 16) {
slide++;
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', slide);
}
};
Bassically you want to increment the position (second argument of cpEISetValue), in your code, you always set it to 5. Also make sure to reset it when it reaches the max slider position.
You can check the SHIFT key inside the click:
var slide = 4;
$('body').click( function (e) {
if (e.shiftKey) {
slide++;
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', slide);
}
});
check here
If you want to set a click with a shift key you can use this:
$(document).click(
function(e){
if(e.shiftKey){
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', 5);
}
}
);
the same works with ctrlKey, and altKey
And to change the page fine you need a control variable like this:
var current_page = 1;
$(document).click(
function(e){
if(e.shiftKey){
current_page++
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', current_page);
}
}
);
I think this is the final code that you need (you maybe need to change document to an id or class that you are using like "#element_id" or ".element_class")

jQuery keyup working incorrectly

I am trying to make an integer variable increment every time the Enter key is pressed. This variable is then used to output a value from an array.
$(document).keyup(function(e) {
if (e.keyCode == 13) {
console.log(++currSteps);
$('#output').text(outNum[currSteps])
if(outNum[currSteps] % 2 == 0){
$('body').css("background", "#4b84e5")
}
else if(outNum[currSteps] == 1){
$('body').css("background", "#9dd622")
}
else{
$('body').css("background", "#d16323")
}
}
});
The problem occurs when I actually press Enter. On the first press, it works properly, and increments the variable currSteps and displays the next value in the array. However, when I press Enter again, it reverts it back to the original value of currStep, as long as Enter is held down, it will display the original value.
Now, yes, this event is for keyup, therefore it makes sense that things will work oddly on keydown. However... if I open up the developer tools and click around in the console, and then return to my original window, the keyup code works perfectly. Why is this only working after the developer tools have been opened?
I have tried this on jQuery 1.11.1 and 1.10.2.
Edit: currSteps and outNum declarations.
$('#in').click(function(){
$('#output').empty();
$('#steps').empty();
var steps = 0
currSteps = 0
var inNum = parseInt($('#input').val());
var col = '#ffffff'
outNum = []
outNum.push(inNum)
...
I allowed to myself to write a little of your missing variables defition: JSFiddle
$(document).ready(function() {
var currSteps = 0;
var outNum = { 0: 0, 1: 1, 2: 2 };
$(document).keyup(function(e) {
if (e.keyCode == 13) {
console.log(++currSteps);
$('#output').val(outNum[currSteps] + ' ' + currSteps)
if(outNum[currSteps] % 2 == 0){
$('body').css("background", "#4b84e5")
}
else if(outNum[currSteps] == 1){
$('body').css("background", "#9dd622")
}
else{
$('body').css("background", "#d16323")
}
}
});
});
Is you problem still actual with upper demo?

Key Navigation with Javascript

Please Help! I have spent a week to complete this game and this is the final huddle i have been stuck with for a couple of days now. I know some techy out there would probably take a glance and flick something in place. But I'm not very sophisticated with javascript and therefore need some help.
$(document).keydown(function(e){
// left arrow
if (e.keyCode == 37 && currentCell > 0) {
currentCell--;
ChangeCurrentCell();
return false;
}
// up arrow
if (e.keyCode == 38 && currentRow > 0) {
currentRow--;
ChangeCurrentCell();
return false;
}
// right arrow
if (e.keyCode == 39 && currentCell < MAX_CELL) {
currentCell++;
ChangeCurrentCell();
return false;
}
//down arrow
if (e.keyCode == 40 && currentRow < MAX_ROW) {
currentRow++;
ChangeCurrentCell();
return false;
}
// enter key
if (e.keyCode == 13) {
}
});
function ChangeCurrentCell()
{
document.getElementById(Boxes[currentRow + currentCell]).focus();
SimulateMouseOver(document.getElementById(Boxes[currentRow + currentCell]));
}
// function will trigger event of selecting current focus.
function selectElement()
{
}
$(document).ready(function(){
loadDivs()
// will give initial focus to top left element paving way for key navigation
ChangeCurrentCell();
// above gives first element in Boxes the focus when loading.
The div element will not focus despite getting it and calling the focus method, i have tried to trigger mousehover on the element with no luck. Please assist me, i put my masters thesis aside despite already being on a tight schedule to do this game which is a requirement for a job position. I have done whole the whole game logic and it all works well, if i send the code in as it is it will definitely be discarded because it doesnt meet the key navigation requirement ... i am desperate i will even pay if i need to -frustrated Student
Look at this
It's my solution for a test, maybe the same...maybe can help you :) If it is, please use it as a hint and don't copy all my code :D
Regards,
L.
You can bind to the document.keydown event to capture key strokes. Then you can use event.which (normalized by jQuery) to determine which key was pressed.
$(document).on("keydown", function (event) {
if (event.which === 37) {
//code for left arrow
} else if (event.which === 38) {
//code for up arrow
} else if (event.which === 39) {
//code for right arrow
} else if (event.which === 40) {
//code for down arrow
}
});
UPDATE
I just noticed you didn't tag your question with jQuery. To use native JS you'll have to change how you bind to the document.keydown event and how you determine the key that was pressed (different browser implementations store the info under different indexes of the event object).
to make it more convenient () not necessary:
`var LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SPACE = 32;`
then bind to keydown, keypress doesn't catch arrow keys
and do something like this:
$(document).bind("keydown", function (e){
var which = e.which;
var navigationKeyWasPressed = which !== undefined && which >= 39 && which <= 40;
//do nothing if no significant key was pressed
if (!navigationKeyWasPressed ) {
return;
}
if ($(".selectedWithKey").length === 1){
switch (which) {
case LEFT:
//...
break;
case UP:
//...
break;
case RIGHT:
//...
break;
case DOWN:
//...
break;
case SPACE:
//turn card
break;
default: //non arrow pressed
//...
}
} else {
// if no card is selected, select one to start arrow navigation
$(".sponsor:first").addClass("selectedWithKey")
}
});

Categories