MeltingDog MeltingDog - 10 months ago 27
jQuery Question

2nd function in toggle function not working

I want to toggle the width of an element on click of another.

I've used the script someone has made here:,css,js,output

and just replaced it with my own elements:

function a(el){
$(el).animate({width: "10%"}, 1500);
function b(el){
$(el).animate({width: "100%"}, 1500);

$("#mybtn").click(function() {
var el = $('#container');
return (el.t = !el.t) ? a(el) : b(el);

The first function (a) works fine and shrinks the element to 10% width. But the 2nd function doesnt work.

Would anyone know why?


The jQuery function doesn't return DOM nodes. It returns an object that contains a collection of DOM nodes.

var el = $('#container');

creates a new instance of an object which happens to contain a reference to the DOM node with an ID of container. Every time the function gets called, you get a brand new instance of el, which means your toggle can never toggle.

To fix this, you're going to want to store the toggle data on the DOM node.

Use the .data() method:

var t ='toggle');
if (t) {
} else {
}'toggle',  !t);