Reputation:
I'm trying to implement a flip effect on multiple tiles every time a user clicks on it, its sort of the beginning of a dashboard type webpage. How do I make a click event work for multiple classes of the same name?
All of the tiles have the same class name but under different "box" divs, the jquery click event only seems to implement in the last tile added, while the other ones are kept static. I can't seem to figure whats causing this and I've been searching all over for an answer. This is the last revision of the click event code:
var i = 0,
abbrs = document.getElementsByClassName("tile"),
len = abbrs.length;
function addEvent(abbr) {
abbr.addEventListener("click", function(event) {
$(this).toggleClass("flip");
})
}
for (i; i < len; i++){
addEvent(abbrs[i]);
}
I can't seem to figure out where the root of the problem is.
Upvotes: 3
Views: 3480
Reputation: 87
Consider this Codepen for a pure javascript solution.
<p class="target">flip me</p>
<p class="target">flip me</p>
<p class="target">flip me</p>
.flipped {
color: red;
}
const targets = document.getElementsByClassName('target');
for (var i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function(){
this.classList.toggle("flipped");
})
}
Or consider this for a jQuery solution.
<p class="target">flip me</p>
<p class="target">flip me</p>
<p class="target">flip me</p>
.flipped {
color: red;
}
$('.target').on('click', function() {
$(this).toggleClass('flipped');
});
EDIT:
After looking at your given code I just realized that you position absolute divs via very large paddings which is not the correct way to do. Rather use top|right|bottom|left
for positioning (see here for docs). After changing the css your example works fully even with the messy javascript. Look here
Upvotes: 1
Reputation: 1178
I think that replacing the snippet you provided with this code should do it for you:
$(document).ready(function() {
$(".tile").click(function() {
$(".tile").toggleClass("flip");
});
});
Depending on where the code actually lives in your project, you might not need the $(document).ready()
event listener that wraps the "on click" event listener.
Upvotes: 0
Reputation: 4413
Note: here is the basic snippet that you need to do. by clicking all class listed call function to call show the effects. if you don't want to show effects then don't add class.
function callMe(){
if ($(this).hasClass('flip')){
$(this).removeClass('flip');//removes flip class
} else {
$(this).addClass('flip');//add flip class
}
}
$(".class1, .class2").click(callMe); //add classes here needs to give effects and call functions
.flip{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1">Class 1</div>
<span class="class2">Class 2</span>
Upvotes: 1