Reputation: 23
Having issues with toggling a class on a targeted div. I have a set of boxes being displayed, each with a button inside. Clicking this button is supposed to reveal a second box within that box. However, each box has a unique ID and I need to show only the targeted one.
The issue is the log displays the targeted ID correctly, however the class is not being toggled. When inspecting on chrome I can manually add the .show class and it works just fine so I know it is not the CSS.
When I tested .style.display = "inline-block";
in place of .toggleClass("show");
the console now says the target is undefined.
I use .toggleClass("show");
with many other parts of my page without issue.
What is wrong with my jQuery that it won't apply the class .show
to the targeted ID?
Also: I know this can be achieved via CSS only, however I need more flex than that in the future.
PHP, HTML and CSS
<?php
i=0;
while(i<20){
i+1;
?>
<div class="box">
<a class="openButton" data-target="i">open hidden box</a>
<div class="hiddenBottom" id="i">stuff</div>
</div>
<?php ;} ?>
<style>
.box {
display: inline-block;
}
.hiddenBottom {
display: none;
}
.show {
display: inline-block;
}
</style>
Jquery
$(".openButton").on("click mouseover", function(){
$($(this).data("target")).toggleClass("show");
console.log($(this).data("target"));
});
Upvotes: 0
Views: 92
Reputation: 21672
To target an ID in jQuery, the syntax is:
$("#MyID")
In your example, data-target
is a number without a preceding #
, so if i
is 19, your selector is:
//i = 19
//$(this).data("target") = "19"
$($(this).data("target")) // $("19")
The above example, $("19")
, won't select anything because it doesn't have a #
.
You'll need to prepend a #
and concatenate if you're trying to select by ID, like so:
$("#" + $(this).data("target")) // $("#19")
Upvotes: 1