Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}
I've built a little carousel programme in vanilla JavaScript and it's working great, except when I visit another browser window and then come back to my carousel window.
The slides race past each other, as though they've been waiting to run while I've been elsewhere, until it reaches the slide it would have been at had I been watching the whole time, which often slides in from the wrong side. Then it settles down and continues to work as expected. This behaviour is the same in Chrome and Firefox.
The full code is on GitHub at https://github.com/lucywho/lightweight-carousel but this is the relevant section of the script:
const slide = document.querySelectorAll("#carousel .carousel-slide");
const dots = document.querySelectorAll("#dots .dot");
const total = slide.length;
let last = total - 1;
let i = 0;
let timer;
let isTransitioning = false;
timer = setTimeout(moveSlide, 5000);
function moveSlide(index) {
isTransitioning = true;
if (typeof index == "number") {
if (i === index) {
return;
} else {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i = index;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
}
} else if (i < last) {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i++;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
} else if (i === last) {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i = 0;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
}
timer = setTimeout(moveSlide, 7000);
}
document.addEventListener("transitionend", function(event) {
if (event.target.classList.contains("offscreen-left")) {
event.target.classList.remove("offscreen-left");
isTransitioning = false;
}
Am I right in thinking that the problem is something to do with the script continuing to run in the background even when the page is not displayed? And if so, how do I force JavaScript to pause? (I tried wrapping it all in a document.addEventListener("DOMContentLoaded", function(){} but that didn't help)
Many thanks in advance.
ETA: thanks to Andre, I've tried the following approach. Again, it runs happily when the page loads but I'm still getting a few seconds of weirdness when I return from another tab.
let screenVis = true;
if (screenVis) {
...
carousel code
...
}
document.addEventListener("visibilitychange", function() {
if (document.hidden === true) {
screenVis = false;
} else {
screenVis = true;
}
});
So, either I've mucked up my code (always possible) or something else is going on?
I have a code that works great for starting and pausing audio html5 player and it looks like this
i want to insert that the img of the player will too change on every click and what i wrote is this
<script>
function aud_play_pause4() {
var myAudio = document.getElementById("myAudio4");
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
</script>
<script>
function aud_play_pause5() {
var myAudio = document.getElementById("myAudio5");
if (myAudio.paused && document.getElementById("btn").src == "btnpause.png") {
myAudio.play();
document.getElementById("btn").src = "btn.png";
} else {
myAudio.pause();
document.getElementById("btn").src = "btnpause.png";
}
}
</script>
this is the fifth track ID
im checking the log but their is nothing wrong with the code
but what I saw that it changes the first track id and not the fifth
192.185.121.126/~vagabond/coral/ this is the link
Your IDs must be specific for each button (img)... you have "btn" as the ID for all your buttons (img).
So, when you call document.getElementById("btn") it is getting the first img (button).
I am currently modifying a web app for iPad. I am trying to attach an audio soundtrack to the image slideshow. I currently have the audio files playing when the user hits the slideshow navigation controls but I can't seem to figure out how to make the audio play when the slides have automatically started.
When the nextBg() function in my main.js file moves from the current background image to the next I want it to play the next audio file in the list. The play function is: playAudio(). How do I do this?
The codes and files I am currently working with are:
function nextBg() {
if(bgRunning) return false;
clearInterval(bgTimer);
if(!$('#bgImages li.active').is(':last-child'))
$('#bgImages li.active').removeClass('active').next().addClass('active');
else
$('#bgImages li.active').removeClass('active').parent().find('li:first-child').addClass('active');
runBg();
}
function playAudio(path){
if(audioSupport){
var isPlaying = !myAudio.paused;
var canPlayMp3 = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/mpeg');
var canPlayOgg = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/ogg; codecs="vorbis"');
if(canPlayMp3)
myAudio.src = path+'.mp3';
else if(canPlayOgg)
myAudio.src = path+'.ogg';
myAudio.removeEventListener('ended', arguments.callee, false);
myAudio.addEventListener('ended', audioAddEndedListener , false);
if(autoPlay || isPlaying)
{
myAudio.play();
$('#audioControls .pause').css('display','block');
$('#audioControls .play').css('display','none');
}else{
$('#audioControls .play').css('display','block');
$('#audioControls .pause').css('display','none');
}
}
}
function audioAddEndedListener()
{
if(loop){
this.currentTime = 0;
this.play();
}else{
this.removeEventListener('ended', arguments.callee, false);
setNextAudio();
path = $('#audioList li.active').html();
playAudio(path);
myAudio.addEventListener('ended', audioAddEndedListener, false);
}
}
http://platinum.megatron.co.nz/main.js
http://platinum.megatron.co.nz/kitchen/video.html
Just call your playAudio() method inside the playBg() method after you swap the image.
I'm using Three.js with the WebGL renderer to make a game which fullscreens when a play link is clicked. For animation, I use requestAnimationFrame.
I initiate it like this:
self.animate = function()
{
self.camera.lookAt(self.scene.position);
self.renderer.render(self.scene, self.camera);
if (self.willAnimate)
window.requestAnimationFrame(self.animate, self.renderer.domElement);
}
self.startAnimating = function()
{
self.willAnimate = true;
self.animate();
}
self.stopAnimating = function()
{
self.willAnimate = false;
}
When I want to, I call the startAnimating method, and yes, it does work as intended. But, when I call the stopAnimating function, things break! There are no reported errors, though...
The setup is basically like this:
There is a play link on the page
Once the user clicks the link, a renderer's domElement should fullscreen, and it does
The startAnimating method is called and the renderer starts rendering stuff
Once escape is clicked, I register an fullscreenchange event and execute the stopAnimating method
The page tries to exit fullscreen, it does, but the entire document is completely blank
I'm pretty sure my other code is OK, and that I'm somehow stopping requestAnimationFrame in a wrong way. My explanation probably sucked, so I uploaded the code to my website, you can see it happening here: http://banehq.com/Placeholdername/main.html.
Here is the version where I don't try to call the animation methods, and fullscreening in and out works: http://banehq.com/Correct/Placeholdername/main.html.
Once play is clicked the first time, the game initializes and it's start method is executed. Once the fullscreen exits, the game's stop method is executed. Every other time that play has been clicked, the game only executes it's start method, because there is no need for it to be initialized again.
Here's how it looks:
var playLinkHasBeenClicked = function()
{
if (!started)
{
started = true;
game = new Game(container); //"container" is an empty div
}
game.start();
}
And here's how the start and stop methods look like:
self.start = function()
{
self.container.appendChild(game.renderer.domElement); //Add the renderer's domElement to an empty div
THREEx.FullScreen.request(self.container); //Request fullscreen on the div
self.renderer.setSize(screen.width, screen.height); //Adjust screensize
self.startAnimating();
}
self.stop = function()
{
self.container.removeChild(game.renderer.domElement); //Remove the renderer from the div
self.renderer.setSize(0, 0); //I guess this isn't needed, but welp
self.stopAnimating();
}
The only difference between this and the working version is that startAnimating and stopAnimating method calls in start and stop methods are commented out.
One way to start/stop is like this
var requestId;
function loop(time) {
requestId = undefined;
...
// do stuff
...
start();
}
function start() {
if (!requestId) {
requestId = window.requestAnimationFrame(loop);
}
}
function stop() {
if (requestId) {
window.cancelAnimationFrame(requestId);
requestId = undefined;
}
}
Working example:
const timeElem = document.querySelector("#time");
var requestId;
function loop(time) {
requestId = undefined;
doStuff(time)
start();
}
function start() {
if (!requestId) {
requestId = window.requestAnimationFrame(loop);
}
}
function stop() {
if (requestId) {
window.cancelAnimationFrame(requestId);
requestId = undefined;
}
}
function doStuff(time) {
timeElem.textContent = (time * 0.001).toFixed(2);
}
document.querySelector("#start").addEventListener('click', function() {
start();
});
document.querySelector("#stop").addEventListener('click', function() {
stop();
});
<button id="start">start</button>
<button id="stop">stop</button>
<div id="time"></div>
Stopping is as simple as not calling requestAnimationFrame anymore, and restarting is to call it it again.
ex)
var pause = false;
function loop(){
//... your stuff;
if(pause) return;
window.requestionAnimationFrame(loop);
}
loop(); //to start it off
pause = true; //to stop it
loop(); //to restart it
var myAnim //your requestId
function anim()
{
//bla bla bla
//it's important to update the requestId each time you're calling reuestAnimationFrame
myAnim=requestAnimationFrame(anim)
}
Let's start it
myAnim=requestAnimationFrame(anim)
Let's stop it
//the cancelation uses the last requestId
cancelAnimationFrame(myAnim)
Reference
I played around with the tutorial of a 2D Breakout Game where they also used requestAnimationFrame and I stopped it with a simple return. The return statement ends function execution if the value of return is omitted.
if(!lives) {
alert("GAME OVER");
return;
}
// looping the draw()
requestAnimationFrame(draw);
I would suggest having a look at the requestAnimationFrame polyfill gibhub page. There are discussions about how this is implemented.
So, after doing some more testing, I've found out that it was, indeed, my other code that posed a problem, not the animation stopping (it was a simple recursion after all). The problem was in dynamically adding and removing the renderer's domElement from the page. After I've stopped doing that, for there was really no reason to do so, and included it once where the initialization was happening, everything started working fine.