Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on click of multiple elements in jquery?

I have:

<div id="d1">
   <div id="d2"></div>
   <div id="d3"></div>
   <div id="d4"></div>
</div>

What I want is in which ever of the above element is clicked call this function:

function clickedele(){
    alert("Ele clicked");
}

I tried these But none worked:

var mhele_1 = $('#d1');
var mhele_2 = $('#d2');
var mhele_3 = $('#d3');
var menu_ico =$('#d4');
$([menu_ico.get(0),mhele_1.get(0), mhele_2.get(0),mhele_3.get(0)]).on('click', function(){
    alert("Ele clicked");
});

or

$('#menu_ico,#d1, #d2,#d3').on()

or

$('#menu_ico').add('#d1').add('#d2').add('#d3').on()

But none worked

like image 720
Mr. Nobody Avatar asked May 17 '17 08:05

Mr. Nobody


1 Answers

Your selector #menu_ico does not point to the element the element ids are d1, d2 and d3 so combine the id selectors and bind click event handler.

$('#d2,#d3,#d4').on('click', function(){
    alert("Ele clicked");
});

$('#d2,#d3,#d4').on('click', function() {
  alert("Ele clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">
  <div id="d2">a</div>
  <div id="d3">b</div>
  <div id="d4">c</div>
</div>

UPDATE 1: If the elements are dynamically added then use event delegation.

// assumes `#d1` is not dynamically added,
// if yes then use any of it's ancestor present
$('#d1').on('click', '#d2,#d3,#d4', function(){
    alert("Ele clicked");
});

$('#d1').on('click', '#d2,#d3,#d4', function(){
    alert("Ele clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">
  <div id="d2">a</div>
  <div id="d3">b</div>
  <div id="d4">c</div>
</div>

FYI : Use your code within document ready handler to run after elements are loaded or add code at the end of the page.


UPDATE 2: The better approach would be using a common class for all elements and bind the handler to that.

$('.d').on('click', function() {
  alert("Ele clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">
  <div id="d2" class="d">a</div>
  <div id="d3" class="d">b</div>
  <div id="d4" class="d">c</div>
</div>
like image 103
Pranav C Balan Avatar answered Oct 05 '22 20:10

Pranav C Balan