How toggle function works in jQuery? - javascript

Simple toggle function-
$('.simple').toggle(function () {
//-----------------
},
function () {
//------------------
});
});
The thing i am not getting about toggle function is-
when first function ends (toggle function(){}), then how it can toggle second function in code?
How toggle works actually?

"when first function ends (toggle function(){}), then how it can toggle second function in code?"
Without getting into the fine detail - which you can see for yourself in the jQuery.js file - the .toggle() function (removed in v1.9) works by binding a click handler to the specified element(s), storing a list of all of the functions that you pass as parameters, and remembering which function in the list should be executed next.
When you first click on the element in question this click handler calls your first function. When you click again it calls the next function in the list. When multiple clicks take it past the end of the list it goes back to the beginning.

This is how .toggle() works :
If a div is hidden using .hide() or using css (display:none), it will display that div. In opposite case, if div is being displayed on screen, it will hide it with display:none property.

Toggle hides and shows an element alternatively. The function inside toggle is called once the toggling is completed. If you want to use another toggle function you have to call that function inside the first function but you should mention the selector as well. May be this is what you are looking for
$('.simple').toggle(function(){
$('.simple').toggle();
});

In jQuery the toggle() method is used for two different purpose. Here is the details link of this method.http://api.jquery.com/?s=toggle one is for efeect and another is for bind two events at a time, which one is deprecated in version 1.8.

This was taken straight from the jQuery doc http://api.jquery.com/toggle-event/
Note: This method signature was deprecated in jQuery 1.8 and removed
in jQuery 1.9. jQuery also provides an animation method named
.toggle() that toggles the visibility of elements. Whether the
animation or the event method is fired depends on the set of arguments
passed.
The function basically worked in conjunction with a click handler. Internally, the code would just simply need to run the handler associated with the 1st, 2nd, [nth], click according to how many clicks had been receieved by the element it was bound to.
I would recommend not using this function.

Related

jQuery hover functions stacking on top of eachother

I have rows in a table containing buttons that when clicked, change the hover function of the tr element they are contained in. I just noticed that when I set the hover function it doesn't actually rewrite over the previous hover function, it just stacks on top of it. So when the hover event fires it calls the most recently set hover function as well as any previous ones that have been set. How can I reset the hover function each time I set it instead of stacking them?
As Mohit Bhardwaj mentioned, the solution is to use the jQuery unbind method.
Note that simply calling $("#id").unbind("hover") will not work. It must be in the form of
$("#id").unbind('mouseenter').unbind('mouseleave')
or more simply
$("#id").unbind('mouseenter mouseleave');
How do I unbind "hover" in jQuery?

How to remove on click from sorting table header

First time post although I've been following helpful advice from here for a while.
I've a table that is being sorted via some Jquery functions that I didn't build myself so not sure how it operates. If a header column is clicked it sorts the table by that column firtst up then down - standard stuff. I'd like to remove the sorting on the first column as this is a series of checkboxes and the sorting is interfering with the checkall function on a mobile.
I've tried using the following script. First to remove the sorting class, and then to try and remove the on click function. The class is being removed (so the javascript is working) but one can still click the header at which point a new class is assigned so this removeAttr isn't really working (which was the solution I'd found on this site).
<script>
!function ($) {
$(function(){
$('th:first-child').removeClass( "sorting" );
$('th:first-child').removeAttr('onclick');
})
}(window.jQuery)
</script>
Any help gratefully received. Many thanks, DomC
The reason the .removeAttr('onclick') doesnt work is because there is a global eventhandler, probably in some .js file (which is the proper place!). The onclick would be inline javascript, which is a no-no!
To get it out of the global eventhandler list, use jQuery's .off():
// this removes all functions bound on the 'click event
$('th:first-child').off('click');
Or, if you have an older version of jQuery, .unbind():
// this removes all functions bound on the 'click event (older jQuery example)
$('th:first-child').unbind('click');
Or, if you want only one function turned off:
// If ´otherFunction´ is bound to click aswell, it will remain working
$('th:first-child').off('click', functionname);
Or, remove ALL events (ie click, hover, resize):
// Or the big cleanup, this clears ALL functions from ALL events
$('th:first-child').off();
#Martijn answer will probably do what you want. But i am putting more details here.
It depends on how the events (click) are registered.
removing the class or onclick attribute from the first header cell may not help.
They may have been used for binding the onclick event to that element. But You need to unbind the event.
When a user clicks on the header cell, it triggers an event. There are methods binded to the events which gets executed on the trigger. There may be one or multiple such methods which gets executed on the event.
In this case the event is click.
To remove bindings for all the methods for click, you can use following -
$('th:first-child').off('click');
//For old Jquery Version as mentioned by #Matijn
//$('th:first-child').unbind('click');
If you wish to unbind a specific method -
$('th:first-child').off('click', reference_to_function);

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

How do you use the click event properly to call another function within the class?

I was confused on how to use the click event in order to call another function within the class.
$.fn.imageareaselect(image)
{
this.click(function(){
$.fn.pinpointImage.add(image);
});
}
The selector that is passed into this function is an image. I wan't to make it so when you click the image it calls that function.
jQuery's kinda funny about passing an HTML element when you'd expect a jQuery one. try using $(this) instead of this.
Also, jQuery functions like to take functions as params, but i'm not sure exactly what this code is trying to do now. The first "(image)" should probably be "= function(image)" instead.

JQuery - Appended Links don't work

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.
The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:
<a rel="itemPick" id="5|2" href="#">This is the link</a>
The JQUERY handler looks like:
$('a[rel=itemPick]').click(function () {
code here...
});
These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?
When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.
So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:
$('a[rel=itemPick]').live('click', function () {
//code here...
})
$('a[rel=itemPick]').live("click", function (){ code here... });
Do you bind the event after adding the links?

Categories