jQuery Buttons In Depth

jquery buttonThe button has been at the core of user interface design on the World Wide Web since it was first added to the HTML 2.0 specification in 1995. As web technologies have continued to evolve, it is increasingly common for a web application’s user interface to run in the visitor’s web browser, and not on the web server.

jQuery simplifies the scripting of user experiences. It improves the way you work with buttons and other components, and helps you to produce clear and consistent interfaces.

This article assumes that you have some familiarity with building web pages in HTML5. You can review the basics of HTML5 at Udemy. Beginners working with jQuery for the first time may also find it helpful to learn more about jQuery before continuing.

Adding Buttons to Web Pages

Traditionally, you add buttons to web pages using an input element. With HTML5, you can also use the newer “button” element.

The following example is a minimal HTML5 document with a reference to the jQuery library, and both types of button:

<!DOCTYPE html>
<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>jQuery Buttons In Depth – Example 1</title>
<script src=”https://code.jquery.com/jquery-2.1.0.min.js”></script>
</head>
<body>
<button type=”button” disabled>Button 1</button>
<input type=”button” value=”Button 2″ disabled />
</body>
</html>

The “disabled” attribute specifies that the button cannot be clicked, and should appear dimmed. It can be useful to add buttons to HTML in this state, to prevent users from clicking them before the whole document is loaded.

At this stage, even without the disabled attributes, clicking on either button would take no action. For something to happen, you need to add an event handler.

Enabling Buttons and Responding to Click Events

The best place to add event handlers and enable buttons is in jQuery’s $(document).ready() method, which runs only after the document has been fully loaded.

The code below waits until the document is fully loaded then adds a handler for the button’s “click” event. Finally, it removes the disabled attribute to enable the button. In this example, the button is targeted in the jQuery selector using its “id”.

<!DOCTYPE html>
<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>jQuery Buttons In Depth – Example 2</title>
<script src=”https://code.jquery.com/jquery-2.1.0.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#btn1”).click(function () {
alert(“Button 1 was clicked!”);
});
$(“#btn1”).removeAttr(“disabled”);
});
</script>
</head>
<body>
<button id=”btn1″ type=”button” disabled>Button 1</button>
</body>
</html>

In addition to the click event, there is the “dblclick” event, which fires when a user double-clicks an element. Click and dblclick do not work well together; as a general rule you should use one or the other, not both. In the example above, the click event handler could be replaced by:

$(“#btn1”).dblclick(function () {
alert(“Button 1 was double-clicked!”);
});

You will often need to prevent the user from clicking on a button while a long-running action is being executed. This is important when communicating with a web server or animating the UI.

This can be achieved by re-adding “disabled” to the button, and removing it after the action is complete:

$(“#btn1”).click(function () {
$(this).attr(“disabled”,”disabled”);

/* … */

$(“#btn1”).removeAttr(“disabled”);
});

Responding to Mouseenter, Mouseleave, and Hover Events

Your work will be much easier to understand if you can keep code separate from content and appearance. Even though it is possible to add handlers to create or customize rollover effects, cascading style sheets (CSS) are better suited to this.

CSS offers considerable control over the appearance of buttons, and the “:hover” pseudo-class can be used to change how a button looks when the mouse pointer is positioned over it. Learn more about CSS Development (with CSS3!) However, there are occasions when you may want to respond to these events in order to display additional context-sensitive information to the user.

In this next example, handlers are added for the “mouseenter” and “mouseleave” events on all three buttons. When the mouse pointer is positioned over a button, its “title” attribute is echoed in a text element under the buttons. When the mouse pointer moves away from a button, the contents of the text element are cleared.

<!DOCTYPE html>
<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>jQuery Buttons In Depth – Example 3</title>
<script src=”https://code.jquery.com/jquery-2.1.0.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“:button”).mouseenter(function () {
$(“#lbl”).text($(this).attr(“title”));
});
$(“:button”).mouseleave(function () {
$(“#lbl”).text(“”);
});
$(“#btn1, #btn2, #btn3”).removeAttr(“disabled”);
});
</script>
</head>
<body>
<button id=”btn1″ type=”button” title=”Function 1″ disabled>Button 1</button>
<button id=”btn2″ type=”button” title=”Function 2″ disabled>Button 2</button>
<button id=”btn3″ type=”button” title=”Function 3″ disabled>Button 3</button>
<p>
Help: <span id=”lbl”></span>
</p>
</body>
</html>

