Animate jQuery toggle only once per call - javascript

I have a pretty complex system with a few AJAX calls which render different templates into other templates in PHP.
One of these templates is a edit form for my entity. This form is rendered hidden into my website until a button was clicked, which will then fire a jQuery toggle() to switch out a part of my site for this edit form.
This works fine until the user is using the jQuery UI slider on my site.
What happens if the user navigates within the slider is that parts of my site will be reloaded with AJAX.
When the button for the toggle() then will be clicked the animation goes of as often as the slider was used (so if the slider was used 4 times the toggle will animate an switch out the 2 elements 4 times).
I debugged through it and couldn't find the mistake, i can't provide a jsFiddle which could rebuild the situation nor can i give access to the site. The click function will be fired only once, so i really can't explain why this is happening.
To mention is that i have 3 buttons which will trigger this event:
#poi_edit_ajax will be shown when the slider was used in the template which will be rendered per AJAX.
#poi_edit_first will be shown by first access to the site and nothing has been reloaded per AJAX.
#poi_edit_last will be shown so the user can come back from the edit view
The Javascript is the following:
$("#poi_edit_ajax").click(function(){
$(".toggle_edit").toggle('slow');
});
$("#poi_edit_first").click(function(){
$(".toggle_edit").toggle('slow');
});
$("#poi_edit_last").click(function(){
$(".toggle_edit").toggle('slow');
});
I don't think that somebody can give me a solution with just this information, but that's everything i can provide now, so my Question now is simply if it is possible to tell the toggle() function from jQuery to only run the animation ONCE PER CLICK.
I don't think that jQuery one() can be used for this, because so the click event could only be used once per pagevisit.
EDIT
According to the comment, i tried out if multiple event handlers will be registered within the AJAX calls, which is true.
The code to fix this is simple:
$("#comment_first").unbind("click").click(function(){
$('.toggle_information').toggle('slow');
});
$("#comment_last").unbind("click").click(function(){
$('.toggle_information').toggle('slow');
});
$("#comment_ajax").unbind("click").click(function(){
$('.toggle_information').toggle('slow');
});
I just need to unbind the Lister before bind it again, else they're gonna stuck and multiple Listeners will react to the click event!

You are probably binding the Click event multiple times (by loading javascript through the AJAX calls). Make sure you bind the Click handler (which triggers the toggle()) only once.
Take a look at this answer: https://stackoverflow.com/a/969011
A (slightly modified) quote from that answer, for quick reference:
function alertEvent() { alert("test"); }
$(".ajax").bind("click", alertEvent);
//When you want to ensure it won't happen twice...
$(".ajax").unbind("click", alertEvent);
$(".ajax").bind("click", alertEvent);
This method will only remove the event you specify

Related

Wordpress, Jquery, Toggle, Button, File Location, Code Location, Works only some of the time. Why?

I've got a wordpress site under my novice care (I'm an intern) and was asked to implement and a button that toggles a form. So I went digging. I found this tutorial http://www.davidtiong.com/create-toggle-shortcode-for-wordpress-using-jquery/
and used it to implement this --> http://www.hardwareclub.co/community/
The button, "request more info", works as it's supposed to when you go to the link as I just directed you to.
BUT if you get there from hardwareclub.co by using the top navigation menu the button no longer works.
What gives?
The same question can be asked about the hardwareclub.co/scale page.
jQuery(function($){
$(".toggle_container").hide();
$(document).on('click', "h3.trigger", function () {
$(this).toggleClass("active").next().slideToggle("normal");
return false; //Prevent the browser jump to the link anchor
});
});
I am not sure how familiar you are with Ajax and JQuery but basically when you click your menu links you are loading the page with Ajax and its preventing your JQuery to run. See this SO answer here. Here is a quote from that answer.
When you do an AJAX call, and replace a section of your page, you're
removing those elements with the event handlers bound to them and
replacing them with new elements. Even if those elements would now
match that selector they don't get the event handler bound because the
code to do that has already executed.
I believe you are having the same issue going on here which is why it works when the page is loaded normally but doesnt work when its loaded via Ajax.
You will need to set your JQuery click event for your form to use something like:
$(document).on('click', ".your-form-class", function () {
...
});
I dont know enough of your JQuery (since you didnt post any code) but im sure thats pretty much whats going on.

