I want to add my javascript a key press function because my script run automaticaly
I want it when i press a specific key it will run and stop
The JS will not run / run automaticaly until i press "a"
When I press "a" it will run;
When I press "e" it will stop.
Can you add it to my javascript, Thanks.
here is the code bellow:
var currentpos = 0,
alt = 1,
curpos1 = 0,
curpos2 = -1
function initialize() {
startit()
}
function scrollwindow() {
if (document.all)
temp = document.body.scrollTop
else
temp = window.pageYOffset
if (alt == 0)
alt = 1
else
alt = 0
if (alt == 0)
curpos1 = temp
else
curpos2 = temp
if (curpos1 != curpos2) {
if (document.all)
currentpos = document.body.scrollTop + 1
else
currentpos = window.pageYOffset + 1
window.scroll(0, currentpos)
} else {
currentpos = 0
window.scroll(0, currentpos)
}
}
function startit() {
setInterval("scrollwindow()", 10) // change the value for speed the bigger the slow
}
window.onload = initialize
<header id="top"></header>
<main>
<article>
<!-- long form content here -->
</article>
<br>
<h1 id="chapter-heading">My Plug-in Spirit Ring</h1>
</br>
<div class=mp3>
<audio controls autoplay loop>
<source src="bg.mp3" type="audio/mpeg">
</audio>
</div>
<div style="font-size:0; position: absolute; left: 20%; top: 10%">
<img src="Cover.png" />
<img src="1.png" />
<img src="2.png" />
<img src="3.png" />
<img src="4.png" />
<img src="Thanks.gif" />
</div>
</main>
Thank you!
I would do this by creating a boolean value called "shouldScroll" and then using event listeners on your desired buttons to set the value of that variable. Then in your interval check to see if the boolean is true before calling your page scrolling function.
var currentpos = 0,
alt = 1,
curpos1 = 0,
curpos2 = -1
var shouldScroll = false;
document.addEventListener('keydown', (event) => {
if(event.key === 'a'){
event.preventDefault();
shouldScroll = true;
}
if(event.key === 'e'){
event.preventDefault();
shouldScroll = false;
}
});
function initialize() {
startit()
}
function scrollwindow() {
if (document.all)
temp = document.body.scrollTop
else
temp = window.pageYOffset
if (alt == 0)
alt = 1
else
alt = 0
if (alt == 0)
curpos1 = temp
else
curpos2 = temp
if (curpos1 != curpos2) {
if (document.all)
currentpos = document.body.scrollTop + 1
else
currentpos = window.pageYOffset + 1
window.scroll(0, currentpos)
} else {
currentpos = 0
window.scroll(0, currentpos)
}
}
function startit() {
setInterval(()=> shouldScroll && scrollwindow(), 10) // change the value for speed the bigger the slow
}
window.onload = initialize
main {
height: 4000px;
}
<header id="top"></header>
<main>
<article>
<!-- long form content here -->
</article>
<br>
<h1 id="chapter-heading">My Plug-in Spirit Ring</h1>
</br>
<div class=mp3>
<audio controls autoplay loop>
<source src="bg.mp3" type="audio/mpeg">
</audio>
</div>
<div style="font-size:0; position: absolute; left: 20%; top: 10%">
<img src="Cover.png" />
<img src="1.png" />
<img src="2.png" />
<img src="3.png" />
<img src="4.png" />
<img src="Thanks.gif" />
</div>
</main>
add in javascript file
document.addEventListener('keydown', function (e) {
console.log('key', e); // look at
if (e.code === 'KeyA') { // it is possible so
// todo
console.log('press a')
}
if (e.key === 'e') { // it is possible and so
// todo
}
console.log('press e')
})
you can do this using jquery.
$(document).bind('keyup', function(e){
if(e.which==65) {
// "a"
}
if(e.which==69) {
// "e"
}
});
for any word keyword code visit this article
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Related
I want to enable audio in a selected area of the page. If the user scrolls out this element, audio will stop.
I found this solution but the problem is that pixels values are different in order the resolution of the window, monitor, kind of browser etc.
var playing = false;
var audioElm = $('#soundTour').get(0);
$(window).scroll(function() {
var pageScroll = $(window).scrollTop();
if(!playing && pageScroll > 500 && pageScroll < 3000){
audioElm.play();
playing = true;
}else if(pageScroll > 3000 || pageScroll < 500){
audioElm.pause();
playing = false;
}
});
For that I'd like to find a solution in a DIV.
My one page is like this:
https://alvarotrigo.com/fullPage/examples/navigationV.html#firstPage
and I want that the background sound, for example, will autoplay during the first and second page, and will stop when the user join the third page.
Any help?
In code below sound starts playing when 30% of the third block is visible.
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<audio src="/sound.wav"></audio>
<div style="height: 100%; background: #ff5555">first page</div>
<div style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const el = document.querySelector("audio");
let playing = false;
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rect = document.getElementById("d3").getBoundingClientRect();
const top = rect.top;
if (!playing && top > rect.height / 3) {
el.play();
playing = true;
} else if (top < rect.height / 3) {
el.pause();
playing = false;
}
});
</script>
</body>
</html>
Update after comments:
<html>
<head>
<meta charset="utf-8" />
<style>
body { margin: 0; padding: 0; }
</style>
</head>
<body>
<div id="d1" style="height: 100%; background: #ff5555">first page</div>
<div id="d2" style="height: 100%; background: #55ff55">second page</div>
<div id="d3" style="height: 100%; background: #5555ff">third page</div>
<script>
const soundfiles = ["sound.wav", "sound2.wav", "sound.wav"];
const divIds = ["d1", "d2", "d3"];
const els = soundfiles.map((filename, index) => {
const el = document.createElement("audio");
el.src = "/" + filename;
document.body.appendChild(el);
return el;
})
const playing = new Array(divIds.length).fill(false);
window.addEventListener('scroll', (e) => {
const scroll = e.target.body.scrollTop;
const rects = divIds.map(id => document.getElementById(id).getBoundingClientRect());
const tops = rects.map(rect => rect.top);
tops.forEach((top, ind) => {
if (!playing[ind] && top <= rects[ind].height * 2 / 3 && top > - rects[ind].height * 1 / 3) {
els[ind].play();
playing[ind] = true;
} else if (playing[ind] && (top > rects[ind].height * 2 / 3 || top < -rects[ind].height * 1 / 3)) {
els[ind].pause();
playing[ind] = false;
}
});
});
</script>
</body>
</html>
I got images with same width and height and onclick they should get bigger, so I made an function with an eventlistener for it but now it tells me that style isn't defined and I don't see the issue. I set the styles inside the img tag and also without style.
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
js file
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', () => {
if (flag == true && window.innerWidth >= 769) {
paint[i].style.maxWidth = '95vw';
paint[i].style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
paint[i].style.maxWidth = '20%';
paint[i].style.minWidth = '300px';
paint[i].style.height = 'auto';
flag = true;
}
})
}
If I try to use getelementById everything works fine but I don't want for every image an eventlistener.
Use event.target in the eventlistener function to find the clicked image.
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', (event) => {
console.log(event.target)
if (flag == true && window.innerWidth >= 769) {
event.target.style.maxWidth = '95vw';
event.target.style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
event.target.style.maxWidth = '20%';
event.target.style.minWidth = '300px';
event.target.style.height = 'auto';
flag = true;
}
})
}
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
I am working on a slideshow for the homepage of my website. It works, automatically shifting throughout 1-3, but the onclick functions are having some troubles. Every single one of the buttons bring me to my first slide, not the second or the third, just the first. Any help is appreciated, please and thanks!
document.getElementById("left").style.opacity =1;
var currentSlide = 2;
var myVar = setInterval(changeSlide, 5000);
function changeSlide() {
if (currentSlide == 1) {
currentSlide++;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide1.png';
document.getElementById("left").style.opacity =1;
document.getElementById("right").style.opacity =.5;
} else if (currentSlide == 2) {
currentSlide++;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide2.png';
document.getElementById("middle").style.opacity =1;
document.getElementById("left").style.opacity =.5;
} else {
--currentSlide;
--currentSlide;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide3.png';
document.getElementById("right").style.opacity =1;
document.getElementById("middle").style.opacity =.5;
}
}
function firstSlide() {
currentSlide = 1;
myVar = setInterval(changeSlide, 5000);
}
function secondSlide() {
currentSlide = 2;
myVar = setInterval(changeSlide, 5000);
}
function thirdSlide() {
currentSlide = 3;
myVar = setInterval(changeSlide, 5000);
}
<div id="slideshow">
<div id="slide1">
<img src="/img/slide1.png" alt="" style="width:100%;height:100%;position:absolute;" id="slide1IMG">
</div>
<div id="selectors">
<a href="" onclick="firstSlide()">
<div id="left">
</div>
</a>
<a href="" onclick="secondSlide()">
<div id="middle">
</div>
</a>
<a href="" onclick="thirdSlide()">
<div id="right">
</div>
</a>
</div>
</div>
You are using links <a> tags, to handle your clicks, the page is reloading every time you click on one of them, on page reload, it will display the first slide. That is the expected behavior of href="".
The easiest solution is to change your <a> tags for <button> tags, though you could also catch the event and use event.preventDefault() to stop the page from reloading.
<button onclick="firstSlide()">
...
</button>
<button onclick="secondSlide()">
...
</button>
<button onclick="thirdSlide()">
...
</button>
Once you stop navigating away from the page, your code will be setting a new interval every time you handle the click, to avoid that, you could use a setTimeout() at the end of changeSlide(), instead of an interval, or clear the interval on your click handlers
function firstSlide() {
// Change the current slide
currentSlide = 1;
changeSlide();
// Reset the interval
clearInterval(myVar);
myVar = setInterval(changeSlide, 5000);
}
I would probaly rename myVar to something that makes it clear that it is the interval, like refreshSlideInterval.
You could also change the conditionals inside changeSlide to use strict comparisons
if (currentSlide == 1) {...}
to
if (currentSlide === 1) {...}
Since you know that you are working with integers.
Example snippet
const content = document.getElementById("content");
let currentSlide = 2;
let slideCountDown = setTimeout(changeSlide, 3000);
function changeSlide() {
// Clear the timeout
clearTimeout(slideCountDown);
if (currentSlide === 1) {
currentSlide = 2;
content.innerText = 1;
} else if (currentSlide === 2) {
currentSlide = 3;
content.innerText = 2;
} else {
currentSlide = 1;
content.innerText = 3;
}
// Reset the timeout
slideCountDown = setTimeout(changeSlide, 3000);
}
function firstSlide() {
currentSlide = 1;
changeSlide();
}
function secondSlide() {
currentSlide = 2;
changeSlide();
}
function thirdSlide() {
currentSlide = 3;
changeSlide();
}
#container {
display: flex;
flex-direction: column;
align-items: center;
}
#content {
font-size: 5rem;
padding: 2rem;
}
#buttons {
display: flex;
flex-direction: row;
}
<div id="container">
<div id="content">1</div>
<div id="buttons">
<button onclick="firstSlide()">
First
</button>
<button onclick="secondSlide()">
Second
</button>
<button onclick="thirdSlide()">
Third
</button>
</div>
</div>
The setInterval at each select function are not necessary.
According to the changeSlide function, change the currentSlide as follow.
function firstSlide() {
currentSlide = 3;
}
function secondSlide() {
currentSlide = 1;
}
function thirdSlide() {
currentSlide = 2;
}
check this (run the snippet below ) i fixed some syntax errors :
document.getElementById("left").style.opacity =1;
var currentSlide = 1;
var myVar = setInterval(function(){
return changeSlide()
}
,1000);
function changeSlide() {
if (currentSlide == 1) {
currentSlide++;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg';
document.getElementById("left").style.opacity =1;
document.getElementById("right").style.opacity =.5;
} else if (currentSlide == 2) {
currentSlide++;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Stellar_%289460796504%29.jpg/1024px-Stellar_%289460796504%29.jpg';
document.getElementById("middle").style.opacity =1;
document.getElementById("left").style.opacity =.5;
} else if(currentSlide==3){
currentSlide = 1;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg/1024px-Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg';
document.getElementById("right").style.opacity =1;
document.getElementById("middle").style.opacity =.5;
}
}
function firstSlide() {
currentSlide = 1;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
function secondSlide() {
currentSlide = 2;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
function thirdSlide() {
currentSlide = 3;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
<div id="slideshow">
<div id="slide1">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Stellar_%289460796504%29.jpg/1024px-Stellar_%289460796504%29.jpg" alt="" style="width:100%;height:100%;position:absolute;" id="slide1IMG">
</div>
<div id="selectors">
<a href="" onclick="firstSlide()">
<div id="left">
</div>
</a>
<a href="" onclick="secondSlide()">
<div id="middle">
</div>
</a>
<a href="" onclick="thirdSlide()">
<div id="right">
</div>
</a>
</div>
</div>
Hi I write this simple javascript slideshow cause I want to write my own slideshow in javascript. It automatically change the images by a set time interval. But when I try to click the backward and forward function the result is not accurate or the images are in order.
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = 0;
var count = images.length;
function slidingImages()
{
i = i % count;
document.banner.src = images[i];
i++;
}
function forward()
{
i = (i + 1) % count;
document.banner.src=images[i];
}
function backward()
{
if (i <= 0)
{
i = count - 1;
}
else
{
i--;
}
document.banner.src=images[i];
}
window.onload = function()
{
slidingImages(),setInterval(slidingImages, 3000)
};
<center>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<input type="button" value="«prev" onClick="backward()">
<input type="button" value="next»" onClick="forward()">
</center>
What is the solution so my slideshow would be accurate?
This will pause the automatic behavior when the mouse is within the red rectangle and continue in auto mode once the mouse is out of the red rectangle. The buttons of course work as expected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: -moz-fit-content; width: -webkit-fit-content; width: fit-content; border: 1px solid red; }
</style>
</head>
<body>
<section>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<fieldset id="control">
<input id="prev" type="button" value="◄">
<input id="next" type="button" value="►">
</fieldset>
</section>
<script>
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = -1;
var count = images.length;
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var control = document.getElementById('control');
var autoSlide;
window.onload = auto;
function auto() {
autoSlide = setInterval(fwd, 3000) };
function pause() {
clearInterval(autoSlide);
}
function fwd() {
if (i >= 0 && i < 2)
{
i += 1;
}
else
{
i = 0;
}
document.banner.src=images[i];
}
function rev() {
if (i > 0 && i <= 2)
{
i -= 1;
}
else
{
i = 2;
}
document.banner.src=images[i];
}
prev.addEventListener('click', function() {
rev();
}, false);
next.addEventListener('click', function() {
fwd();
}, false);
control.addEventListener('mouseover', function() {
pause();
}, false);
control.addEventListener('mouseout', function() {
auto();
}, false);
</script>
</body>
</html>
This the html:
<div id = "slideshow">
<div id="slideshowWindow">
<div class="slide"><img src="slideshow.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8185.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8211.jpg" alt="" /></div>
<div class="slide"><img src="OrganicSoilad.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8243.jpg" alt="" /></div>
<input style = "display: none;" value = "" id="hide"/>
</div>
Everything seems to work fine except for the prev() button. It just bugs out if you click it more than once. It gets all buggy. I'm relatively new to jquery and if anyone has any insight on how to stop the slider from sliding while on hover that would also be helpful.
the javascript:
$(document).ready(function() {
$(".content").mouseenter(function(){
$( ".arrows" ).fadeIn(100);
});
$('.content').mouseleave(function(){
$( ".arrows" ).fadeOut(700);
});
var currentPosition = 0;
var $hide = $('#hide');
$hide.val(currentPosition);
var slideWidth = 1140;
var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval;
var speed = 5000; slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
function changePosition() {
currentPosition = $('#hide').val();
if(currentPosition == numberOfSlides - 1)
{
currentPosition = 0; $hide.val(currentPosition);
} else {
currentPosition++; $hide.val(currentPosition);
}
moveSlide();
}
function moveSlide() {
$current = $('#slidesHolder').css('padding-left');
$current_num = $current.replace('px' , '');
$padding = $current_num;
$('#slidesHolder').animate({'paddingLeft': $padding});
/* alert($padding); */
/*alert($('#slidesHolder').css('padding-left')); */
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#media').html(currentPosition);
}
});
function next()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
++currentPosition; if(currentPosition > 4){currentPosition =0;}
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#hide').val(currentPosition)
$('#media').html(currentPosition);
}
function prev()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
$left = 1140;
if(currentPosition == 0)
{
currentPosition = 5;
}
else
{
if($('#slidesHolder').css('padding-left') == '1140px')
{
$left = $left + $left;
}
$('#hide').val(currentPosition);
$('#slidesHolder').animate({'paddingLeft' : $left});
if(currentPosition == 0)
{
currentPosition = 4;
}
else{
--currentPosition;
}
$('#hide').val(currentPosition);
$('#media').html(currentPosition);
}
}