This example also shows two ways of selecting more than one button in jQuery:

  • Using “:button” to select all buttons in the document; all of those created with “button” elements or “input” elements.
  • Specifying more than one id by separating each value with a comma.

The mouseenter and mouseleave events are exclusive to Internet Explorer. However, jQuery automatically makes these events work in other web browsers.

For convenience, the method hover() can be used when it is desirable to specify both event handlers at the same time. Notice the comma separating the two handler functions.

$(“:button”).hover(
function () {
$(“#lbl”).text($(this).attr(“title”));
},
function () {
$(“#lbl”).text(“”);
}
);

Triggering Button Events

In some rare situations, it may be useful to simulate a click, dblclick, mouseenter, or mouseleave event programmatically. This can be done using the trigger() method of the target button.

In the code below, two buttons are defined in an HTML document. When “Button 2” is clicked, a message is displayed to the user. When “Button 1” is clicked, the click handler simulates a click event on “Button 2” by calling its trigger() method and specifying the name of the event to be fired.

<!DOCTYPE html>
<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>jQuery Buttons In Depth – Example 4</title>
<script src=”https://code.jquery.com/jquery-2.1.0.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#btn1”).click(function () {
$(“#btn2”).trigger(“click”);
});
$(“#btn2”).click(function () {
alert(“Button 2 clicked!”);
});
});
</script>
</head>
<body>
<button id=”btn1″ type=”button”>Button 1</button>
<button id=”btn2″ type=”button”>Button 2</button>
</body>
</html>

Triggering events in this way does not change the appearance of the button. However, if you customize styles or properties in the event handler of a button, then these changes will occur when triggering that handler.

Dynamically Creating Buttons

Sometimes it can be helpful to create buttons dynamically, instead of writing them in HTML. Without jQuery, the usual practice is to create a new button element in JavaScript. You can then set its properties, and append it to an existing element.

With jQuery, the process is similar. However, jQuery has a compact way of describing a new element and its properties:

$(‘<button/>’, {
id: “btn1”,
text: “Button 1”,
click: function () {
// click action
}
})

The selector “<button/>” creates a new, empty button element in memory. The properties of this button are set within braces – the name of the property, followed by a colon, and then the value. Multiple properties can be defined in one block by separating each property with a comma.

As the example shows, it is also possible to specify the event handlers using the same syntax.

At this point, the button has not been added to the document. You append it to an existing element using the appendTo() method. This can be combined with the button’s creation.

The following example populates the “toolbar” element with five generated buttons:

<!DOCTYPE html>
<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>jQuery Buttons In Depth – Example 5</title>
<script src=”https://code.jquery.com/jquery-2.1.0.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
for (i = 1; i <= 5; i++) {
$(‘<button/>’, {
id: “btn” + i,
text: i,
click: function () {
alert(‘Run function: ‘ + $(this).text());
}
}).appendTo($(“#toolbar”));
}
});
</script>
</head>
<body>
<div id=”toolbar”></div>
</body>
</html>

Considering jQuery UI

jQuery UI is a separate library built on top of jQuery. It contains a large number of coded interactions, widgets, and effects, to be used when designing client-side user interfaces for the web. Get started working with jQuery UI.

jQuery UI adds several predefined (but customizable) new types of button. The new options include

  • easy methods for adding icons to buttons;
  • toggle buttons;
  • modern radio buttons;
  • split buttons (buttons combined with drop-down lists);
  • and built-in support for toolbars.

There is nothing in jQuery UI that you cannot do using the approaches already mentioned. However, it is often safer to use a popular and well-tested library. If the functionality you need has already been written then using it can save you a lot of effort, and a lot of testing.