Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS and JQuery: spaces inside image name break code of url()

I have a page that is supposed to display a larger version of an image when hovered over a thumbnail.

I have a 'div' with an ID and the JQuery code is as following:

$(document).ready(function(){

  $('img').hover(function() {

    var src = $("#im" + this.id).attr("src");
    $('#viewlarge').css('backgroundImage','url(' + src +')'); 
    return false;
  });

});

The images I use, are generated by a Ruby script that "generate" an image with a similar, yet different id. However, sometimes, photo's are uploaded that have "spaces" inside. My developer tools tell me that the background-image is not set correctly, yet the image path is correct and the browser don't have problems finding the image.

My question is, can I somehow sanitize the url 'src', so spaces won't be a problem? I am aware of doing this server side, yet I would like to know how to do this with JQuery/JS too.

Thanks!

like image 597
Shyam Avatar asked May 18 '10 10:05

Shyam


2 Answers

Spaces are not valid in a URI. They need to be encoded to %20.

You could src.replace(/ /g, '%20'), or more generally, encodeURI(src) to %-encode all characters that aren't valid in a URI. encodeURIComponent(src) is more common, but it would only work if the src was just a single relative filename; otherwise, it'd encode / and stop paths working.

However, the real problem is that the original img src is already broken and only working thanks to browser fixups correcting your error. You need to fix the Ruby script generating the page. You should be URL-encoding the filename before including it in the path; there are many more characters that can cause you problems than just space.

As Pekka said, you should also use quotes around the URL in the url(...) value. Whilst you can get away without them for many URLs, some characters would have to be \-escaped. Using double-quotes mean you can avoid that (no double-quotes can appear in a URL itself).

like image 143
bobince Avatar answered Oct 20 '22 00:10

bobince


Adding quotes around the URL should help:

  $('#viewlarge').css('backgroundImage','url("' + src +'")'); 

however, according to the W3C specs, white space must be escaped, so the URL encoding solution provided by @Andy E's head @bobince is the safest one.

like image 24
Pekka Avatar answered Oct 20 '22 01:10

Pekka