LEARN TO CODE

View Original

How to Toggle an Element Using jQuery

See this search field in the original post

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:

See this content in the original post

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.

See this content in the original post

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.

See this content in the original post

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.

See this content in the original post

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