How To Toggle Attribute In Jquery

In this blog post, we will learn how to toggle (add or remove) an attribute of an HTML element using jQuery. jQuery is a popular JavaScript library that simplifies the process of working with HTML documents, handling events, creating animations, and performing other common web development tasks.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. You will also need to include the jQuery library in your project. You can do this by adding the following script tag to the head of your HTML file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Toggle Attribute using jQuery

To toggle an attribute, we will create a custom jQuery function called toggleAttr(). This function will accept two parameters: the attribute name and the function callback to determine whether the attribute should be added or removed.

First, let’s create our custom function. Add the following code to your JavaScript file or inside a script tag in your HTML document:

$.fn.toggleAttr = function (attr, callback) {
    return this.each(function () {
        var $this = $(this);
        if (callback.call(this)) {
            $this.attr(attr, true);
        } else {
            $this.removeAttr(attr);
        }
    });
};

Now let’s create an example to demonstrate how to use this function. Consider the following HTML code that contains a button and a checkbox:

<button id="toggle-disabled">Toggle Disabled Attribute</button>
<input type="checkbox" id="checkbox" />

We will use our custom function to toggle the disabled attribute of the checkbox when the button is clicked. Add the following jQuery code to your JavaScript file or inside a script tag in your HTML document:

$("#toggle-disabled").on("click", function () {
    $("#checkbox").toggleAttr("disabled", function () {
        return !$(this).attr("disabled");
    });
});

In this example, we are using the toggleAttr() function to toggle the disabled attribute of the checkbox element with the ID checkbox. The callback function returns the negation of the current value of the disabled attribute. If the attribute is not present, it will be added, and if it is present, it will be removed when the button is clicked.

Conclusion

In this blog post, we have learned how to create a custom jQuery function to toggle an attribute of an HTML element. This function can be easily extended to handle different attributes and elements as needed. The ability to toggle attributes using jQuery can be helpful in various web development scenarios, such as changing the state of an element based on user interaction.