How to make all buttons(even dynamically created) in an application follow jquery button widget without calling .button() multiple times

I am new to stack overflow and this is my first question. Pardon me for any mistakes.
This question is more generic but i tried to search for an answer but could not find it.
Say i have a page and i am using jquery ui button() widget for all the button. What happens is i have a specific class defined for all the buttons on my page. So i can just specify $('.myButtonClass').button(); but whenever i render partial views which has button again i have to do the same thing in the partial views. Is there any way i can globally specify a transition for button or any element for that matter.
Here is a sample Fiddle which adds buttons on click. But the added buttons are not transitions as button widgets(I do not want to use clone).
http://jsfiddle.net/wjxn8/
$('.clsTest').button().click(function(){
$(this).after('<input type="button" value="Added" class="clsTest"/>');
});
Is this possible without:-
1) Adding the css classes for a button widget manually for all the buttons created.
2) Tracking DOM Changes using Javascript and perform transitions for all the button elements.
Thanks for your help!!!
Since you were looking for something else, why not trigger a custom event when you load partials or whatever:
$('.clsTest').button().click(function(){
$(this).after('<input type="button" value="Added" class="clsTest"/>').trigger('addButtonUI');
});
$(document).bind('addButtonUI',function(){
$('.clsTest').button();
});
http://jsfiddle.net/wJXN8/3/
If you trigger your event and have the document listening for it, then you can do whatever you would like. I could have put in there the ability to add more buttons as well, but this should get the point across.
What you are asking for, some event when a button is added.... you would need to come up with that yourself and trigger it when a button is added. There is this: How to detect new element creation in jQuery? which talks about a specific event that is triggered when new elements are added to the DOM. Haven't tested it, and it looks like it may not work on IE.
I'm not a huge fan of this, but you could poll for new buttons. Check out my fork of your fiddle (that sounds funny):
http://jsfiddle.net/lbstr/Hq97H/
Using your example, this would look like:
setInterval(function(){
$('.clsTest').not('.ui-button').button();
}, 1000);
As I said, I'm not a huge fan of this. I understand the desire for something like $.live here, but I still think its better to initialize your new content when you add it. If you are making an ajax call for new content, just initialize it when you add it to the DOM.
My silly polling code and $.live (which is now deprecated) might be convenient, but they perform terribly. Just my two cents. You know your code better than I do!

jquery $.getJSON repeats X times

I'm having trouble recreating the issue in jsbin without giving away project-specific details (I'm using JSON from an API), but I'm running into an issue that I can't seem to get around, and would really appreciate any help or insight.
I start with the following markup:
I have a blank unordered list.
<ul id="results-list">
<!-- it is blank for now, and will be populated via jQuery -->
</ul>
And also an input.
When that input has been submitted, I run some code to populate #results-list with data, based on a JSON response. All's well. In that population of the data, I embed links that go nowhere, to make it like a sidebar navigation (user clicks on a link, and the main content area's content changes accordingly). This works fine the first time around.
Then, I've got an anonymous function running inside of .live() for clicking on those links in #results-list.
$("#results-list a").live('click', function(){
// populate the main content area with the correct information.
});
Okay, so that works just perfectly the first time around. Once the user changes what's in the input, and resubmits the form, all of the items in the main content area change accordingly, but there are two of them. If they resubmit the form again, there are three. And so on.
So, the main content stuff is duplicated X times, with X being the number of times the form has been submitted.
I realize this is a somewhat vague question, but I wanted to see if anyone had any pointers as to what may be going on? This is all happening within a normal $.getJSON method call.
Any ideas?
If you call the live function after each post, jQuery will just keep adding event handlers to the DOM, so the handler will get called multiple times. To get round this, either just call the live function once, or if you have to set up event handlers after each post use unbind and then a bind function (i.e. bind or something more specific like click).

