How to stop jQuery functions from executing multiple times in this case? - javascript

I am using jQuery with .load function to update count, however if the button is clicked so fast, it can be hacked. Also I can't use unbind as this makes the button unusable after the first click.
Here is the jQuery I use when button is clicked.
<script type="text/javascript">
$(function() {
// update "likes" of a post
$(".bubble-like a").click(function() {
var post_id = $(this).parent().parent().parent().attr('id');
var number = post_id.replace(/[^0-9]/g, '');
$(this).parent().parent().children('.bubble-count').children('span').fadeOut(200);
$(this).parent().parent().children('.bubble-like').fadeOut(200);
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/add_post_like.php?post_id=' + number);
});
// remove my like from a post
$(".bubble-unlike a").click(function() {
var post_id = $(this).parent().parent().parent().attr('id');
var number = post_id.replace(/[^0-9]/g, '');
$(this).parent().parent().children('.bubble-count').children('span').fadeOut(200);
$(this).parent().parent().children('.bubble-liked').fadeOut(200);
$(this).parent().parent().children('.bubble-unlike').fadeOut(200);
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/remove_post_like.php?post_id=' + number);
});
});
</script>
If I clicked on like too fast or vice versa, the load is executed more than once. I also explained that unbind does not help.
Any idea?
UPDATE
I am not sure if I am doing that correct, but it seems to resolve it in my case.. can anyone correct/make me wrong ?
I added this line to my click handlers
// update "likes" of a post
$(".bubble-like a").click(function() {
$(this).css({'display' : 'none'});
var post_id = $(this).parent().parent().parent().attr('id');
var number = post_id.replace(/[^0-9]/g, '');
$(this).parent().parent().children('.bubble-count').children('span').fadeOut(200);
$(this).parent().parent().children('.bubble-like').fadeOut(200);
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/add_post_like.php?post_id=' + number);
});
// remove my like from a post
$(".bubble-unlike a").click(function() {
$(this).css({'display' : 'none'});
var post_id = $(this).parent().parent().parent().attr('id');
var number = post_id.replace(/[^0-9]/g, '');
$(this).parent().parent().children('.bubble-count').children('span').fadeOut(200);
$(this).parent().parent().children('.bubble-liked').fadeOut(200);
$(this).parent().parent().children('.bubble-unlike').fadeOut(200);
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/remove_post_like.php?post_id=' + number);
});
I added this line to my loaded scripts add_post_like and remove_post_like:
$('.bubble a').show();
Now it seems to accept only one click.. Is that reliable?

You can disable the click event whenever the button is clicked til the end of loading process. Then activate the event after it's completed within the callback function.
gory details: http://api.jquery.com/load/
UPDATE:
I've made a quick example for you: http://jsfiddle.net/hvfc5/1/
As you click the button, it would firstly remove the event binding on the button, then bind it back again after the image loaded. But if you click it again after this, you'd figure that the event still can be unbinded, but it never comes back. It's because the image has been loaded, therefore the load() function won't even be triggered.
This is just a demo sample for you to understand how to manipulate things, you still need to customize your own version as demanded.

You can disable the button as it is clicked and enable on when other button is clicked like toggle e.g. When likes is clicked disable it and enable unlike and vice versa.

The one() function comes to mind.
http://api.jquery.com/one/

Yes: first action of button click would be disabling the button itself. That way, fast clicks are no longer possible. Of course, you,'d have to re-enable the button after the load.
Update
Sigh... It's all about teh codez right?
$(".bubble-like a").click(function() {
$(".bubble-like a").attr('disabled', 'disabled');
var post_id = $(this).parent().parent().parent().attr('id');
var number = post_id.replace(/[^0-9]/g, '');
$(this).parent().parent().children('.bubble-count').children('span').fadeOut(200);
$(this).parent().parent().children('.bubble-like').fadeOut(200);
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/add_post_like.php?post_id=' + number,
function(){
$(".bubble-like a").removeAttr('disabled');
});
});

$(".bubble-like a").click(function() {
var button = $(this);
$(this).wrap($('<button/>', {
"class" : "disButton",
disabled: true,
width: button.width()
}
)); // wrap the anchor with button with disabled property
...
..
$("#result-likes").load('<?php bloginfo('template_directory'); ?>/ajax/add_post_like.php?post_id=' + number, function() {
button.unwrap(); // remove the wrapping button
});
});
You have to right some css to make the button look like a simple text. For example,
button.disButton {
border: none;
background: transparent;
}
button.disButton a{
color: #ddd;
text-decoration: none;
}

Related

Getting clone() to only work onetime interchangebly

