ohh2ahh
ohh2ahh

Reputation: 385

How to handle jQuery on click the right way?

I'm making a little web app with an Off Canvas menu where each item executes a specific function. My research with Google revealed that jQuery's .on("click", ... is better than the attr onclick("myFunction()"). The function will loads static data from the HTML file ("stored" in a hidden div) and dynamic data (JSON) with ajax into a div on the viewport.

So here's my question: I know there are lots of solutions to achieve something like this, but is this a "good and efficient" way? Maybe it's a silly question, but I'm in the progress of learning :) Thank you very much!

HTML

<ul>
    <li><a class="home" href="#">Home</a></li>
    <li><a class="credits" href="#">Credits</a></li>
</ul>

JavaScript (for static data)

$(".sidebar a").on("click", function(ev) {
    // get class from clicked menu item
    var sidebar_class = $(this).attr("class");

    // load static data from hidden div into .container
    // e.g. .credits would load .page-credits
    $(".container").html($(".page-"+sidebar_class).html());

    // hide sidebar again
    hideSidebar();
});

Upvotes: 0

Views: 123

Answers (2)

Mir
Mir

Reputation: 1613

The code you posted has nothing wrong, other valid alternatives are:

$(".sidebar a").click(function() { //you don't ned the ev and you can use the click() method that is the same of on("click"

$(".sidebar").on("click", "a", function() { //you have a single delegate listener for all as instead of one listener for each one.

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

For dynamic data (works with btw static ones), use delegation:

$(document).on("click",".sidebar a", function(ev) {
    // get class from clicked menu item
    var sidebar_class = $(this).attr("class");

    // load static data from hidden div into .container
    // e.g. .credits would load .page-credits
    $(".container").html($(".page-"+sidebar_class).html());

    // hide sidebar again
    hideSidebar();
});

Here i use document, but you should use the closest static container of dynamic contents.

Upvotes: 0

Related Questions