Clicking the button below will change the background colour of the element whose ID is "change_me" (the paragraph below), using the selector #change_me, just as in CSS. Clicking a second time will change it back again (a toggle). This example uses the jQuery .toggleClass() function to toggle a class on and off. The class rule can be as simple or as complex as we want, so spectacular changes to an element can be made without any additional JavaScript.
Here's the script that does the work:
<script type="text/javascript">
function makeChange(){
$("#change").toggleClass('change_me');
return false;
}
</script>
And the markup for the trigger button:
<form> <input type="button" value="Make Change" onclick="makeChange()" /> </form>
And the CSS rule that is toggled on and off:
.change_me {
background-color:#BADB35;
}
Duis sed ligula odio, sed posuere magna. Integer facilisis interdum hendrerit. Nunc eleifend tempus facilisis. Nunc mattis erat ut justo scelerisque sed convallis lorem ultricies. Proin convallis vehicula tincidunt. Fusce ac sapien et odio consectetur condimentum et id elit. Suspendisse potenti. Aliquam erat volutpat. Mauris sollicitudin aliquam lacus, sit amet commodo nisl ornare sed. In tristique, mauris at auctor gravida, tellus nibh dapibus elit, nec cursus purus nisl faucibus magna. Morbi feugiat pulvinar pretium.
Note that this method uses an event handler (the onclick attribute). This technique is no longer recommended because it does not completely separate the behaviour from the structure. The preferred option is to use unobtrusive JavaScript, referencing elements using selectors.