go to next image element when right arrow is pressed - javascript

So if i had an element like this on HTML
index.html
<div><img id="2" src="1.jpg"><img id="2" src="2.jpg"></div>
that created by js like this
index.js
let image = document.createElement("img")
image.src = img.image
image.style.width = "725"
image.style.height = "1024"
image.setAttribute("id",img.index)
how can I make if the right arrow pressed it go to the top of the next image index
I've try this
image.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
document.location.href = `#${img.index--}`
} else if (e.keyCode == '39') {
document.location.href = `#${img.index++}`
}
}
but didn't work

You should not change the document.location, the script will have to rerun because the page is reloaded. Instead just scrollIntoview:
Also no need for index, you can calculate the index from the content
const imageArr = [
"https://via.placeholder.com/725x1024/000000/FFFFFF/?text=image1",
"https://via.placeholder.com/725x1024/FF0000/0000FF/?text=image2",
"https://via.placeholder.com/725x1024/FFAAFF/00AA00/?text=image3"
]
const container = document.getElementById("imageContainer");
container.innerHTML = imageArr.map(img => `<img src="${img}" />`)
const images = container.querySelectorAll("img");
let current = 0;
const max = imageArr.length
window.addEventListener("keydown", function(event) {
if (event.defaultPrevented) {
return; // Do nothing if event already handled
}
const key = event.code;
if (key === "ArrowLeft") current--;
else if (key === "ArrowRight") current++
// wrap
if (current < 0) current = max; // change to current=0 if no wrap
else if (current >= max) current = 0; // change to current = max if no wrap
images[current].scrollIntoView()
})
<div id="imageContainer"></div>

Related

Script does not jump to the next field when the maxlength is reached

This is my script
<script>
var InputContainer = document.getElementsByClassName("InputContainer")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}
</script>
I have also put a around the entire form.
You can find the original webpage at: https://im-here.biz/ContactForm/contact-inc.php
Obviously, I am doing something wrong here.
Ideas?
I can see an error in the console on the above-mentioned URL. By seeing your code there is no container defined. I guess you should be using InputContainer instead of the container variable or change the declaration like this:
<script defer>
// Put your code here
var container = document.getElementsByClassName("InputContainer")[0];
</script>

Manipulating integers using a keyboard

Sorry for the vague post. I'm stuck on an online coding challenge, where the objective is that it must be possible to increase and or decrease a number using a keyboard, using the up and down keys. (all HTML-content must be created using JS)
It wants me to use addEventListener without an element object - use the event type keydown. Regardless if the buttons or the up and down keys are used, the decrease button must be 'disabled' if the values in the div-element is '1', and there can't be a number less than '1' in the div element.
Here is my code so far - I'm not sure how to incorporate the functions described above:
addEventListener('load', function() {
let button = document.createElement('input')
let secondButton = document.createElement('input')
button.setAttribute('type', 'button')
button.setAttribute('id', 'increase')
secondButton.setAttribute('type', 'button')
secondButton.setAttribute('id', 'decrease')
document.body.appendChild(button)
document.body.appendChild(secondButton)
let div = document.createElement('div')
div.setAttribute('id', 'bet-size')
div.textContent = '1'
document.body.appendChild(div)
if (Number(div.textContent) === 1) {
secondButton.setAttribute('disabled', '')
}
const increase = function() {
div.textContent = Number(div.textContent) + 1
if (Number(div.textContent) > 1) {
secondButton.disabled = false
}
}
const decrease = function() {
if (Number(div.textContent) === 2) {
secondButton.disabled = true
}
if (Number(div.textContent) > 1) {
div.textContent = Number(div.textContent) - 1
}
}
button.addEventListener('click', increase)
secondButton.addEventListener('click', decrease)
})
You want to use keyDown event's keyCode property to determine the pressed key and call increase() or decrease() accordingly. keyCode stores a number indicating the key that caused the event evocation. There are a number of sites on the internet to determine your desired key code, like this for example.
You also might want to use keyUp to determine key releases again because you might get these events multiple times and only want to react to one of them.
let isKeyDown = false;
const handleKeyDown = function(event) {
if(isKeyDown == false)
{
isKeyDown = true;
if(event.keyCode == 38) // Arrow Up
{
event.preventDefault(); // Prevent page scrolling
increase();
}
else if(event.keyCode == 40) // Arrow Down
{
event.preventDefault(); // Prevent page scrolling
decrease();
}
}
}
const handleKeyUp = function(event) {
if(isKeyDown == true)
{
isKeyDown = false;
}
}
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
Your expanded example might look like this, then:
addEventListener('load', function() {
let button = document.createElement('input')
let secondButton = document.createElement('input')
button.setAttribute('type', 'button')
button.setAttribute('id', 'increase')
secondButton.setAttribute('type', 'button')
secondButton.setAttribute('id', 'decrease')
document.body.appendChild(button)
document.body.appendChild(secondButton)
let div = document.createElement('div')
div.setAttribute('id', 'bet-size')
div.textContent = '1'
document.body.appendChild(div)
if (Number(div.textContent) === 1 ) {
secondButton.setAttribute('disabled', '')
}
const increase = function() {
div.textContent = Number(div.textContent) + 1
if (Number(div.textContent) > 1) {
secondButton.disabled = false
}
}
const decrease = function() {
if (Number(div.textContent) === 2) {
secondButton.disabled = true
}
if (Number(div.textContent) > 1) {
div.textContent = Number(div.textContent) - 1
}
}
// Required to remember if a key is already pressed or not
let isKeyDown = false;
//Event handlers for KeyUp And KeyDown
const handleKeyDown = function(event) {
if(isKeyDown == false)
{
isKeyDown = true;
if(event.keyCode == 38) // Up
{
event.preventDefault(); // Prevent page scrolling
increase();
}
else if(event.keyCode == 40) // Down
{
event.preventDefault(); // Prevent page scrolling
decrease();
}
}
}
const handleKeyUp = function(event) {
if(isKeyDown == true)
{
isKeyDown = false;
}
}
button.addEventListener('click', increase)
secondButton.addEventListener('click', decrease)
//Add the new event handlers to the document's keydown and keyup events
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
})

