How to handle click events on a div

I have a dataset from a SQL database. These elements are displayed in multiple divs like:

 <?php
 $url = 'DataBase';

 $json_response = file_get_contents ( $url );

 $json_arr = json_decode ( $json_response, true );

 for($i = count ( $json_arr )-1; $i > 0;  $i--) {
 $json_obj = $json_arr [$i];


 echo '<div id="MyDIV">';
 echo $json_obj ['id'] ;
 echo $json_obj ['title'];  
 echo $json_obj ['article'];  
 echo '<button id="read_more_btn">Read more</button>';
 echo '</div>'
 }
 ?>

      

My problem is that I cannot handle the click events for the EACH div, so I cannot determine which element was clicked. I've been looking for a solution for quite some time, but I couldn't find anything. So my question is, how can I identify the element that was clicked?

EDIT I have no idea how I can dynamically assign an ID to a button

+3


source to share


3 answers


You can use attributes data

(presumably HTML5) to attach id as metadata to your div

s. Your PHP (note that I am adding attributes data-id

):

<?php
 $url = 'DataBase';
 $json_response = file_get_contents ( $url );
 $json_arr = json_decode ( $json_response, true );
 for($i = count ( $json_arr )-1; $i > 0;  $i--) {
   $json_obj = $json_arr [$i];
   echo '<div data-id="' . $json_obj['id'] . '">';
   echo $json_obj ['id'] ;
   echo $json_obj ['title'];  
   echo $json_obj ['article'];  
   echo '<button id="read_more_btn">Read more</button>';
   echo '</div>'
 }
 ?>

      

JS - simple click handler insertion using jQuery .data()

[docs] to get the data attribute:



$('div').click(function(e) {
    var id = $(this).data("id");
    alert(id);
});

      

JSFiddle Demo

+3


source


How about creating html in php, you are iterating over the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';

So now in html it will look like <div id="mydiv-1"> ... </div>


<div id="mydiv-2"> ... </div>


<div id="mydiv-3"> ... </div>


etc.

And then in Javascript you can access them the same way you would any tag.

$('#mydiv-1').click(function(e){
    console.log('a div was clicked');
    console.log($(this))
});

      



So, to assign listeners to each div

, you can loop

for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
     $('#mydiv-' + i).click(function(){ 

}

      

Make sure to add a container for all sections.

+2


source


Give each div a unique numeric class, so your jquery will be

$('div').click(function() {
    var item_id = $(this).attr("class");
    //do stuff here
});

      

or

$('div').click(function() {
    var item_id = this.className;
    //do stuff here
});

      

+1


source







All Articles