user744587
user744587

Reputation:

error to change dynamically background url / image src

I am changing background:url('image-file') or img's src dynamically and it's doing as i expected but one problem i am getting when the file has space between the name e.g. file name.gif (Not loading) or file-name.gif (load successfully)

  var file-src = ../context/image file.jpg  /*not changing */
              /* ../context/image-file.jpg : changes   */

 if(this.is('img')){   /* 'this' is selecter */
    this.attr('src', file_src);
    }else{
    this.css('background','url('+ file_src +')');
    }

as far as i am not very sure why such files are not loading, i just try my best to find out the reason but i want to know if there could be any other reason.

Upvotes: 0

Views: 446

Answers (2)

Tran Dinh Thoai
Tran Dinh Thoai

Reputation: 702

You should cover filename by quote. Your code should be change to:

var file-src = '../context/image file.jpg';

this.css('background',"url('"+ file_src + "')");

Upvotes: 1

jfriend00
jfriend00

Reputation: 707696

URLs cannot have spaces in them. A space should be represented by a %20. You can use the encodeURI function to properly encode special characters.

Your javascript also doesn't look correct as strings must be quoted, but I'm assuming that's just a shortcut you took when posting.

Upvotes: 0

Related Questions