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’);
});
});

How to use HTML for jQuery dialog title

Latest version of jQuery UI doesn’t allow HTML as dialog title to avoid vulnerabilities. It only allows text. So if you want to show some icon or custom design for the title then you don’t have a way to do it from title property.

But we can do it by extending the dialog widget.

1st we will add an extra option to dialog property called titleIsHtml. We will set it as true if we want to use HTML for dialog title or false for text or even we can leave it so by default it will be text.

$(“#myDialog”).dialog({
        modal: true,
        title: “<div class=’widget-header widget-header-small’><h4 class=’smaller’><i class=’ic-file ‘></i> My Dialog</h4></div>”,
        titleIsHtml: true,
        autoOpen: false,
        width:800,
        height:’auto’
});

Now we are extending the dialog property like

$.widget(“ui.dialog”, $.extend({}, $.ui.dialog.prototype, {
        _title: function(title) {
            var $title = this.options.title || ‘&nbsp;’
            if( (“titleIsHtml” in this.options) && this.options.titleIsHtml == true )
                title.html($title);
            else title.text($title);
        }
}));

Here we are checking the titleIsHtml property of dialog, if it is set and true then we are setting dialog title using jQuery’s html() function which will allow to set HTML in dialog.

If titleIsHtml isn’t set or false then we are using jQuery’s text() function to set the title which will just put raw text as dialog title