How to toggle an attribute in jQuery

In jQuery 1.9 version toggle() function deprecated. New toggle() helps you to hide and show elements with animation and easing effects.

Now if you need a function for toggling an attribute value on click event, how you will do it because jQuery doesn’t provides any function for this. For doing this you can write your own function and can use it in same way you use any other jQuery function.

$.fn.toggleAttr = function(attrName, attrVal1, attrVal2) {
return this.each(function() {
var self = $(this);
if (self.attr(attrName) == attrVal1)
self.attr(attrName, attrVal2);
else
self.attr(attrName, attrVal1);
});
};

Now this function will helps you toggle any attribute.

Lets see an example

Suppose i am having an image in page

<img src=”myUrl/test1.jpg” alt=”img1″ title=”img1″ id=”img”>

Now suppose i need to change image to test2.jpg when some click on test1.jpg and the reverse one. So we can do it using above function like

$(function() {
$(‘#img’).click(function(){
$(‘#img’).toggleAttr(‘src’, ‘myUrl/test1.jpg’, ‘myUrl/test2.jpg’);
$(‘#img’).toggleAttr(‘alt’, ‘img1’, ‘img2’);
$(‘#img’).toggleAttr(‘title’, ‘img1’, ‘img2’);
});
});

Leave a comment