I have a series of image thumbnails in a page. They are created using css sprites.
<div class="galleryImg1"></div>
<div class="galleryImg2 featured"></div>
<div class="galleryImg3"></div>
I was originally using id="galleryImg1"
but changed to using class="galleryImg1"
because the images may appear in multiple places on the same page and i wanted to avoid duplicate ids.
I have a jQuery selector to attach click events to all of these classes.
$("[class^=galleryImg]").click(function() {
// how do i get 'galleryImg2' and '2' here?
}
What I'm wondering is if there is an easy way to find out the className beginning with 'galleryImg' that was clicked on. Will I have to use a regular expression or is there a 'cleverer' way?
(yes if i was using an #ID selector then I could just say 'this.id' but as mentioned I don't want to use IDs because I want to display multiple copies of the same image.)
As far as I know, you're going to need a pretty basic regular expression, like so:
$("[class^=galleryImg]").click(function(Event) {
var id = this.className.match(/galleryImg(\d+)/)[1];
console.log(id);
});
If you're particularly averse to this, though, you can use something like this, which won't validate but will Get The Job Done.
<div class="galleryImg1" image_id="1"></div>
<div class="galleryImg2 featured" image_id="2"></div>
<div class="galleryImg3" image_id="3"></div>
<script>
$("[class^=galleryImg]").click(function(Event) {
var id = $(this).attr('image_id');
console.log(id);
});
</script>
Since I am assuming you have full control over your HTML and you know that galleryImg class will always be followed by the ID I don't think a regular expression here is evil at all. Just go with it!
What I do is something like this:
<div class="galleryImg 1"></div>
<div class="galleryImg 2 featured"></div>
<div class="galleryImg 3"></div>
<script>
$(".galleryImg").click(function(Event) {
var Class = $(this).attr('class').split(" ");
var id = Class[1]
});
</script>
You could use a Regex, but using split and indexof will be understood by more programmers. Also for something so simple, maybe better to avoid Regex.
In the event handler use the jQuery normalized Event object:
$("[class^=galleryImg]").click(function(Event) {
var classAttribute=Event.target.className
var classes=classAttribute.split(" ");
for (var i=0;i<classes.length;i++)
{
if (classes[i].indexOf('targetClassNamePrefix')==0)
{
// This element has the required class, do whatever you need to.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With