Reputation: 43
Hi i don't know how to change a div background image so here is the how it should work
I have some images with an onclick="change_color()" and some divs also with an onclick="get_color()", what i want is when i click the image i should get the image src and then after i click on the div that div will get the background image from the prev clicked image.
all i've managed to do is to get the image src
$(document).click(function(e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
$.lastClicked2 = e.target || e.srcElement;
});
function change_color()
{
var lastClickedElement = $.lastClicked;
lastClickedElement.getAttribute('data-color');
}
Please help me.
Upvotes: 0
Views: 8403
Reputation: 5212
Try something this:
$(function(){
var lastSrc = '';
$('img').on('click', function(){
lastSrc = $(this).attr('src');
});
$('div').on('click', function(){
$(this).css('background-image','url('+ lastSrc +')')
});
});
Upvotes: 1
Reputation: 318352
Drop the inline javascript, and add a class to the div's and images instead. I'll use .change_color
for the divs, .lastimage
for the images :
var bgImage = null;
$('img.lastimage').on('click', function() {
bgImage = this.src;
});
$('div.change_color').on('click', function() {
if (bgImage) $(this).css('background-image','url('+bgImage+')')
});
Upvotes: 3