Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  69] [ 6]  / answers: 1 / hits: 24417  / 13 Years ago, wed, august 24, 2011, 12:00:00

In HTML code my page contains:



<div id=main_menu>
<a href=# id=login>Link1</a>
<a href=# id=logout>Link2</a>
</div>
<div id=second_menu>
<a href=# id=information>Link info</a>
<a href=# id=profile>My profile</a>
</div>
<div id=menu_oustide><a href=# id=something>Link1</a></div>


In jQuery if I want to check if the user clicked any link in page I use this code:



$('a').click(function() { 

// do something

});


How can I start a function if the user clicked only on links in specific div? I would like to have a function that starts if a user clicked any link only in div ID named main_menu AND second_menu, but not in menu_outside.


More From » jquery

 Answers
18

Depending on what exactly you want to do, you can bind the event handler to those links only, using the descendant [docs] and multiple [docs] selectors:



$('#main_menu a, #second_menu a').click(function() {
// link inside #main_menu or #second_menu
});


If you don't want to perform the same action for both, you have to bind the event handler individually.



You could also check dynamically whether the link is a descendant of any of these element, with closest [docs]:



$('a').click(function() {
if($(this).closest(#main_menu).length) {
// inside #main_menu
}
if($(this).closest(#second_menu).length) {
// inside #second_menu
}
//...
});


But that introduces an additional overhead.


[#90444] Tuesday, August 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;