John Davidson

javascript - Fire click event once per (different) class

0 comments
Message:


I'm trying to have a click event fire on any tag with the same class only once.


I tried using '.one', although, it removes itself after the first class tag is clicked.


$(document).ready(function() {   
$(".dropdown").one('click', function() {
...
});
});

The code is bought in from another .php file on the same directory with some server information so there are multiple (no end) in the number of tags with the same class.


<div class = \"dropdown\" id=" . $row["name"] . "dropdown" . ">
<div>". $row["email"] . "</div>
<div>name:" . $row["name"] ."</div>
<div>". $row["email"] ."</div></div>
";

Any recommendations?



My Answer:
One way to achieve this is to use a flag to keep track of whether the click event has already been fired for a particular class. Here's an example:

javascript
$(document).ready(function() {
var clickedClasses = {};

$(".dropdown").on('click', function() {
var classId = $(this).attr('id');

if (!clickedClasses[classId]) {
// Your code here
console.log('Clicked on class: ' + classId);

// Set the flag to true for this class
clickedClasses[classId] = true;
}
});
});


In this code, we use an object `clickedClasses` to store the classes that have already been clicked. When a `.dropdown` element is clicked, we check if the flag for that class is false (indicating it hasn't been clicked before), then we execute the code inside the if statement and set the flag to true. This way, the click event will only fire once for each unique class.

Rate this post

4 of 5 based on 1150 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us