can I trigger click event onload

I am having anchor tag in my page. I like to trigger click event onload . Which means I wanna open this page "http://XXXXX.com" with new tab. Because I don't wanna popup blockers. Is there anyway to do this?
anchor attrs are given bellow
id="add_redirect"
href="http://XXXXX.com"
target="_blank"
Yeah, you can use a click event called onLoad(). Just use the setTimeout() method in jquery. It will call a click function without clicking it. Here is an example:
$("document").ready(function() {
setTimeout(function() {
$("#add_redirect").trigger('click');
},10);
});
This will work for you when the page start to load and the time delay is 10ms which is negligible.
Syntax has been corrected.
Try adding the following code in the page load
document.getElementById('add_redirect').click();
Using JQuery you can do that pretty easy. The earlier posted solution also work of course.
$(document).ready(function(){
$("#add_redirect").trigger('click');
});
TRY DEMO
If your goal is to bypass pop-up blockers on page load, triggering the click event synthetically probably won't work. Browsers are smart enough to know when a click is user-generated vs. when you've called the click function on the DOM element (on those browsers were that even works). Examples: http://jsbin.com/avibi3/3, http://jsbin.com/avibi3/4
Using jQuery's trigger mechanism certainly won't do it, because it doesn't really trigger a click event at all; it just fires the handlers that jQuery hooked up (edit: and, apparently, ones defined via an onclick attribute — see Sukhi's answer — but not ones attached via addEventListener). If that's what you want to do, Sukhi's answer shows you how, although I always say: If you want code to be run from two different places, put it in a function, and call that function from two different places (rather than putting it in a click handler and then simulating a click just to run the code). There are valid use cases for trigger (mostly relating to integrating with third-party scripts), but for running your own code from two different places, it's a symptom of a design problem.

Event bubbling jQuery .delegate() or .live() after click event

I've tried so many different possibilities to achieve what I feel like should be a simple code execution. I am loading DOM objects from the server via .load(). One of the loaded items is an input text box with a date in it. I want to load the jdpicker (a plugin datepicker) when I click on the input box. Due to the behavior of .live() and .delegate(), even when I use .die() or .undelegate() respectively, I can't get the popup datepicker to behave normally. It either pops up, allows me to click one object in the window and then immediately closes (I cannot navigate through the months, years without the window closing), or the window pops up and every subsequent click re-executes the code producing multiple instances of the datepicker.
I've tried different combinations of .live(), .delegate(), .one() with no luck. I've tested the datepicker in the main window and know that it works fine there. I could post code, but am not sure which of the ten different attempts I've made would be the best example. I can show my latest attempt.
Does anyone have a suitable example for this? Thanks!
Update
I've edited the code to read as follows:
$("#edit-entry").load("/edit/", { id:id }, function(){
$('.jdpicker').one('click', function(){
$(this).jdPicker();
});
});
This is hinging on becoming the complete answer. The datepicker is no longer calling multiple instances, which is good, but I still can't navigate it's controls (month, year selection). If I click the next month, it will load and close. The next time I click it, it re-opens on the next month. So, it does work, but is certainly not desirable. Any suggestions?
You just can't do that with "live" or "delegate". The fact of the matter is that you'll need to apply your plugin initialization explicitly after ".load()" succeeds.
edit — the change you've made is probably not going to work. Here's your code in English:
"Fetch content from the URL '/edit/' and deposit it into the element with id 'edit-entry'. When that content has been received, then bind a one-time event handler to the "click" function of all elements with class 'jdpicker'. In that event handler, set up the 'jdPicker' functionality for the element."
Instead, what you should be doing is just calling the jdPicker setup directly instead of setting it up so that the user has to click on the elements first.
$("#edit-entry").load("/edit/", { id:id }, function(){
$('.jdpicker').each(function(){
$(this).jdPicker();
});
});

Categories