Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the image src using jQuery

I am trying to change the image src attribute using jQuery

jQuery("#imageID").attr('src','http://localhost:8080/images/1/myImage.png' ); 

using the above code i can change the src attribute, but when i try this:-

jQuery("#imageID").attr('src',jQuery("#imageBlock").css('background-image') ); 

i am unable to change the src.

provided

alert ( jQuery("#imageBlock").css('background-image') ); 

returns:

url(http://localhost:8080/images/1/myImage.png)

Edit #1 Just when i was about to accept the solution. I must say, almost all solution worked in FF. I tried:

  • slice(4,-1);
  • split("(")[1] > then replace ( ")" , "" );

I guess others will also work. But none of the solutions is working in IE. Reason being: while FF returns:

url(http://localhost:8080/images/1/myImage.png)

IE Returns:

url("http://localhost:8080/images/1/myImage.png")

^^ mind the quotes here

Now, what could be the generic way to set the src attr. Do i need to test the browser if it is IE or not?

This is the working code.

var src = "";     if ( jQuery.browser.msie ) {         src = jQuery("#imageBlock").css('background-image').slice(5,-2);             }else{         src = jQuery("#imageBlock").css('background-image').slice(4,-1);     }        jQuery("#imageID").attr('src', src ); 

I really don't like it :x. If there is another solution than this, then please let me know or else i will accept the slice solution straight away.

like image 629
Rakesh Juyal Avatar asked Feb 02 '10 10:02

Rakesh Juyal


People also ask

How to set image src jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.

How do I change my Onclick image in HTML?

The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS. I would name the images starting with bw_ and clr_ and just use JS to swap between them.


2 Answers

IMO, slice is more appropriate than substring or replace. Try this:

jQuery("#imageID").attr(     'src',     jQuery("#imageBlock").css('background-image').slice(4,-1) ); 

Here, you're slicing the string in between url( and ). See MDC on slice for a detailed description of the method.

like image 168
Andy E Avatar answered Sep 24 '22 05:09

Andy E


You need to extract the url part:

var backgroundImage = $("#imageBlock")     .css('backgroundImage')     .replace(/"/g,"")     .replace(/url\(|\)$/ig, ""); jQuery("#imageID").attr('src', backgroundImage); 
like image 38
Darin Dimitrov Avatar answered Sep 24 '22 05:09

Darin Dimitrov