The best way to handle multi-click events

I am trying to perform some actions when clicking a link in my application.

For example, I am creating a guide containing several internal links within a document. Currently, I will handle them like this:

function waitForClick() { $('#about').click(function() { $('#container').slideDown(); }); $('#using').click(function() { changeContent... }); <!-- etc, etc --> } 

Is there a better way to handle multiple click events, so I don't need an event for every single item. I am sure there should be a way to delegate which item was clicked.

HTML:

 <li><a id="about" href="#">About this Application</a></li> <li><a id="using" href="#">Using this Manual</a></li> <li><a id="pages" href="#">Pages:</a></li> <!-- etc, etc --> 

This should be a table of contents for guidance. Thus, there will be many local links.

+4
source share
3 answers

Personally, I would use something like below. It allows you to avoid tons of events performed individually and scalable enough for your purpose. All you do is add a class "clickEventClasss" (or something that takes your imagination) to each element that needs to have an event, add an identifier so that you can recognize each.

 function waitForClick() { $('.clickEventClass').click(function() { var id = $(this).attr('id'); switch(id) { case 'about': //Logic break; case 'using': //Logic break; } }); } 
+1
source

You can bind click events to classes, not to identifiers.

 <a class="navigationLink" href="home.com">Home</a> <a class="navigationLink" href="about.com">About</a> <a class="navigationLink" href="contactus.com">Contact Us</a> $(".navigationLink").click(function() { //Do something cool }); 
+1
source

You can use the class you assign the click event to.

After this, the following is possible:

 $(".class").click(function() { if($(this).attr("id") == "about") { //code here } else if($(this).attr("id") == "using") { //code here } } 
0
source

All Articles