Reputation: 3
EDIT: I have the following code:
<div class="specificBlock" id="thevagabond">
<a class="intro"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs testing">
<a type="button" class="btn btn-success intro">Use</a>
</div>
</div>
<div class="specificBlock" id="thedog">
<a class="intro"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs testing">
<a type="button" class="btn btn-success intro">Use</a>
</div>
</div>
My issue is the following: I'd like to find a jQuery/JavaScript way to get the ID of the div from which the clicked 'a' class="intro" comes from.
The problem here is that if the first a
with class="intro"
is clicked on, I would need to use the closest div's ID.
But if I click on the second the closest div is not the right one - the closest would be then the div with class="testing"
, which I don't want.
Is there any way to do this?
Upvotes: 0
Views: 54
Reputation: 5081
$("a").on("click", function (e) {
$(this).parents("#thevagabond");
});
or as mentioned before #thevagabond
directly.
EDIT:
Depending on the new information (see comments below) heres a new solution.
You could either place the target URL for the iframe
in the href
of the a
or add an data-
attribute to either the a
or one of its parents.
HTML:
<div class="specificBlock" id="thevagabond" data-url="my/iframe/url">
<a class="intro"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs testing">
<a type="button" class="btn btn-success intro">Use</a>
</div>
</div>
<div class="specificBlock" id="thedog">
<a class="intro" href="my/iframe/url"><img src="images/blabla.png"/></a>
</br>
<div class="btn-group-xs testing">
<a type="button" href="my/iframe/url" class="btn btn-success intro">Use</a>
</div>
</div>
<iframe id="my-frame" src="" width="500" height="500" style="display:none" />
JavaScript/jQuery:
var $specificBlocks = $(".specificBlock"),
$thevagabond = $specificBlocks.filter("#thevagabond"),
$thedog = $specificBlocks.filter("#thedog"),
$iframe = $("#my-frame");
$thevagabond.on("click", "a", function (e) {
e.preventDefault();
$iframe.attr("src", $thevagabond.data("url"));
$iframe.show();
});
$thedog.on("click", "a", function (e) {
e.preventDefault();
var $t = $(this),
url = $t.attr("href");
$iframe.attr("src", url);
$iframe.show();
});
I would prefer the #thedog
option because the page that will be shown in the iframe will be also accessable for non JS users and search engines.
Upvotes: 0
Reputation: 287
ID should be unique, so you would do just $('#thevagabond')
. However, you probably need to use .parents(selector_here)
- check documentation.
If you really need ID, check this:
$('.specificBlock a').click(function(){
var id_that_you_looking_for = $(this).parents('.specificBlock').attr('id');
//code more
});
Upvotes: 1