Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How check if any link was clicked in a specific DIV?

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".

like image 591
Lucas Avatar asked Aug 24 '11 10:08

Lucas


People also ask

How do you check if a div has been clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

How do you check if a link has been clicked?

For websites, you can use Google Analytics. To do this, enable the analytics tools provided by Google and use their measurements to check all your clicked links arriving at the website. If you use marketing channels to mostly drive traffic to your website, this is a good place to start.

How do you check if a link has been clicked in JavaScript?

// get the element const element = document. getElementById('profile_title') // always checking if the element is clicked, if so, do alert('hello') element. addEventListener("click", () => { alert('hello'); }); One can solve the same problem using a variety of different strategies Javascript Check If Link Is Clicked.


2 Answers

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.

like image 97
Felix Kling Avatar answered Oct 21 '22 11:10

Felix Kling


use this to select the div and ahref you want.

 $('#second_menu a').click(function(){
    // This will select the a href's only in the second menu.
    // basically, in div id "#second_menu" select all "a" elements.
 });
like image 38
Anil Avatar answered Oct 21 '22 11:10

Anil