Multiple buttons with onclick animations - certain ones not finishing setTimeout - javascript

I have three buttons with different onclick animations. On click, it adds the "active" class to start the CSS animation. And with setTimeout, it removes that class to remove the final state of the animation and so the button can be clicked again.
Unfortunately though, when you're quickly clicking on the buttons, certain buttons doesn't go through the setTimeout.
Not sure exactly what's going on but here's my js.
var i=0;
$('button').each(function(){
i++;
$('.btn-' + i).on('click', toggleBtn);
function toggleBtn() {
btn = this;
// btn = btn.querySelector(".btn-" + i);
btn.classList.add('active');
setTimeout(function () {
btn.classList.remove('active');
}, 3000)
}
});
Here's the codepen as well.
https://codepen.io/anon/pen/ZqJxZd
Thanks!

each time you click a different button, you lose the setTimeout reference.
one solution is to put the setTimeout in an external function, like this:
function stOut(btn) {
setTimeout(function () {
btn.classList.remove('active');
}, 3000)
}
and calls the function toggleBtn within its function stOut(btn) and passing btn as parameter

Related

How to make an action on first click and another action on second click

My goal is to move a div element to the right side of the page on the first click and move it back to the left if I click it again and so on. How can I do this in javascript?
As enhzfelp said in their comment, the best solution would be to create a css class which moves your element to the right side of the page and to add / remove it with javascript.
If your goal is actually to perform one action and on next event call perform another, you can simply change a variable whenever the event is called.
Example code:
let right = false;
someElement.on('click', () => {
right = !right;
if (right) moveRight();
else moveLeft();
});
function moveRight() { ... }
function moveLeft() { ... }
You can also do this
<script>
var clickCount = 0;
function checkClick() {
if ( clickCount % 2 == 0 ) {
alert("first click");
} else {
alert("Second click");
}
clickCount++
}
</script>
<button onclick="checkClick()">Click me</button>
So, as I understood, you want to make so on click, the div element move to the opositive direction of left or right.
You can make this with an event listener, that listens to the click event and execute whatever you want on every click.
document.addEventListener('click', function(event) {
// your code that executes on every click
});
This event listener listens the click on all your webpage, so if you want to only listen the click when the use click your div, you need to get the div. There are several ways, but I recomend you to add an id to the div.
<div id="iAmYourElement"></div>
And then get the element in JavaScript
const element = document.getElementById("iAmYourElement");
element.addEventListener('click', function(event) {
// your code that executes on every click
});
Now that we have the way to deal with the click event, let's talk about the code that goes inside the listener.
One way to do this is creating two CSS classes, one is your div on the left and another whe div on your right. So, if we need the element to be on the right, we add the right-class, and if we need the div to be to the left, we add left-class and remove right-class.
Final javascript code will looks like that:
const element = document.getElementById("iAmYourElement");
let isDivOnLeft = true;
element.addEventListener('click', function (event) { // executes if you click on the div
isDivOnLeft = !isDivOnLeft // We negate the value of isDivOnLeft, so if it was true, it will now be false and vice versa.
if (isDivOnLeft) {
elementToRight()
} else {
elementToLeft()
}
});
function elementToRight() {
element.classList.remove("left-class")
element.classList.add("right-class")
}
function elementToLeft() {
element.classList.remove("right-class")
element.classList.add("left-class")
}
Hmm,
my English is kinda weak so I'll try my best to explain.
Let's assume that we have a div with id moveable
<div id="moveable"></div>
And we have button
<button id="move">Move</div>
And our goal is to move the div to the right in the first click, and in the second click, we will move it back to the right.
let button = document.getElementById("move");
let div = document.getElementById("moveable");
button.addEventListener("click", function () {
const dataMovedAttribute = div.getAttribute("data-moved");
if (dataMovedAttribute && dataMovedAttribute === "true") {
div.setAttribute("data-moved", "false");
div.style.float = "left";
} else {
div.setAttribute("data-moved", "true");
div.style.float = "right";
}
});
Checkout this example:
https://codesandbox.io/s/vigilant-rosalind-176by

toggleClass for different functions