How to change background color after using 'onkeydown'?

I was trying many solutions but none worked.
The problem is where I put the comment.
I trying to do a game which I can change a color of boxes using arrows.
var p = 0;
var d0 = document.getElementById('p1').getAttribute('value');
var d1 = document.getElementById('p2').getAttribute('value');
var arraj = [];
arraj.push(d0, d1);
function change() {
for (var i = 0; i < arraj.length; i++) {
if (arraj[i] == p) {
// and here is the problem
arraj[i].style.backgroundColor = "red";
}
}
}
document.onkeydown = check;
function check(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left
} else if (e.keyCode == '39') {
p++;
change();
// right
}
}
and HTML
<div class='g' id='p1' value="0">bla</div>
<div class='g' id='p2' value="1">bla</div>
This should fix it:
var p = 0;
var d0 = document.getElementById('p1'); // Remove 'getAttribute('value')' here
var d1 = document.getElementById('p2'); // Remove 'getAttribute('value')' here
var arraj = [];
arraj.push(d0, d1);
function change() {
for (var i = 0; i < arraj.length; i++) {
if (arraj[i].getAttribute('value') == p) { // Check for the attribute equality here
arraj[i].style.backgroundColor = "red";
}
}
}
document.onkeydown = check;
function check(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left
} else if (e.keyCode == '39') {
p++;
change();
// right
}
}
Basically the main issue that you're trying to set background color on element's value attribute and not the element itself.

Image change on pressing keyup and keydown

