How to Toggle an Element Using jQuery

jquery logo.png

In this lesson I will show you how to toggle an element on and off using jQuery.

STEP 1

The first step is to include the jQuery library in your webpage as follows:

The above shows a simple HTML document with jQuery loaded at line 6 from the Google hosted library location. The is recommended over hosting jQuery on your own server.

STEP 2

The next step is to create an element that we can toggle on and off. In this example I will use a simple div element.

The div element has been given an id so that we can reference it within the jQuery code.

STEP 3

Next, we create a button that we will click to toggle the div element on and off.

The button has also been given an id so that it can easily be referenced. Note that we do not have to do this within this short codeblock since there is only one button. However, you would need some way of referencing this single button if you had multiple button instances on your page.

STEP 4

We now write the code to toggle the div element.

Line 8: once the page has loaded a function is run

Line 9: we target the element with id of 'toggleButton' (our button) and when it is clicked we run a function

Line 10: we target the element with an id of 'divToToggle' and toggle it on/off

DID YOU FIND THIS TUTORIAL USEFUL?

If you found this tutorial useful then leave a comment and make a donation of $2 to help pay for hosting of this page.