How to change the url of the "background" property?

Asked

Viewed 571 times

6

I have this function that changes the src of an img:

window.document.images['img'].src = n_src;

<img src="" name="img"/>

But I wanted to change the background url of the style:

<div name="img" style="background: url()"></div>

How best to do this function?

2 answers

5

To change the background you can use this in Javascript:

document.querySelector("[name='img']").style.backgroundImage = 'url(...)';

The best thing would be to do that in CSS, but in answer to your question you should use it then:

element.style.backgroundImage = ...

Example: http://jsfiddle.net/5m47veLa/show/

  • I only had a doubt the link of my image came from another function that was n_src; how can I make this change?

  • @Josimara in that case you can do elemento.style.backgroundImage = 'url(' + n_src + ')';

  • I tried that way before I didn’t get it

  • Document.querySelector("[name='img']").elemento.style.backgroundImage = 'url('+n_src+')';

  • @Josimara what is inside n_src ? what gives alert(n_src);?

  • @Josimara withdraws elemento of that code you put on top... it should be just document.querySelector("[name='img']").style.backgroundImage = 'url('+n_src+')';

  • in n_src this is the link of an image

  • I’m not getting it yet, but in your example jsfiddle it worked.

  • If I put the image link right in there this going but if I put the +n_src+ no longer takes.

  • @Josimara, where are you leaving that variable? Can you put some more code on it so I can figure out where you are?

  • @josimara, did you try to remove the HTML style attribute as I recommended? If you have taken, copy and paste exactly how you created your variable in the question, please...

Show 6 more comments

5

Modify in this case using the following structure:

var n_src = 'http://arcticmonkeysbr.com/wp-content/uploads/2014/10/maxresdefault1.jpg';


document.querySelector("[name='img']").addEventListener('click', function() {
  this.style.backgroundImage = 'url(' + n_src + ')';
});
div {
  border: 2px solid #000;
  display: block;
  min-height: 100px;
  min-width: 100px;
}
<div name="img"></div>

OBS.: remove the style attribute from HTML, you may be having difficulty due to value override.

If you are not yet able, in the browser console type console.log(n_src) and comment exactly what value was returned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.