I guess this code does not work, because at DOM load jQuery caches its objects and bind the functions to them?
$('span.button.slide_out').on('click', function () {
$(this).toggleClass('slide_out').toggleClass('slide_in');
$('#testbox').slideDown();
});
$('span.button.slide_in').on('click', function () {
$(this).toggleClass('slide_out').toggleClass('slide_in');
$('#testbox').slideUp();
});
I know I could write this easily with slideToggle or something else, but I have to fire different actions on every first and every second click. How can I achieve this using the same selector (instead of creating two different selectors)?
JS FIDDLE
The binding is indeed done on DOM creation, but that doesn't have to be a problem in this case, it also means that the button is still clicked if it no longer has the slide_out class. Therefore you can reuse the same click event and check the current state to choose whether to slide up or down. For example:
$('.slide_out').on('click', function () {
if($(this).toggleClass('slide_out slide_in').hasClass('slide_in'))
$('#testbox').slideDown();
else
$('#testbox').slideUp();
});
Fiddle
You could use the solution from Event binding on dynamically created elements?, as suggested by https://stackoverflow.com/users/502381/juhana:
HTML:
<span class="button_container"><span class="button slide_out">Click me</span></span>
<div id="testbox">Whohoohoooo, I am slidiiing!<br><br><small>Hey… wait! Why I am not sliding up again?</small></div>
JS:
$('.button_container').on('click', '.slide_out', function () {
$(this).toggleClass('slide_out').toggleClass('slide_in');
$('#testbox').slideDown();
});
$('.button_container').on('click', '.slide_in', function () {
$(this).toggleClass('slide_out').toggleClass('slide_in');
$('#testbox').slideUp();
});
http://jsfiddle.net/ag3cpcfb/
But, in my opinion it would be better to make your code simpler by using slideToggle() and adjust your css classes:
HTML:
<span class="button">Click me</span>
<div id="testbox">Whohoohoooo, I am slidiiing!<br><br><small>Hey… wait! Why I am not sliding up again?</small></div>
JS:
$('.button').on('click', function () {
var $testbox = $('#testbox');
if ($testbox.is(':visible')) {
console.log('Click 1');
} else {
console.log('Click 2');
}
$(this).toggleClass('slide_in');
$testbox.slideToggle();
});
http://jsfiddle.net/k77ferjh/
But this fires "Click 1" all of the time if you repeatedly click on the button. If this is not an issue, fine, if it is, you can also use a number to keep track of your clicks:
JS:
var clicks = 0;
$('.button').on('click', function () {
clicks++;
if (clicks % 2 == 0) {
console.log('Slide out');
} else {
console.log('Slide in');
}
$(this).toggleClass('slide_in');
$('#testbox').slideToggle();
});
http://jsfiddle.net/k77ferjh/1/

First click will not work

The first click does not work but every click after does perfectly. Is there anything I'm doing wrong or is it the site? (I'm using JS Fiddle by the way)
$("a").click(function () {
var x = document.getElementsByTagName("a");
$(x).click(function () {
var y = this.parentElement.parentElement;
$(y).hide("slide", {
direction: "right"
}, 1000);
});
});
In your code the first click will register another click handler which is actually doing the work so when the first click happens there is no handler which is actually hiding the parent element.
Also here you are attaching a new click handler in each click of the anchor element.
Instead you can just add the hide logic in the first click handler itself like
$("a").click(function () {
$(this).parent().parent().hide("slide", {
direction: "right"
}, 1000);
});
Demo: Fiddle
On your first click, you are executing a function that adds another click listener, so it won't be executed until it is clicked again. Try something like this:
function yourFunction() {
var y = this.parentElement.parentElement; // this may have to be slightly modified - I'm not sure of the rest of your code
$(y).hide("slide", {
direction: "right"
}, 1000);
}
$("a").click(function () {
var x = document.getElementsByTagName("a");
$(x).click(yourFunction);
yourFunction(); // calling yourFunction here also ensures it's called on the first click
});
Edit: this is redundant. Arun P Johny has a much cleaner solution. This is what I get for staying up all night.

Prevent 'click' event from firing multiple times + issue with fading

