Kevin Kopf
Kevin Kopf

Reputation: 14210

jQuery - slashes replaced with blanks for no reason

I got a jquery code:

$('.image_thumb').click(function() {
 var big_image = $('.image_thumb').attr('src').replace('thumbs/','').replace('skin/','');
 alert(big_image);
   $('body').html('<div style="position: absolute; left: 0; top: 0; width: 100%; height:100%; background-color: #000000; background: url("..'+big_image+'") center center no-repeat;"></div>'
);
});

When I click an .image_thumb element, it first shows an alert, which is "images/work/1/image.png". But when the div loads, the url value in background looks like this: "images work 1 image.png" - all slashes are replaced with blanks. Could someone please explain what the heck? :)) Thanx.

Funny, but the following code works perfectly:

    $('.image_thumb').click(function() {
 var big_image = $('.image_thumb').attr('src').replace('thumbs/','').replace('skin/','');
 alert(big_image);
   $('body').html('<div style="position: absolute; left: 0; top: 0; width: 100%; height:100%; background-color: #000000;"><img src="'+big_image+'"></div>'
);
});

There is only one problem - that way I can't center the image (as I do not know the width and height), so I'm pretty much stuck with the first option.

Upvotes: 2

Views: 253

Answers (2)

scrowler
scrowler

Reputation: 24406

My solution is to put all of those properties except for the background-image into a class, create a div, assign the class to it and set the background-image property, then replace the body element with it (this is not a good idea by the way):

CSS:

.newElement {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    background-position: center center;
    background-repeat: no-repeat;
}

jQuery:

$('.image_thumb').click(function() {
    var big_image = $('.image_thumb').attr('src').replace('thumbs/','').replace('skin/','');
    alert(big_image);
    var newElement = $('<div></div>').addClass('newElement').css('background-image', 'url(../' + big_image + ')');
    $('body').replaceWith(newElement);
});

Fiddle

Upvotes: 1

Kevin Kopf
Kevin Kopf

Reputation: 14210

I found the solution myself and it was quite... um... silly:

$('.image_thumb').click(function() {
 var big_image = $('.image_thumb').attr('src').replace('thumbs/','');
 alert(big_image);
  $('body').html('<div style="position: absolute; left: 0; top: 0; width: 100%; height:100%; background: url('+big_image+') #000000 center center no-repeat;"></div>'
);
});

The double quotes in background:url() were interfering for some reason.

The other thing is, I had to remove .replace('skin/','') and not use the .. in the url() and now it all works perfectly fine.

Upvotes: 1

Related Questions