I am trying to get an image to move over to a separate box upon clicking and then to be removed with a remove button I have in my html. I figured out how to add the image upon clicking it then removing it upon clicking the remove button.
The issue I am having is: when I click the image itself, it should copy over to the right but it should only copy one time and then I must .remove() the image using the button before I can click it again so it appears once more. Right now the image appears over and over upon clicking. I tried using .stop() but that stops the function entirely, I need it to work interchangeably. How do I do this using jQuery?
JQUERY CODE:
$(document).ready(function(){
$("#john").click(function(){
var johnImage = $("#john").clone(false);
$("h2").html("John is in the box");
$("h2").css({ 'color': 'red'});
$("#johnbox").prepend(johnImage);
});
Check out the below code. You should be setting clicked to false again in your remove handler.
Here is the full code after I got your remove code.
$(document).ready(function () {
var clicked = false;
$("#john").click(function () {
if (!clicked) {
var johnImage = $("#john").clone(false);
$("h2").html("John is in the box");
$("h2").css({ 'color': 'red' });
$("#johnbox").prepend(johnImage);
clicked = true;
}
});
$("#removejohn").click(function () {
clicked = false;
$("#john").remove();
$("h2").html("Click John to put him in the Box");
$("h2").css({ 'color': 'black' });
});
});

Prevent anchor click after one click

I am facing one issue, I want to disable anchor click after one click. I have
on-click attribute set in my anchor tag. Below is my HTML
<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>
After I click "Verify" I am changing anchors text to "Verifying..." and one more thing I am trying to disable this anchor to avoid click in between the verification logic going on.
I have tried event.preventdefault() and also added disabled attribute to anchor.
But nothing works.
Please help!
If you were using jQuery for this you could have done this more easly.
Here we add a new class to a link to show that it has been clicked already. We check this when a click is made.
<a style="cursor:pointer;" id="someId">Verify</a>
$('#someId').on('click',function(){
//Check if button has class 'disabled' and then do your function.
if(! $(this).hasClass('disabled')){
$(this).addClass('disabled');
Myfuntion();
$(this).removeClass('disabled');
}
});
Here is a demo as to how it could be done using Javascript.
//Pass the event target to the function
function Myfuntion(elem) {
//If the element has no "data-status" attribute
if (!elem.getAttribute("data-status")) {
//Set attribute "data-status=progress"
elem.setAttribute("data-status", "progress");
//Change the text of the element
elem.textContent = "Verifying...";
//The setTimeout(s) below is only for the demp purpose
//Lets say, your verification process takes 4 seconds
//When complte
setTimeout(function() {
//Remove the attribute "data-status"
elem.removeAttribute("data-status");
//Notify the use that verification is done
elem.textContent = "Verified";
//Again, this is only for demo purpose
setTimeout(function() {
//User may verify again
elem.textContent = "Verify";
}, 1000);
}, 4000);
}
return false;
}
Link to the demo
There are plenty of ways to do this; one simple approach is to just redefine the function itself:
var myFunction = function() {
alert('clicked');
// do whatever your function needs to do on first click, then:
myFunction = function() { // redefine it
// to no-op, or to another action
alert('second click');
}
}
<a onclick="myFunction()">click me</a>

Reset Variable Flag to original state

When a user empties the cart it removes all items and the page reloads. The page will reload in order to reset the buttons that are activated (all buttons with .button class will reset to there original state) There should be a way to reset the buttons without needing to reload the page. Instead of the function preforming location.reload is there a function that can reset all flags to "99cents.png"
<script>
$(".button").on('click', function(){
var flag = $(this).data('flag');
simpleCart.add({
name : $(this).attr("data-product-id"),
price : .99,
quantity : (flag ? -1 : 1)
});
$(this).attr("src", flag ? "99cents.png" : "m99cents.png");
$(this).data('flag', !flag);
});
function reloadFunction() {
location.reload();
}
</script>
Store the original state in a data also. When reloadFunction is called, you can retrieve the state from this property and replace the source attribute.
In the html:
<img class="button" src="originalsrc.png" />
In the javascript:
$(function(){
$(".button").each(function(i,el)
{
var el = $(this);
el.data('flag-original', el.attr('src'));
});
});
function reloadFunction() {
$(".button").each(function()
{
var el = $(this);
el.text(el.data('flag-original'));
});
}
After some research on jquery I discovered there was a method I could use called .removeData(); with this I was able to achieve the desired task by adding a class called ".empty" to the empty cart button. Here is what I came up with that works:
$(".empty").on('click', function(){
$(".button").attr("src", "99cents.png");
$(".button").removeData();
});
.removeData() was able to clear out everything without needing to refresh the page!
Thank you!

jQuery animation skipped when clicking quickly

Please take a look at this jsfiddle
If you click on the divs on the top quickly enough, you'll find that eventually two divs end up appearing. I've had this problem with jQuery before as well. I just ended up disabling the buttons (or animation triggers) in that case, but I'm wondering if there is a more elegant solution to this.
Here is my jQuery code -
$(function () {
var _animDuration = 400;
$("#tabLists a").click(function () {
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function () {
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function () {
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
})
});
return false;
});
});
I'm using callbacks everywhere. I would like a solution that would queue up the animation rather than, not allow me to click
try this code with a check var:
$(function(){
var check = 1;
var _animDuration = 400;
$("#tabLists a").click(function(){
if(check == 1){
check = 0;
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function(){
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function(){
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
check = 1;
})
});
}
return false;
});
});
DEMO

jQuery doesn't recognize a class change

Ok, I have a edit button, when I press on it, it changes to "done" button.
It's all done by jQuery.
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.attr('class', 'icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});
When I press on a "edit" (".icon-pencil") button, its classes change to .icon-ok-sign (I can see in chrome console),
but when I click on it, no alert shown.
When I create a <span class="icon-ok-sign">press</span> and press on it, a alert displays.
How to solve it?
Try using $( document ).on( "click", ".icon-ok-sign", function() {...
Thats because you can not register click-events for future elements, you have to do it like this:
$(document).on('click', '.icon-ok-sign', function() {
alert('hey');
});
This method provides a means to attach delegated event handlers to the
document element of a page, which simplifies the use of event handlers
when content is dynamically added to a page.
Use following script:
$(document).on('click','.icon-ok-sign',function(){
alert("hey");
});
Try this:
$(".icon-pencil").click(function() {
var pencil = $(this);
var row = $(this).parent('td').parent('tr');
row.find('td').not(":nth-last-child(2)").not(":last-child").each(function() {
$(this).html("hi");
});
pencil.removeAttr('class').addClass('icon-ok-sign');
});
// save item
$(".icon-ok-sign").click(function() {
alert("hey");
});

Categories

Resources