Morning folks. Have an issue with a simple jQuery gallery i'm making. It lets the user cycle through a collection of images via some buttons and at the same time, rotates through these images on a timer. My problem is that the user is able to click the button multiple times which queues up the fade in animation and repeats it over and over, e.g. user clicks button 5 times > same image fades in/out 5 times > gallery moves to next image.
I've tried using:
$('#homeGalleryImage li a').unbind('click');
After the click event is fired and then rebinding:
$('#homeGalleryImage li a').bind('click');
After it's done but this simply removes the click event after pressing a button once and never rebinds to it?
I've also tried disabling the button via:
$('#homeGalleryImage li a').attr('disabled', true);
To no avail... ?
There is a secondary issue where if you manage to click a button while the image is in a transition, the next image appears 'faded' as if the opacity has been lowered? Very strange... Here is the code for button clicks:
var i = 1;
var timerVal = 3000;
$(function () {
$("#homeGalleryControls li a").click(function () {
var image = $(this).data('image');
$('#galleryImage').fadeOut(0, function () {
$('#galleryImage').attr("src", image);
});
$('#galleryImage').fadeIn('slow');
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(this).find('img').attr("src", "/Content/Images/Design/btn_checked.gif");
i = $(this).data('index') + 1;
if (i == 4) {
i = 0;
}
timerVal = 0;
});
});
Here is the code that cycles through the images on a timer:
//Cycle through gallery images on a timer
window.setInterval(swapImage, timerVal);
function swapImage() {
$('#galleryImage').fadeOut(0, function () {
var imgArray = ["/Content/Images/Design/gallery placeholder.jpg", "/Content/Images/Design/1.jpg", "/Content/Images/Design/2.jpg", "/Content/Images/Design/3.jpg"];
var image = imgArray[i];
i++;
if (i == 4) {
i = 0;
}
$('#galleryImage').attr("src", image);
$('#galleryImage').fadeIn('slow');
});
var currentButton = $('#homeGalleryControls li a img').get(i - 1);
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(currentButton).attr("src", "/Content/Images/Design/btn_checked.gif");
}
I realise it might be a better idea to use a plugin but I'm very new to jQuery and I'd like to learn something rather than using some ready made code.
Any help at all, is much appreciated.
Thankyou
You could always try adding something to the element to cancel the click event?
For example
$(".element").click(function(e) {
if ( $(this).hasClass("unclickable") ) {
e.preventDefault();
} else {
$(this).addClass("unclickable");
//Your code continues here
//Remember to remove the unclickable class when you want it to run again.
}
}):
In your case you could try adding a check on the click.
$('#homeGalleryImage li a').attr('data-disabled', "disabled");
Then inside your click event
if ( $(this).attr("data-disabled" == "disabled") {
e.preventDefault();
} else {
//Ready to go here
}
Edit
Here is a working example showing the element becoming unclickable. http://jsfiddle.net/FmyFS/2/
if you want to make sure that the registered event is fired only once, you should use jQuery's one :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using vanilly JS: https://codepen.io/loicjaouen/pen/gOOBXYq
// add a listener that run only once
button.addEventListener('click', once_callback, {capture: true, once: true});

Stop js slideshow caching amount of clicks

Does anyone know how to stop this slideshow from 'caching' the amount of clicks through the slides? If I click the arrows 10 times then 10 slides will slide through is there a way to stop this? Or alternatively if you click the opposite arrow for it to cancel the 'cached' clicks from the other?
http://www.switchonthecode.com/tutorials/jquery-creating-a-slideshow
Thanks!
Using the one() function will probably do what you are looking for. Adjust the code to the following:
$(document).ready(function(){
// The "one()" function means that this action is disconnected
// from the element once the action occurs. In other words, click
// it twice, and the second one does nothing.
$("#slideshow-previous").one("click", showPreviousSlide);
$("#slideshow-next").one("click", showNextSlide);
...
});
However just doing that isn't enough. We have to hook up the event handler again after the animation is finished. Use the callback function for animate():
function updateContentHolder()
{
...
$("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
$("#slideshow-previous").one("click", showPreviousSlide);
$("#slideshow-next").one("click", showNextSlide);
});
}
As was pointed out in the comments this has the problem of attaching showPreviousSlide and showNextSlide multiple times to whichever button was not pressed. You can remedy this by doing just a little more work:
function showPreviousSlide()
{
currentSlide--;
updateContentHolder($(this).attr("id"), showPreviousSlide);
updateButtons();
}
function showNextSlide()
{
currentSlide++;
updateContentHolder($(this).attr("id"), showNextSlide);
updateButtons();
}
...
function updateContentHolder(id, callback)
{
...
$("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000, function() {
$("#" + id).one("click", callback);
});
}
You could set a flag to true whenever an arrow is clicked something like isPending. Then check this whenever an arrow is clicked and if it is true, ignore the click. Then when the animation finishes set the flag back to false.

Categories

Resources