Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a CSS background URL be passed a dynamic query string, and if so, how?

Tags:

css

background

Is it possible to pass the url attribute a dynamical query string? E.g url( ./SOME_IMAGE_GENERATOR?image=1 ); where image varies?

I need this attribute to be set via JS:

$( "#elem" )[ 0 ].style.background = "url( ./renders/circuit.php?circuit=" + dirY + dirX + "&dims=1|1 )";

The link in the url points to a file, that generates and returns an image. The image is generated correctly, but not applied as backround.

Clarification

The image I want to put inside does not exist yet. It is generated and returned by the page circuits.php and depends on the arguments.

The background is well changed, if the image exists. I have noticed that unlike changin the src attribute of the img tag, while the argument creates a request by the browser, sends and recieves headers and info, the background does not.

I'd thought about sending a request to the circuit.php generator, make him save the image on the server and then, with setTimeout, change the background, but I cannot rely on a certain time for the generation.

That is the problem. Now, do you guys have any ideas how to overtake this?

like image 278
Michael Sazonov Avatar asked Dec 31 '25 22:12

Michael Sazonov


1 Answers

Are you using jQuery? This should be very easy to do.

Store the generated image url in a variable, and then use jQuery to change the CSS background image value, like so:

var imageUrl = "./renders/circuit.php?circuit=" + dirY + dirX + "&dims=1|1";
$('#myDiv').css('background-image', 'url(' + imageUrl + ')');

Here's a a jsfiddle demonstrating the concept. Click the div to see the background-image dynamically changed via JS. http://jsfiddle.net/DigitalBiscuits/F3PUy/2/

like image 84
OACDesigns Avatar answered Jan 03 '26 14:01

OACDesigns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!