Reputation: 393
I want, via jQuery, to get the background-image url, from the element i'm clicking on. The problem is that the divs are numbered, since I needed a way to have many different images. This is how they are numbered:
<div id="photoBackground photo1"></div>
<div id="photoBackground photo2"></div>
<div id="photoBackground photo3"></div>
<div id="photoBackground photo4"></div>
etc etc
I have this is jQuery right now:
$(document).ready(function() {
$('.photoBackground').click(function () {
var image = $(this).css('background-image');
// remove "url(" and ")" to get the url
image = image.replace('url(','').replace(')','');
$("#lightbox").css('background-image','url(' + image + ')');
})
});
How do I make it read from the numbered ids? Eg. photo1, photo2 etc?
Thanks!
Upvotes: 1
Views: 46
Reputation: 432
In CSS an ID should be unique. Make .photobackground a class and then do photo1, photo2, etc as the id. Then do the on click function
$('.photoBackground').on('click',function () {
var idIClickedOn = '#' + $(this).attr('id'); //this will give you the actual id of the element
var image = $(idIClickedOn ).css('background-image');
// remove "url(" and ")" to get the url
image = image.replace('url(','').replace(')','');
$("#lightbox").css('background-image','url(' + image + ')');
})
Upvotes: 0
Reputation: 171679
An element ID can't have a space in it.
Since your jQuery selector is already looking for a class photoBackground
change the html to following structure:
<div id="photo4" class="photoBackground"></div>
Then within click handler this.id
will be id of element that was clicked
$('.photoBackground').click(function () {
var id = this.id;
// do something with id and background
});
ID's must be unique, but class is used to group common elements with common class names
Upvotes: 1