Okay, basically, I want to create a button that triggers a new javascript function. I want the button to click and stay clicked (then click again to toggle off).
My code (without button):
function playSound(target) {
//Play the sound: play (src, interrupt, delay, offset, loop, volume, pan)
var instance = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_ANY, 0, 0, false, 1);
if (instance == null || instance.playState == createjs.Sound.PLAY_FAILED) { return; }
target.className = "gridBox1 active";
instance.addEventListener ("complete", function(instance) {
target.className = "gridBox1";
});
}
I want a clickable button to trigger a new set of sounds that loop, this is what I have come up with:
<button id="buttonEv" onclick="myFunction()">Evolve</button>
<script>
function myFunction() {
function playSound(target) {
//Play the sound: play (src, interrupt, delay, offset, loop, volume, pan)
var instance = createjs.Sound.play(1, {loop:2});
instance.on("loop", handleLoop);
if (instance == null || instance.playState == createjs.Sound.PLAY_FAILED) { return; }
target.className = "gridBox1 active";
instance.addEventListener ("complete", function(instance) {
target.className = "gridBox1";
});
}
}
$('#buttonEv').click(function(event){
if($(this).hasClass('active')){
$(this).removeClass('active')
} else {
$(this).addClass('active')
}
});
</script>
The button clicks and stays clicked, though not affecting the sounds
Make sense? Any ideas? Thanks!
Related
I'm using flickity, which is a bit irrelevant, and on first load and for each 'change' of a slide I'll search the slide for any videos that have audio enabled (set as a data attribute via PHP via CMS) and then it'll autoplay the video and if the user clicks an unmute button then it'll unmute and vice versa.
This worked fine going forward but going back once the mute button is clicked, the eventListener for the click will fire every time it's existed. I'm guessing the eventListener is being added to each time but I can't work out how to remove the eventListener.
Any help on how to prevent the muteButton.addEventListener('click') from being fired more than once?
//
playVideo = function(index) {
var videos, video, muteButton = null, hasAudio = false;
// Pause all other slide video content if it was playing
flkty.cells.forEach(function(cell, i) {
videos = cell.element.querySelectorAll('video.--autoplay');
videos.forEach(function(video) {
if (video !== null && typeof video !== 'undefined') {
if (!video.paused) {
video.pause();
}
}
});
});
// For current slide
if (index == flkty.selectedIndex) {
videos = flkty.selectedElement.querySelectorAll('video.--autoplay');
muteButton = flkty.selectedElement.querySelector('a.button__mute');
// If videos exist on the current slide
if (videos.length) {
videos.forEach(function(video, index) {
if (video !== null && typeof video !== 'undefined') {
video.play();
if (muteButton !== null && typeof muteButton !== 'undefined' && index == 0) { // Only fire this once per video (as mute = mute all)
console.log(muteButton);
muteButton.addEventListener('click', function(e) {
e.preventDefault();
console.log('clicked'); // TOFIX; fires multiple times
muteVideo(videos, video, muteButton, true);
});
}
}
return;
});
}
}
};
flkty.on('select', function(event, index) {
if (index === 0) {
playVideo(index);
return false;
}
});
flkty.on('change', function(index) {
playVideo(index);
});
//
muteVideo = function(videos, video, muteButton, hasAudio) {
console.log('hasAudio');
if (videos.length > 1) {
videos.forEach(function(video, index) {
if (video.muted == true) {
video.muted = false;
if (index == 0) {
$(muteButton).text('mute');
}
} else {
video.muted = true;
if (index == 0) {
$(muteButton).text('unmute');
}
}
});
} else {
if (video.muted == true) {
$(muteButton).text('mute');
video.muted = false;
} else {
$(muteButton).text('unmute');
video.muted = true;
}
}
};
Just use removeEventListener().
To remove event handlers, the function specified with the addEventListener() method must be an external function.
Anonymous functions, like yours, will not work.
As for only attaching it once: Just set a flag to be checked before adding the eventhandler in the first place.
Don't use removeEventListener() in this case. The real problem is that you are adding event listeners each time your playVideo() function is called. So the problem you should solve is to make sure you only add the event listeners once, probably when the page initializes or something.
Here is what I would do:
Extract the "add event listener code" into a separate function, addButtonListeners() by removing that piece of code from the playVideo(). Then call the addButtonListeners() once when your page is loaded.
I'm having an issue trying to hide a button I've created with p5.js:
var quit_button;
var pause = false;
function keyPressed() {
if (keyCode == '80') { // If p is pressed on the keyboard
if (pause === true) {
quit_button.hide()
pause = false;
} else {
pause = true;
}
}
}
function restart() {
quit_button.hide() // This isn't working
pause = false;
setup()
}
function setup() { //Start-up screen
createCanvas(600, 400);
}
function draw() {
background('#fae'); //This creates a new canvas
if (pause === true) {
quit_button = createButton('quit')
quit_button.position(300,200)
quit_button.mousePressed(restart)
text("Game has been paused. Press P to resume.", 100, 100)
} else {
}
}
When I run the code and press p to pause my snake game, the game pauses (as expected). However, if I press p to unpause or if I click 'quit', the quit button is still there.
If the game is paused, you're creating a new button every single frame. That's 60 buttons per second. So you have a bunch of buttons just sitting on top of each other. To see what I mean, right-click your button and click inspect element and look at all the buttons on your page.
So you need to make sure you only ever create one button. You can do this by checking whether quit_button has already been initialized, and if it has then skip the creation step:
if(!quit_button){
quit_button = createButton('quit')
}
You could also move this creation code to the beginning and then have it hidden by default.
I have multiple .player-button elements, each with its own audio.
The clicked element plays the audio, pauses the previously playing element and changes class to .playing.
The problem is that I need to click again on the .playing element to change it's class to .paused. That means that when I click another .player-button the paused one does not change its class to .paused as long as I don't click on it. That means if the user just clicks on the various elements, he will be seeing a whole bunch of nice pause icons!
Here is the FIDDLE: https://jsfiddle.net/VitoLattarulo/mdcan81n/14/
jQuery(document).ready(function($) {
$(".player-button").click(function(e) {
e.preventDefault();
var song = $(this).prev('audio').get(0);
if (song.paused) {
song.play();
$(this).addClass("playing");
$(this).removeClass("paused");
} else {
song.pause();
$(this).addClass("paused");
$(this).removeClass("playing");
}
});
document.addEventListener('play', function(e) {
var audios = document.getElementsByTagName('audio');
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] != e.target) {
audios[i].pause();
}
}
}, true);
});
I evidently need a way to merge the two functions together but I am still a newbie and cannot figure out how to do it.
I would really appreciate a lot any help! It's the last issue to solve before I can publish my first website ^_^
Since you're not using the classes to determine the button state and only using them for styling, I would just remove all paused and playing classes when any button is clicked then reset the classes as needed like this:
jQuery(document).ready(function($) {
$(".player-button").click(function(e) {
e.preventDefault();
var $this=$(this); // cache this
var song = $this.prev('audio').get(0);
$(".player-button").removeClass("paused playing");
if (song.paused) {
song.play();
$this.addClass("playing");
} else {
song.pause();
$this.addClass("paused");
}
});
document.addEventListener('play', function(e) {
var audios = document.getElementsByTagName('audio');
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] != e.target) {
audios[i].pause();
}
}
}, true);
document.addEventListener('ended', function(e) {
$(".player-button").removeClass("paused playing");
}, true);
});
Updated jsFiddle
I am trying to figure out how when the page loads the game is "paused" and the user has to hit enter to play and when the user does so the game starts.
Here are the current keystates to control the player when the game is active. I feel like I'm almost there (correct me if I'm wrong), but I just can't get what makes the canvas "pause" when the page is loaded and how to make it "play" when the enter button is pushed.
keystate = {};
document.addEventListener('enter', function(evt){
keystate[evt.keyCode] = true;
});
document.addEventListener('keydown', function(evt){
keystate[evt.keyCode] = true;
});
document.addEventListener('keyup', function(evt){
delete keystate[evt.keyCode];
});
I have two ways,
One simple, but not so nice
One hard, can be nice
The first ay is just alerting something with comfirm(text).
Here is the code for that way :
var gameBrightness = 10;
function pause() {
var pause = confirm("You paused the game, click 'OK' to continue your game and the other button to go to options");
if (pause == false) { //Didn't click on OK
var options = confirm("Click on 'Ok' to not change brigthness, but the other one to change the brightness to a random value");
if (options == true) { //Clicked on OK
ReDopause();
return;
}
else { //Didn't click on OK
brightness = Math.floor(Math.random() * 20);
document.getElementById("brightness").innerHTML = brightness;
ReDopause();
return;
}
}
}
var ReDopause = function() {
pause();
}
<button onclick="pause()">Pause</button>
<span id="brightness">brigthness : 10</span>
The second way I havn't made but it is in each movements or timers add an if statment. Like this:
var pause = false;
setInerval(tick, 100);
function tick() {
if (pause == false) {
....
}
}
At the bginnning you should have a canvas which isn't visible which is the pause menu. Here gow you do the CSS for that:
#pause {
display: none;
...
}
When you pause set pause to true, set your main canvas to document.getElementById("mainCanvas").style.display = "none" this will make the canvas dissapear but still with all it's drawings. Then show the pause canvas like this : document.getElementById("mainCanvas").style.display = "initial". The when "Continue" is clicked: set pause to false and to the contrary of this.
What I want to happen is... when the image 'x' is clicked i want it to change image then when it is clicked again i want it to change back so on and so fourth, however I only want this to happen on the second click.
So X is clicked & nothing happens,
Then when it is clicked again it changes images,
and then back after another click, and then it alternates back and forth after that,
until the page resets, then i want it to reset as well.
this is my code so far:
document.getElementById('x').onclick = function() {
var ClickedOnce = 0;
if (this.src == 'Media/Images/Other/SwitchUP.jpg') {
ClickedOnce + 1
}
if (this.src == 'Media/Images/Other/SwitchUP.jpg' && ClickedOnce > 1) {
this.src = 'Media/Images/Other/SwitchDOWN.jpg';
} else if ('Media/Images/Other/SwitchDOWN.jpg') {
this.src = 'Media/Images/Other/SwitchUP.jpg';
}
}
It looks like the reason this isn't working is because you are declaring the var ClickedOnce inside of a function. This means that it is a local variable inside that function that will be set to 0 every time that function is called. Therefore, the same thing will happen every time it is clicked.
Try declaring some variable outside of the function.
You can try something like this:
var wasClicked = false;
document.getElementById('x').onclick = function() {
if (!wasClicked) {
wasClicked = true;
return;
}
if (this.getAttribute("src") == 'Media/Images/Other/SwitchUP.jpg') {
this.setAttribute("src", 'Media/Images/Other/SwitchDOWN.jpg');
} else {
this.setAttribute("src", 'Media/Images/Other/SwitchUP.jpg');
}
}
Additionally, since you tagged this question with jQuery, here is a jQuery approach to it:
var wasClicked = false;
$(document).ready(function() {
$("#x").click(function() {
if (!wasClicked) {
wasClicked = true;
return;
}
if ($(this).attr("src") == "path/to/some/image") {
$(this).attr("src", "path/to/other/image");
} else {
$(this).attr("src", "path/to/some/image");
}
});
});