I am new to JavaScript and this community. I apologize if this has been asked before, but the threads I found for this topic did not really help me with this specific problem.
I would like to achieve the following working:
Image 1 is displayed.
If you press the left arrow key (keydown) the image should change to image 2.
If you stop pressing (keyup), it should change to image 3.
If you press the right arrow key it should change to image 4 and on keyup, change to image 5.
The code is:
<img src="img/image1.png" id="myIMG">
and
var imgs = ["img/image5.png", "img/image3.png", "img/image1.png", "img/image4.png"];
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
}
var keys = {};
$(document).keydown(function (event) {
keys[event.which] = true;
}).keyup(function (event) {
if(e.keyCode == 37){
delete keys[37];
changeIMG(+1);
}
else if(e.keyCode == 39){
delete keys[39];
changeIMG(+2);
}
});
function IMGLoop() {
if (keys[37]) {
changeIMG(+3);
} else if (keys[39]) {
changeIMG(+4);
}
setTimeout(IMGLoop, 20);
}
IMGLoop();
The issue is described below.
The keyup does not do anything and the keydown only works once and then I can not even switch between left and right anymore.
I need to do this with a loop because I also want to do other things on the loop that are not displayed in this code. I would appreciate any type of help.
Hope this helps you
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e) {
if (e.keyCode == 37) {
showImageName--;
if (showImageName == -1) {
showImageName = imgs.length - 1;
}
changeIMG(showImageName);
} else if (e.keyCode == 39) {
showImageName++;
if (showImageName == imgs.length) {
showImageName = 0;
}
changeIMG(showImageName);
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e);
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e);
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">
Update after question edited
var imgs = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQgz2HMpGysZL6ifYfhqWASDoA0b2MyX-gyMuQszgYRv87yr9qug",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQV3JL_HtVvlLr3Xy-KQV5MNmIF2-kCb9cHB4oXkUKQ1jiLT0H",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgDmo-5YpwYK9Yc35CK1oq3Y2zHDnXlu3q6m7GnSvLarDTRl0B",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQt2dZklq8eDbsNL1vZ0MTwZsm0KWDIxl6YifmbUqjPiE5lOmIe",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnDWTv5oLaNgUm_SXQFSzzBJl-21c7wLCC6Hgld-ndQ1k0knly"
];
var showImageName = 2;
function changeIMG(dir) {
var img = document.getElementById("myIMG");
img.src = imgs[dir];
img.alt = dir;
}
var keyPressed = false;
function f(e, str) {
switch (str) {
case "up":
if (e.keyCode == 37) {
changeIMG(2);
} else if (e.keyCode == 39) {
changeIMG(4);
}
break;
case "down":
if (e.keyCode == 37) {
changeIMG(1);
} else if (e.keyCode == 39) {
changeIMG(3);
}
break;
}
}
$(document)
.keydown(function(e) {
if (!keyPressed) {
keyPressed = true;
f(e, "down");
}
})
.keyup(function(e) {
if (keyPressed) {
keyPressed = false;
f(e, "up");
}
});
changeIMG(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img alt='' src="" id="myIMG">

Onkeypress slideshow with description change

I'm here for help. I'm creating some onkeypress wannabe slideshow using javascript. Code I used is down there. I'd like to add some description to the photos I used and I want it to change to correspond with the current picture, so when I have "picture 1", text "description 1" is shown, then "picture 2" and "description 2" appears etc... Any suggestions, please?
Thanks for help!
PS.: If youre willing to help me, please keep in mind, that I have no idea what I'm doing...
let images = ["https://static.boredpanda.com/blog/wp-content/uploads/2017/03/189578_205761_4_-Yuan-Peng-China-Shortlist-Professional-Sport-2017-Sony-World-Photography-Awards-58c68fa8b4532__880.jpg",
"https://static.boredpanda.com/blog/wp-content/uploads/2017/03/212367_227257_1_-Adi-Bulboac-Romania-Shortlist-Professional-Architecture-2017-Sony-World-Photography-Awards-58c68fe283e62__880.jpg",
"https://static.boredpanda.com/blog/wp-content/uploads/2017/03/217609_232497_0_-Wilson-Lee-China-Shortlist-Open-Competition-Still-Life-2017-Sony-World-Photography-Awards-58c68fed34611__880.jpg"];
function changeImage(dir) {
let img = document.getElementById("imgClickAndChange");
img.src = images[images.indexOf(img.src) + (dir || 1)] || images[dir ? images.length - 1 : 0];
}
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
changeImage(-1) //left <- show Prev image
} else if (e.keyCode == '39') {
// right -> show next image
changeImage()
}
}
You can download this jQuery-sliderResponsive and call the function on your key up and key down. The code work for only this slider.
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
prevSlide(); // Previous
} else if (e.keyCode == '39') {
nextSlide(); // Next
}
}
You should use an existing plugin.
However, if you would like to go on this path you could have another array with the descriptions, matching the positions.
Something like this should work:
let descriptions = ["It hurts!", "This is a room with small chairs (no kidding!!)", "Painting?"];
let currentIndex = 0;
function changeImage(dir) {
// Get the index
let img = document.getElementById("imgClickAndChange");
let newIndex = currentIndex + dir;
currentIndex = images[newIndex] != undefined ? newIndex : (dir > 0 ? 0 : images.length-1);
// Change the picture
img.src = images[currentIndex];
// Change the description
document.getElementById("description").innerHTML = descriptions[currentIndex];
}
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
changeImage(-1) //left <- show Prev image
} else if (e.keyCode == '39') {
// right -> show next image
changeImage(1)
}
}
Here is the example code:
https://jsfiddle.net/fwgk7stt/

Categories